python_code
stringlengths 0
1.8M
| repo_name
stringclasses 7
values | file_path
stringlengths 5
99
|
---|---|---|
// SPDX-License-Identifier: GPL-2.0-or-later
/* L2TPv3 IP encapsulation support
*
* Copyright (c) 2008,2009,2010 Katalix Systems Ltd
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <asm/ioctls.h>
#include <linux/icmp.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/random.h>
#include <linux/socket.h>
#include <linux/l2tp.h>
#include <linux/in.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/udp.h>
#include <net/inet_common.h>
#include <net/tcp_states.h>
#include <net/protocol.h>
#include <net/xfrm.h>
#include "l2tp_core.h"
struct l2tp_ip_sock {
/* inet_sock has to be the first member of l2tp_ip_sock */
struct inet_sock inet;
u32 conn_id;
u32 peer_conn_id;
};
static DEFINE_RWLOCK(l2tp_ip_lock);
static struct hlist_head l2tp_ip_table;
static struct hlist_head l2tp_ip_bind_table;
static inline struct l2tp_ip_sock *l2tp_ip_sk(const struct sock *sk)
{
return (struct l2tp_ip_sock *)sk;
}
static struct sock *__l2tp_ip_bind_lookup(const struct net *net, __be32 laddr,
__be32 raddr, int dif, u32 tunnel_id)
{
struct sock *sk;
sk_for_each_bound(sk, &l2tp_ip_bind_table) {
const struct l2tp_ip_sock *l2tp = l2tp_ip_sk(sk);
const struct inet_sock *inet = inet_sk(sk);
int bound_dev_if;
if (!net_eq(sock_net(sk), net))
continue;
bound_dev_if = READ_ONCE(sk->sk_bound_dev_if);
if (bound_dev_if && dif && bound_dev_if != dif)
continue;
if (inet->inet_rcv_saddr && laddr &&
inet->inet_rcv_saddr != laddr)
continue;
if (inet->inet_daddr && raddr && inet->inet_daddr != raddr)
continue;
if (l2tp->conn_id != tunnel_id)
continue;
goto found;
}
sk = NULL;
found:
return sk;
}
/* When processing receive frames, there are two cases to
* consider. Data frames consist of a non-zero session-id and an
* optional cookie. Control frames consist of a regular L2TP header
* preceded by 32-bits of zeros.
*
* L2TPv3 Session Header Over IP
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Session ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Cookie (optional, maximum 64 bits)...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* L2TPv3 Control Message Header Over IP
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | (32 bits of zeros) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |T|L|x|x|S|x|x|x|x|x|x|x| Ver | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Control Connection ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Ns | Nr |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* All control frames are passed to userspace.
*/
static int l2tp_ip_recv(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
struct sock *sk;
u32 session_id;
u32 tunnel_id;
unsigned char *ptr, *optr;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel = NULL;
struct iphdr *iph;
if (!pskb_may_pull(skb, 4))
goto discard;
/* Point to L2TP header */
optr = skb->data;
ptr = skb->data;
session_id = ntohl(*((__be32 *)ptr));
ptr += 4;
/* RFC3931: L2TP/IP packets have the first 4 bytes containing
* the session_id. If it is 0, the packet is a L2TP control
* frame and the session_id value can be discarded.
*/
if (session_id == 0) {
__skb_pull(skb, 4);
goto pass_up;
}
/* Ok, this is a data packet. Lookup the session. */
session = l2tp_session_get(net, session_id);
if (!session)
goto discard;
tunnel = session->tunnel;
if (!tunnel)
goto discard_sess;
if (l2tp_v3_ensure_opt_in_linear(session, skb, &ptr, &optr))
goto discard_sess;
l2tp_recv_common(session, skb, ptr, optr, 0, skb->len);
l2tp_session_dec_refcount(session);
return 0;
pass_up:
/* Get the tunnel_id from the L2TP header */
if (!pskb_may_pull(skb, 12))
goto discard;
if ((skb->data[0] & 0xc0) != 0xc0)
goto discard;
tunnel_id = ntohl(*(__be32 *)&skb->data[4]);
iph = (struct iphdr *)skb_network_header(skb);
read_lock_bh(&l2tp_ip_lock);
sk = __l2tp_ip_bind_lookup(net, iph->daddr, iph->saddr, inet_iif(skb),
tunnel_id);
if (!sk) {
read_unlock_bh(&l2tp_ip_lock);
goto discard;
}
sock_hold(sk);
read_unlock_bh(&l2tp_ip_lock);
if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
goto discard_put;
nf_reset_ct(skb);
return sk_receive_skb(sk, skb, 1);
discard_sess:
l2tp_session_dec_refcount(session);
goto discard;
discard_put:
sock_put(sk);
discard:
kfree_skb(skb);
return 0;
}
static int l2tp_ip_hash(struct sock *sk)
{
if (sk_unhashed(sk)) {
write_lock_bh(&l2tp_ip_lock);
sk_add_node(sk, &l2tp_ip_table);
write_unlock_bh(&l2tp_ip_lock);
}
return 0;
}
static void l2tp_ip_unhash(struct sock *sk)
{
if (sk_unhashed(sk))
return;
write_lock_bh(&l2tp_ip_lock);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip_lock);
}
static int l2tp_ip_open(struct sock *sk)
{
/* Prevent autobind. We don't have ports. */
inet_sk(sk)->inet_num = IPPROTO_L2TP;
l2tp_ip_hash(sk);
return 0;
}
static void l2tp_ip_close(struct sock *sk, long timeout)
{
write_lock_bh(&l2tp_ip_lock);
hlist_del_init(&sk->sk_bind_node);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip_lock);
sk_common_release(sk);
}
static void l2tp_ip_destroy_sock(struct sock *sk)
{
struct l2tp_tunnel *tunnel = l2tp_sk_to_tunnel(sk);
struct sk_buff *skb;
while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL)
kfree_skb(skb);
if (tunnel)
l2tp_tunnel_delete(tunnel);
}
static int l2tp_ip_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_l2tpip *addr = (struct sockaddr_l2tpip *)uaddr;
struct net *net = sock_net(sk);
int ret;
int chk_addr_ret;
if (addr_len < sizeof(struct sockaddr_l2tpip))
return -EINVAL;
if (addr->l2tp_family != AF_INET)
return -EINVAL;
lock_sock(sk);
ret = -EINVAL;
if (!sock_flag(sk, SOCK_ZAPPED))
goto out;
if (sk->sk_state != TCP_CLOSE)
goto out;
chk_addr_ret = inet_addr_type(net, addr->l2tp_addr.s_addr);
ret = -EADDRNOTAVAIL;
if (addr->l2tp_addr.s_addr && chk_addr_ret != RTN_LOCAL &&
chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST)
goto out;
if (addr->l2tp_addr.s_addr) {
inet->inet_rcv_saddr = addr->l2tp_addr.s_addr;
inet->inet_saddr = addr->l2tp_addr.s_addr;
}
if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
inet->inet_saddr = 0; /* Use device */
write_lock_bh(&l2tp_ip_lock);
if (__l2tp_ip_bind_lookup(net, addr->l2tp_addr.s_addr, 0,
sk->sk_bound_dev_if, addr->l2tp_conn_id)) {
write_unlock_bh(&l2tp_ip_lock);
ret = -EADDRINUSE;
goto out;
}
sk_dst_reset(sk);
l2tp_ip_sk(sk)->conn_id = addr->l2tp_conn_id;
sk_add_bind_node(sk, &l2tp_ip_bind_table);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip_lock);
ret = 0;
sock_reset_flag(sk, SOCK_ZAPPED);
out:
release_sock(sk);
return ret;
}
static int l2tp_ip_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *)uaddr;
int rc;
if (addr_len < sizeof(*lsa))
return -EINVAL;
if (ipv4_is_multicast(lsa->l2tp_addr.s_addr))
return -EINVAL;
lock_sock(sk);
/* Must bind first - autobinding does not work */
if (sock_flag(sk, SOCK_ZAPPED)) {
rc = -EINVAL;
goto out_sk;
}
rc = __ip4_datagram_connect(sk, uaddr, addr_len);
if (rc < 0)
goto out_sk;
l2tp_ip_sk(sk)->peer_conn_id = lsa->l2tp_conn_id;
write_lock_bh(&l2tp_ip_lock);
hlist_del_init(&sk->sk_bind_node);
sk_add_bind_node(sk, &l2tp_ip_bind_table);
write_unlock_bh(&l2tp_ip_lock);
out_sk:
release_sock(sk);
return rc;
}
static int l2tp_ip_disconnect(struct sock *sk, int flags)
{
if (sock_flag(sk, SOCK_ZAPPED))
return 0;
return __udp_disconnect(sk, flags);
}
static int l2tp_ip_getname(struct socket *sock, struct sockaddr *uaddr,
int peer)
{
struct sock *sk = sock->sk;
struct inet_sock *inet = inet_sk(sk);
struct l2tp_ip_sock *lsk = l2tp_ip_sk(sk);
struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *)uaddr;
memset(lsa, 0, sizeof(*lsa));
lsa->l2tp_family = AF_INET;
if (peer) {
if (!inet->inet_dport)
return -ENOTCONN;
lsa->l2tp_conn_id = lsk->peer_conn_id;
lsa->l2tp_addr.s_addr = inet->inet_daddr;
} else {
__be32 addr = inet->inet_rcv_saddr;
if (!addr)
addr = inet->inet_saddr;
lsa->l2tp_conn_id = lsk->conn_id;
lsa->l2tp_addr.s_addr = addr;
}
return sizeof(*lsa);
}
static int l2tp_ip_backlog_recv(struct sock *sk, struct sk_buff *skb)
{
int rc;
/* Charge it to the socket, dropping if the queue is full. */
rc = sock_queue_rcv_skb(sk, skb);
if (rc < 0)
goto drop;
return 0;
drop:
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_INDISCARDS);
kfree_skb(skb);
return 0;
}
/* Userspace will call sendmsg() on the tunnel socket to send L2TP
* control frames.
*/
static int l2tp_ip_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct sk_buff *skb;
int rc;
struct inet_sock *inet = inet_sk(sk);
struct rtable *rt = NULL;
struct flowi4 *fl4;
int connected = 0;
__be32 daddr;
lock_sock(sk);
rc = -ENOTCONN;
if (sock_flag(sk, SOCK_DEAD))
goto out;
/* Get and verify the address. */
if (msg->msg_name) {
DECLARE_SOCKADDR(struct sockaddr_l2tpip *, lip, msg->msg_name);
rc = -EINVAL;
if (msg->msg_namelen < sizeof(*lip))
goto out;
if (lip->l2tp_family != AF_INET) {
rc = -EAFNOSUPPORT;
if (lip->l2tp_family != AF_UNSPEC)
goto out;
}
daddr = lip->l2tp_addr.s_addr;
} else {
rc = -EDESTADDRREQ;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
daddr = inet->inet_daddr;
connected = 1;
}
/* Allocate a socket buffer */
rc = -ENOMEM;
skb = sock_wmalloc(sk, 2 + NET_SKB_PAD + sizeof(struct iphdr) +
4 + len, 0, GFP_KERNEL);
if (!skb)
goto error;
/* Reserve space for headers, putting IP header on 4-byte boundary. */
skb_reserve(skb, 2 + NET_SKB_PAD);
skb_reset_network_header(skb);
skb_reserve(skb, sizeof(struct iphdr));
skb_reset_transport_header(skb);
/* Insert 0 session_id */
*((__be32 *)skb_put(skb, 4)) = 0;
/* Copy user data into skb */
rc = memcpy_from_msg(skb_put(skb, len), msg, len);
if (rc < 0) {
kfree_skb(skb);
goto error;
}
fl4 = &inet->cork.fl.u.ip4;
if (connected)
rt = (struct rtable *)__sk_dst_check(sk, 0);
rcu_read_lock();
if (!rt) {
const struct ip_options_rcu *inet_opt;
inet_opt = rcu_dereference(inet->inet_opt);
/* Use correct destination address if we have options. */
if (inet_opt && inet_opt->opt.srr)
daddr = inet_opt->opt.faddr;
/* If this fails, retransmit mechanism of transport layer will
* keep trying until route appears or the connection times
* itself out.
*/
rt = ip_route_output_ports(sock_net(sk), fl4, sk,
daddr, inet->inet_saddr,
inet->inet_dport, inet->inet_sport,
sk->sk_protocol, RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if);
if (IS_ERR(rt))
goto no_route;
if (connected) {
sk_setup_caps(sk, &rt->dst);
} else {
skb_dst_set(skb, &rt->dst);
goto xmit;
}
}
/* We don't need to clone dst here, it is guaranteed to not disappear.
* __dev_xmit_skb() might force a refcount if needed.
*/
skb_dst_set_noref(skb, &rt->dst);
xmit:
/* Queue the packet to IP for output */
rc = ip_queue_xmit(sk, skb, &inet->cork.fl);
rcu_read_unlock();
error:
if (rc >= 0)
rc = len;
out:
release_sock(sk);
return rc;
no_route:
rcu_read_unlock();
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
rc = -EHOSTUNREACH;
goto out;
}
static int l2tp_ip_recvmsg(struct sock *sk, struct msghdr *msg,
size_t len, int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
size_t copied = 0;
int err = -EOPNOTSUPP;
DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
struct sk_buff *skb;
if (flags & MSG_OOB)
goto out;
skb = skb_recv_datagram(sk, flags, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
err = skb_copy_datagram_msg(skb, 0, msg, copied);
if (err)
goto done;
sock_recv_timestamp(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
sin->sin_port = 0;
memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet_cmsg_flags(inet))
ip_cmsg_recv(msg, skb);
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
return err ? err : copied;
}
int l2tp_ioctl(struct sock *sk, int cmd, int *karg)
{
struct sk_buff *skb;
switch (cmd) {
case SIOCOUTQ:
*karg = sk_wmem_alloc_get(sk);
break;
case SIOCINQ:
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
*karg = skb ? skb->len : 0;
spin_unlock_bh(&sk->sk_receive_queue.lock);
break;
default:
return -ENOIOCTLCMD;
}
return 0;
}
EXPORT_SYMBOL_GPL(l2tp_ioctl);
static struct proto l2tp_ip_prot = {
.name = "L2TP/IP",
.owner = THIS_MODULE,
.init = l2tp_ip_open,
.close = l2tp_ip_close,
.bind = l2tp_ip_bind,
.connect = l2tp_ip_connect,
.disconnect = l2tp_ip_disconnect,
.ioctl = l2tp_ioctl,
.destroy = l2tp_ip_destroy_sock,
.setsockopt = ip_setsockopt,
.getsockopt = ip_getsockopt,
.sendmsg = l2tp_ip_sendmsg,
.recvmsg = l2tp_ip_recvmsg,
.backlog_rcv = l2tp_ip_backlog_recv,
.hash = l2tp_ip_hash,
.unhash = l2tp_ip_unhash,
.obj_size = sizeof(struct l2tp_ip_sock),
};
static const struct proto_ops l2tp_ip_ops = {
.family = PF_INET,
.owner = THIS_MODULE,
.release = inet_release,
.bind = inet_bind,
.connect = inet_dgram_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = l2tp_ip_getname,
.poll = datagram_poll,
.ioctl = inet_ioctl,
.gettstamp = sock_gettstamp,
.listen = sock_no_listen,
.shutdown = inet_shutdown,
.setsockopt = sock_common_setsockopt,
.getsockopt = sock_common_getsockopt,
.sendmsg = inet_sendmsg,
.recvmsg = sock_common_recvmsg,
.mmap = sock_no_mmap,
};
static struct inet_protosw l2tp_ip_protosw = {
.type = SOCK_DGRAM,
.protocol = IPPROTO_L2TP,
.prot = &l2tp_ip_prot,
.ops = &l2tp_ip_ops,
};
static struct net_protocol l2tp_ip_protocol __read_mostly = {
.handler = l2tp_ip_recv,
};
static int __init l2tp_ip_init(void)
{
int err;
pr_info("L2TP IP encapsulation support (L2TPv3)\n");
err = proto_register(&l2tp_ip_prot, 1);
if (err != 0)
goto out;
err = inet_add_protocol(&l2tp_ip_protocol, IPPROTO_L2TP);
if (err)
goto out1;
inet_register_protosw(&l2tp_ip_protosw);
return 0;
out1:
proto_unregister(&l2tp_ip_prot);
out:
return err;
}
static void __exit l2tp_ip_exit(void)
{
inet_unregister_protosw(&l2tp_ip_protosw);
inet_del_protocol(&l2tp_ip_protocol, IPPROTO_L2TP);
proto_unregister(&l2tp_ip_prot);
}
module_init(l2tp_ip_init);
module_exit(l2tp_ip_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("James Chapman <[email protected]>");
MODULE_DESCRIPTION("L2TP over IP");
MODULE_VERSION("1.0");
/* Use the values of SOCK_DGRAM (2) as type and IPPROTO_L2TP (115) as protocol,
* because __stringify doesn't like enums
*/
MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET, 115, 2);
MODULE_ALIAS_NET_PF_PROTO(PF_INET, 115);
| linux-master | net/l2tp/l2tp_ip.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* L2TPv3 IP encapsulation support for IPv6
*
* Copyright (c) 2012 Katalix Systems Ltd
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/icmp.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/random.h>
#include <linux/socket.h>
#include <linux/l2tp.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/udp.h>
#include <net/inet_common.h>
#include <net/tcp_states.h>
#include <net/protocol.h>
#include <net/xfrm.h>
#include <net/transp_v6.h>
#include <net/addrconf.h>
#include <net/ip6_route.h>
#include "l2tp_core.h"
struct l2tp_ip6_sock {
/* inet_sock has to be the first member of l2tp_ip6_sock */
struct inet_sock inet;
u32 conn_id;
u32 peer_conn_id;
struct ipv6_pinfo inet6;
};
static DEFINE_RWLOCK(l2tp_ip6_lock);
static struct hlist_head l2tp_ip6_table;
static struct hlist_head l2tp_ip6_bind_table;
static inline struct l2tp_ip6_sock *l2tp_ip6_sk(const struct sock *sk)
{
return (struct l2tp_ip6_sock *)sk;
}
static struct sock *__l2tp_ip6_bind_lookup(const struct net *net,
const struct in6_addr *laddr,
const struct in6_addr *raddr,
int dif, u32 tunnel_id)
{
struct sock *sk;
sk_for_each_bound(sk, &l2tp_ip6_bind_table) {
const struct in6_addr *sk_laddr = inet6_rcv_saddr(sk);
const struct in6_addr *sk_raddr = &sk->sk_v6_daddr;
const struct l2tp_ip6_sock *l2tp = l2tp_ip6_sk(sk);
int bound_dev_if;
if (!net_eq(sock_net(sk), net))
continue;
bound_dev_if = READ_ONCE(sk->sk_bound_dev_if);
if (bound_dev_if && dif && bound_dev_if != dif)
continue;
if (sk_laddr && !ipv6_addr_any(sk_laddr) &&
!ipv6_addr_any(laddr) && !ipv6_addr_equal(sk_laddr, laddr))
continue;
if (!ipv6_addr_any(sk_raddr) && raddr &&
!ipv6_addr_any(raddr) && !ipv6_addr_equal(sk_raddr, raddr))
continue;
if (l2tp->conn_id != tunnel_id)
continue;
goto found;
}
sk = NULL;
found:
return sk;
}
/* When processing receive frames, there are two cases to
* consider. Data frames consist of a non-zero session-id and an
* optional cookie. Control frames consist of a regular L2TP header
* preceded by 32-bits of zeros.
*
* L2TPv3 Session Header Over IP
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Session ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Cookie (optional, maximum 64 bits)...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* L2TPv3 Control Message Header Over IP
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | (32 bits of zeros) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |T|L|x|x|S|x|x|x|x|x|x|x| Ver | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Control Connection ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Ns | Nr |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* All control frames are passed to userspace.
*/
static int l2tp_ip6_recv(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
struct sock *sk;
u32 session_id;
u32 tunnel_id;
unsigned char *ptr, *optr;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel = NULL;
struct ipv6hdr *iph;
if (!pskb_may_pull(skb, 4))
goto discard;
/* Point to L2TP header */
optr = skb->data;
ptr = skb->data;
session_id = ntohl(*((__be32 *)ptr));
ptr += 4;
/* RFC3931: L2TP/IP packets have the first 4 bytes containing
* the session_id. If it is 0, the packet is a L2TP control
* frame and the session_id value can be discarded.
*/
if (session_id == 0) {
__skb_pull(skb, 4);
goto pass_up;
}
/* Ok, this is a data packet. Lookup the session. */
session = l2tp_session_get(net, session_id);
if (!session)
goto discard;
tunnel = session->tunnel;
if (!tunnel)
goto discard_sess;
if (l2tp_v3_ensure_opt_in_linear(session, skb, &ptr, &optr))
goto discard_sess;
l2tp_recv_common(session, skb, ptr, optr, 0, skb->len);
l2tp_session_dec_refcount(session);
return 0;
pass_up:
/* Get the tunnel_id from the L2TP header */
if (!pskb_may_pull(skb, 12))
goto discard;
if ((skb->data[0] & 0xc0) != 0xc0)
goto discard;
tunnel_id = ntohl(*(__be32 *)&skb->data[4]);
iph = ipv6_hdr(skb);
read_lock_bh(&l2tp_ip6_lock);
sk = __l2tp_ip6_bind_lookup(net, &iph->daddr, &iph->saddr,
inet6_iif(skb), tunnel_id);
if (!sk) {
read_unlock_bh(&l2tp_ip6_lock);
goto discard;
}
sock_hold(sk);
read_unlock_bh(&l2tp_ip6_lock);
if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb))
goto discard_put;
nf_reset_ct(skb);
return sk_receive_skb(sk, skb, 1);
discard_sess:
l2tp_session_dec_refcount(session);
goto discard;
discard_put:
sock_put(sk);
discard:
kfree_skb(skb);
return 0;
}
static int l2tp_ip6_hash(struct sock *sk)
{
if (sk_unhashed(sk)) {
write_lock_bh(&l2tp_ip6_lock);
sk_add_node(sk, &l2tp_ip6_table);
write_unlock_bh(&l2tp_ip6_lock);
}
return 0;
}
static void l2tp_ip6_unhash(struct sock *sk)
{
if (sk_unhashed(sk))
return;
write_lock_bh(&l2tp_ip6_lock);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip6_lock);
}
static int l2tp_ip6_open(struct sock *sk)
{
/* Prevent autobind. We don't have ports. */
inet_sk(sk)->inet_num = IPPROTO_L2TP;
l2tp_ip6_hash(sk);
return 0;
}
static void l2tp_ip6_close(struct sock *sk, long timeout)
{
write_lock_bh(&l2tp_ip6_lock);
hlist_del_init(&sk->sk_bind_node);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip6_lock);
sk_common_release(sk);
}
static void l2tp_ip6_destroy_sock(struct sock *sk)
{
struct l2tp_tunnel *tunnel = l2tp_sk_to_tunnel(sk);
lock_sock(sk);
ip6_flush_pending_frames(sk);
release_sock(sk);
if (tunnel)
l2tp_tunnel_delete(tunnel);
}
static int l2tp_ip6_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct sockaddr_l2tpip6 *addr = (struct sockaddr_l2tpip6 *)uaddr;
struct net *net = sock_net(sk);
__be32 v4addr = 0;
int bound_dev_if;
int addr_type;
int err;
if (addr->l2tp_family != AF_INET6)
return -EINVAL;
if (addr_len < sizeof(*addr))
return -EINVAL;
addr_type = ipv6_addr_type(&addr->l2tp_addr);
/* l2tp_ip6 sockets are IPv6 only */
if (addr_type == IPV6_ADDR_MAPPED)
return -EADDRNOTAVAIL;
/* L2TP is point-point, not multicast */
if (addr_type & IPV6_ADDR_MULTICAST)
return -EADDRNOTAVAIL;
lock_sock(sk);
err = -EINVAL;
if (!sock_flag(sk, SOCK_ZAPPED))
goto out_unlock;
if (sk->sk_state != TCP_CLOSE)
goto out_unlock;
bound_dev_if = sk->sk_bound_dev_if;
/* Check if the address belongs to the host. */
rcu_read_lock();
if (addr_type != IPV6_ADDR_ANY) {
struct net_device *dev = NULL;
if (addr_type & IPV6_ADDR_LINKLOCAL) {
if (addr->l2tp_scope_id)
bound_dev_if = addr->l2tp_scope_id;
/* Binding to link-local address requires an
* interface.
*/
if (!bound_dev_if)
goto out_unlock_rcu;
err = -ENODEV;
dev = dev_get_by_index_rcu(sock_net(sk), bound_dev_if);
if (!dev)
goto out_unlock_rcu;
}
/* ipv4 addr of the socket is invalid. Only the
* unspecified and mapped address have a v4 equivalent.
*/
v4addr = LOOPBACK4_IPV6;
err = -EADDRNOTAVAIL;
if (!ipv6_chk_addr(sock_net(sk), &addr->l2tp_addr, dev, 0))
goto out_unlock_rcu;
}
rcu_read_unlock();
write_lock_bh(&l2tp_ip6_lock);
if (__l2tp_ip6_bind_lookup(net, &addr->l2tp_addr, NULL, bound_dev_if,
addr->l2tp_conn_id)) {
write_unlock_bh(&l2tp_ip6_lock);
err = -EADDRINUSE;
goto out_unlock;
}
inet->inet_saddr = v4addr;
inet->inet_rcv_saddr = v4addr;
sk->sk_bound_dev_if = bound_dev_if;
sk->sk_v6_rcv_saddr = addr->l2tp_addr;
np->saddr = addr->l2tp_addr;
l2tp_ip6_sk(sk)->conn_id = addr->l2tp_conn_id;
sk_add_bind_node(sk, &l2tp_ip6_bind_table);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip6_lock);
sock_reset_flag(sk, SOCK_ZAPPED);
release_sock(sk);
return 0;
out_unlock_rcu:
rcu_read_unlock();
out_unlock:
release_sock(sk);
return err;
}
static int l2tp_ip6_connect(struct sock *sk, struct sockaddr *uaddr,
int addr_len)
{
struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr;
struct sockaddr_in6 *usin = (struct sockaddr_in6 *)uaddr;
struct in6_addr *daddr;
int addr_type;
int rc;
if (addr_len < sizeof(*lsa))
return -EINVAL;
if (usin->sin6_family != AF_INET6)
return -EINVAL;
addr_type = ipv6_addr_type(&usin->sin6_addr);
if (addr_type & IPV6_ADDR_MULTICAST)
return -EINVAL;
if (addr_type & IPV6_ADDR_MAPPED) {
daddr = &usin->sin6_addr;
if (ipv4_is_multicast(daddr->s6_addr32[3]))
return -EINVAL;
}
lock_sock(sk);
/* Must bind first - autobinding does not work */
if (sock_flag(sk, SOCK_ZAPPED)) {
rc = -EINVAL;
goto out_sk;
}
rc = __ip6_datagram_connect(sk, uaddr, addr_len);
if (rc < 0)
goto out_sk;
l2tp_ip6_sk(sk)->peer_conn_id = lsa->l2tp_conn_id;
write_lock_bh(&l2tp_ip6_lock);
hlist_del_init(&sk->sk_bind_node);
sk_add_bind_node(sk, &l2tp_ip6_bind_table);
write_unlock_bh(&l2tp_ip6_lock);
out_sk:
release_sock(sk);
return rc;
}
static int l2tp_ip6_disconnect(struct sock *sk, int flags)
{
if (sock_flag(sk, SOCK_ZAPPED))
return 0;
return __udp_disconnect(sk, flags);
}
static int l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr,
int peer)
{
struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr;
struct sock *sk = sock->sk;
struct ipv6_pinfo *np = inet6_sk(sk);
struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk);
lsa->l2tp_family = AF_INET6;
lsa->l2tp_flowinfo = 0;
lsa->l2tp_scope_id = 0;
lsa->l2tp_unused = 0;
if (peer) {
if (!lsk->peer_conn_id)
return -ENOTCONN;
lsa->l2tp_conn_id = lsk->peer_conn_id;
lsa->l2tp_addr = sk->sk_v6_daddr;
if (np->sndflow)
lsa->l2tp_flowinfo = np->flow_label;
} else {
if (ipv6_addr_any(&sk->sk_v6_rcv_saddr))
lsa->l2tp_addr = np->saddr;
else
lsa->l2tp_addr = sk->sk_v6_rcv_saddr;
lsa->l2tp_conn_id = lsk->conn_id;
}
if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL)
lsa->l2tp_scope_id = READ_ONCE(sk->sk_bound_dev_if);
return sizeof(*lsa);
}
static int l2tp_ip6_backlog_recv(struct sock *sk, struct sk_buff *skb)
{
int rc;
/* Charge it to the socket, dropping if the queue is full. */
rc = sock_queue_rcv_skb(sk, skb);
if (rc < 0)
goto drop;
return 0;
drop:
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_INDISCARDS);
kfree_skb(skb);
return -1;
}
static int l2tp_ip6_push_pending_frames(struct sock *sk)
{
struct sk_buff *skb;
__be32 *transhdr = NULL;
int err = 0;
skb = skb_peek(&sk->sk_write_queue);
if (!skb)
goto out;
transhdr = (__be32 *)skb_transport_header(skb);
*transhdr = 0;
err = ip6_push_pending_frames(sk);
out:
return err;
}
/* Userspace will call sendmsg() on the tunnel socket to send L2TP
* control frames.
*/
static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_txoptions *opt_to_free = NULL;
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct flowi6 fl6;
struct ipcm6_cookie ipc6;
int addr_len = msg->msg_namelen;
int transhdrlen = 4; /* zero session-id */
int ulen;
int err;
/* Rough check on arithmetic overflow,
* better check is made in ip6_append_data().
*/
if (len > INT_MAX - transhdrlen)
return -EMSGSIZE;
ulen = len + transhdrlen;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/* Get and verify the address */
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = READ_ONCE(sk->sk_mark);
fl6.flowi6_uid = sk->sk_uid;
ipcm6_init(&ipc6);
if (lsa) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6)
return -EAFNOSUPPORT;
daddr = &lsa->l2tp_addr;
if (np->sndflow) {
fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK;
if (fl6.flowlabel & IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (IS_ERR(flowlabel))
return -EINVAL;
}
}
/* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
lsa->l2tp_scope_id &&
ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL)
fl6.flowi6_oif = lsa->l2tp_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = READ_ONCE(sk->sk_bound_dev_if);
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
ipc6.opt = opt;
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, &ipc6);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (IS_ERR(flowlabel))
return -EINVAL;
}
if (!(opt->opt_nflen | opt->opt_flen))
opt = NULL;
}
if (!opt) {
opt = txopt_get(np);
opt_to_free = opt;
}
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
ipc6.opt = opt;
fl6.flowi6_proto = sk->sk_protocol;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi_common(&fl6));
if (ipc6.tclass < 0)
ipc6.tclass = np->tclass;
fl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel);
dst = ip6_dst_lookup_flow(sock_net(sk), sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (ipc6.hlimit < 0)
ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (ipc6.dontfrag < 0)
ipc6.dontfrag = np->dontfrag;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
lock_sock(sk);
err = ip6_append_data(sk, ip_generic_getfrag, msg,
ulen, transhdrlen, &ipc6,
&fl6, (struct rt6_info *)dst,
msg->msg_flags);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = l2tp_ip6_push_pending_frames(sk);
release_sock(sk);
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
txopt_put(opt_to_free);
return err < 0 ? err : len;
do_confirm:
if (msg->msg_flags & MSG_PROBE)
dst_confirm_neigh(dst, &fl6.daddr);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
static int l2tp_ip6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name);
size_t copied = 0;
int err = -EOPNOTSUPP;
struct sk_buff *skb;
if (flags & MSG_OOB)
goto out;
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len, addr_len);
skb = skb_recv_datagram(sk, flags, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
err = skb_copy_datagram_msg(skb, 0, msg, copied);
if (err)
goto done;
sock_recv_timestamp(msg, sk, skb);
/* Copy the address. */
if (lsa) {
lsa->l2tp_family = AF_INET6;
lsa->l2tp_unused = 0;
lsa->l2tp_addr = ipv6_hdr(skb)->saddr;
lsa->l2tp_flowinfo = 0;
lsa->l2tp_scope_id = 0;
lsa->l2tp_conn_id = 0;
if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL)
lsa->l2tp_scope_id = inet6_iif(skb);
*addr_len = sizeof(*lsa);
}
if (np->rxopt.all)
ip6_datagram_recv_ctl(sk, msg, skb);
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
return err ? err : copied;
}
static struct proto l2tp_ip6_prot = {
.name = "L2TP/IPv6",
.owner = THIS_MODULE,
.init = l2tp_ip6_open,
.close = l2tp_ip6_close,
.bind = l2tp_ip6_bind,
.connect = l2tp_ip6_connect,
.disconnect = l2tp_ip6_disconnect,
.ioctl = l2tp_ioctl,
.destroy = l2tp_ip6_destroy_sock,
.setsockopt = ipv6_setsockopt,
.getsockopt = ipv6_getsockopt,
.sendmsg = l2tp_ip6_sendmsg,
.recvmsg = l2tp_ip6_recvmsg,
.backlog_rcv = l2tp_ip6_backlog_recv,
.hash = l2tp_ip6_hash,
.unhash = l2tp_ip6_unhash,
.obj_size = sizeof(struct l2tp_ip6_sock),
.ipv6_pinfo_offset = offsetof(struct l2tp_ip6_sock, inet6),
};
static const struct proto_ops l2tp_ip6_ops = {
.family = PF_INET6,
.owner = THIS_MODULE,
.release = inet6_release,
.bind = inet6_bind,
.connect = inet_dgram_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = l2tp_ip6_getname,
.poll = datagram_poll,
.ioctl = inet6_ioctl,
.gettstamp = sock_gettstamp,
.listen = sock_no_listen,
.shutdown = inet_shutdown,
.setsockopt = sock_common_setsockopt,
.getsockopt = sock_common_getsockopt,
.sendmsg = inet_sendmsg,
.recvmsg = sock_common_recvmsg,
.mmap = sock_no_mmap,
#ifdef CONFIG_COMPAT
.compat_ioctl = inet6_compat_ioctl,
#endif
};
static struct inet_protosw l2tp_ip6_protosw = {
.type = SOCK_DGRAM,
.protocol = IPPROTO_L2TP,
.prot = &l2tp_ip6_prot,
.ops = &l2tp_ip6_ops,
};
static struct inet6_protocol l2tp_ip6_protocol __read_mostly = {
.handler = l2tp_ip6_recv,
};
static int __init l2tp_ip6_init(void)
{
int err;
pr_info("L2TP IP encapsulation support for IPv6 (L2TPv3)\n");
err = proto_register(&l2tp_ip6_prot, 1);
if (err != 0)
goto out;
err = inet6_add_protocol(&l2tp_ip6_protocol, IPPROTO_L2TP);
if (err)
goto out1;
inet6_register_protosw(&l2tp_ip6_protosw);
return 0;
out1:
proto_unregister(&l2tp_ip6_prot);
out:
return err;
}
static void __exit l2tp_ip6_exit(void)
{
inet6_unregister_protosw(&l2tp_ip6_protosw);
inet6_del_protocol(&l2tp_ip6_protocol, IPPROTO_L2TP);
proto_unregister(&l2tp_ip6_prot);
}
module_init(l2tp_ip6_init);
module_exit(l2tp_ip6_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Chris Elston <[email protected]>");
MODULE_DESCRIPTION("L2TP IP encapsulation for IPv6");
MODULE_VERSION("1.0");
/* Use the values of SOCK_DGRAM (2) as type and IPPROTO_L2TP (115) as protocol,
* because __stringify doesn't like enums
*/
MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET6, 115, 2);
MODULE_ALIAS_NET_PF_PROTO(PF_INET6, 115);
| linux-master | net/l2tp/l2tp_ip6.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* L2TP subsystem debugfs
*
* Copyright (c) 2010 Katalix Systems Ltd
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
#include <linux/hash.h>
#include <linux/l2tp.h>
#include <linux/in.h>
#include <linux/etherdevice.h>
#include <linux/spinlock.h>
#include <linux/debugfs.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/udp.h>
#include <net/inet_common.h>
#include <net/inet_hashtables.h>
#include <net/tcp_states.h>
#include <net/protocol.h>
#include <net/xfrm.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include "l2tp_core.h"
static struct dentry *rootdir;
struct l2tp_dfs_seq_data {
struct net *net;
netns_tracker ns_tracker;
int tunnel_idx; /* current tunnel */
int session_idx; /* index of session within current tunnel */
struct l2tp_tunnel *tunnel;
struct l2tp_session *session; /* NULL means get next tunnel */
};
static void l2tp_dfs_next_tunnel(struct l2tp_dfs_seq_data *pd)
{
/* Drop reference taken during previous invocation */
if (pd->tunnel)
l2tp_tunnel_dec_refcount(pd->tunnel);
pd->tunnel = l2tp_tunnel_get_nth(pd->net, pd->tunnel_idx);
pd->tunnel_idx++;
}
static void l2tp_dfs_next_session(struct l2tp_dfs_seq_data *pd)
{
/* Drop reference taken during previous invocation */
if (pd->session)
l2tp_session_dec_refcount(pd->session);
pd->session = l2tp_session_get_nth(pd->tunnel, pd->session_idx);
pd->session_idx++;
if (!pd->session) {
pd->session_idx = 0;
l2tp_dfs_next_tunnel(pd);
}
}
static void *l2tp_dfs_seq_start(struct seq_file *m, loff_t *offs)
{
struct l2tp_dfs_seq_data *pd = SEQ_START_TOKEN;
loff_t pos = *offs;
if (!pos)
goto out;
if (WARN_ON(!m->private)) {
pd = NULL;
goto out;
}
pd = m->private;
if (!pd->tunnel)
l2tp_dfs_next_tunnel(pd);
else
l2tp_dfs_next_session(pd);
/* NULL tunnel and session indicates end of list */
if (!pd->tunnel && !pd->session)
pd = NULL;
out:
return pd;
}
static void *l2tp_dfs_seq_next(struct seq_file *m, void *v, loff_t *pos)
{
(*pos)++;
return NULL;
}
static void l2tp_dfs_seq_stop(struct seq_file *p, void *v)
{
struct l2tp_dfs_seq_data *pd = v;
if (!pd || pd == SEQ_START_TOKEN)
return;
/* Drop reference taken by last invocation of l2tp_dfs_next_session()
* or l2tp_dfs_next_tunnel().
*/
if (pd->session) {
l2tp_session_dec_refcount(pd->session);
pd->session = NULL;
}
if (pd->tunnel) {
l2tp_tunnel_dec_refcount(pd->tunnel);
pd->tunnel = NULL;
}
}
static void l2tp_dfs_seq_tunnel_show(struct seq_file *m, void *v)
{
struct l2tp_tunnel *tunnel = v;
struct l2tp_session *session;
int session_count = 0;
int hash;
rcu_read_lock_bh();
for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
hlist_for_each_entry_rcu(session, &tunnel->session_hlist[hash], hlist) {
/* Session ID of zero is a dummy/reserved value used by pppol2tp */
if (session->session_id == 0)
continue;
session_count++;
}
}
rcu_read_unlock_bh();
seq_printf(m, "\nTUNNEL %u peer %u", tunnel->tunnel_id, tunnel->peer_tunnel_id);
if (tunnel->sock) {
struct inet_sock *inet = inet_sk(tunnel->sock);
#if IS_ENABLED(CONFIG_IPV6)
if (tunnel->sock->sk_family == AF_INET6) {
const struct ipv6_pinfo *np = inet6_sk(tunnel->sock);
seq_printf(m, " from %pI6c to %pI6c\n",
&np->saddr, &tunnel->sock->sk_v6_daddr);
}
#endif
if (tunnel->sock->sk_family == AF_INET)
seq_printf(m, " from %pI4 to %pI4\n",
&inet->inet_saddr, &inet->inet_daddr);
if (tunnel->encap == L2TP_ENCAPTYPE_UDP)
seq_printf(m, " source port %hu, dest port %hu\n",
ntohs(inet->inet_sport), ntohs(inet->inet_dport));
}
seq_printf(m, " L2TPv%d, %s\n", tunnel->version,
tunnel->encap == L2TP_ENCAPTYPE_UDP ? "UDP" :
tunnel->encap == L2TP_ENCAPTYPE_IP ? "IP" :
"");
seq_printf(m, " %d sessions, refcnt %d/%d\n", session_count,
tunnel->sock ? refcount_read(&tunnel->sock->sk_refcnt) : 0,
refcount_read(&tunnel->ref_count));
seq_printf(m, " %08x rx %ld/%ld/%ld rx %ld/%ld/%ld\n",
0,
atomic_long_read(&tunnel->stats.tx_packets),
atomic_long_read(&tunnel->stats.tx_bytes),
atomic_long_read(&tunnel->stats.tx_errors),
atomic_long_read(&tunnel->stats.rx_packets),
atomic_long_read(&tunnel->stats.rx_bytes),
atomic_long_read(&tunnel->stats.rx_errors));
}
static void l2tp_dfs_seq_session_show(struct seq_file *m, void *v)
{
struct l2tp_session *session = v;
seq_printf(m, " SESSION %u, peer %u, %s\n", session->session_id,
session->peer_session_id,
session->pwtype == L2TP_PWTYPE_ETH ? "ETH" :
session->pwtype == L2TP_PWTYPE_PPP ? "PPP" :
"");
if (session->send_seq || session->recv_seq)
seq_printf(m, " nr %u, ns %u\n", session->nr, session->ns);
seq_printf(m, " refcnt %d\n", refcount_read(&session->ref_count));
seq_printf(m, " config 0/0/%c/%c/-/%s %08x %u\n",
session->recv_seq ? 'R' : '-',
session->send_seq ? 'S' : '-',
session->lns_mode ? "LNS" : "LAC",
0,
jiffies_to_msecs(session->reorder_timeout));
seq_printf(m, " offset 0 l2specific %hu/%d\n",
session->l2specific_type, l2tp_get_l2specific_len(session));
if (session->cookie_len) {
seq_printf(m, " cookie %02x%02x%02x%02x",
session->cookie[0], session->cookie[1],
session->cookie[2], session->cookie[3]);
if (session->cookie_len == 8)
seq_printf(m, "%02x%02x%02x%02x",
session->cookie[4], session->cookie[5],
session->cookie[6], session->cookie[7]);
seq_puts(m, "\n");
}
if (session->peer_cookie_len) {
seq_printf(m, " peer cookie %02x%02x%02x%02x",
session->peer_cookie[0], session->peer_cookie[1],
session->peer_cookie[2], session->peer_cookie[3]);
if (session->peer_cookie_len == 8)
seq_printf(m, "%02x%02x%02x%02x",
session->peer_cookie[4], session->peer_cookie[5],
session->peer_cookie[6], session->peer_cookie[7]);
seq_puts(m, "\n");
}
seq_printf(m, " %u/%u tx %ld/%ld/%ld rx %ld/%ld/%ld\n",
session->nr, session->ns,
atomic_long_read(&session->stats.tx_packets),
atomic_long_read(&session->stats.tx_bytes),
atomic_long_read(&session->stats.tx_errors),
atomic_long_read(&session->stats.rx_packets),
atomic_long_read(&session->stats.rx_bytes),
atomic_long_read(&session->stats.rx_errors));
if (session->show)
session->show(m, session);
}
static int l2tp_dfs_seq_show(struct seq_file *m, void *v)
{
struct l2tp_dfs_seq_data *pd = v;
/* display header on line 1 */
if (v == SEQ_START_TOKEN) {
seq_puts(m, "TUNNEL ID, peer ID from IP to IP\n");
seq_puts(m, " L2TPv2/L2TPv3, UDP/IP\n");
seq_puts(m, " sessions session-count, refcnt refcnt/sk->refcnt\n");
seq_puts(m, " debug tx-pkts/bytes/errs rx-pkts/bytes/errs\n");
seq_puts(m, " SESSION ID, peer ID, PWTYPE\n");
seq_puts(m, " refcnt cnt\n");
seq_puts(m, " offset OFFSET l2specific TYPE/LEN\n");
seq_puts(m, " [ cookie ]\n");
seq_puts(m, " [ peer cookie ]\n");
seq_puts(m, " config mtu/mru/rcvseq/sendseq/dataseq/lns debug reorderto\n");
seq_puts(m, " nr/ns tx-pkts/bytes/errs rx-pkts/bytes/errs\n");
goto out;
}
if (!pd->session)
l2tp_dfs_seq_tunnel_show(m, pd->tunnel);
else
l2tp_dfs_seq_session_show(m, pd->session);
out:
return 0;
}
static const struct seq_operations l2tp_dfs_seq_ops = {
.start = l2tp_dfs_seq_start,
.next = l2tp_dfs_seq_next,
.stop = l2tp_dfs_seq_stop,
.show = l2tp_dfs_seq_show,
};
static int l2tp_dfs_seq_open(struct inode *inode, struct file *file)
{
struct l2tp_dfs_seq_data *pd;
struct seq_file *seq;
int rc = -ENOMEM;
pd = kzalloc(sizeof(*pd), GFP_KERNEL);
if (!pd)
goto out;
/* Derive the network namespace from the pid opening the
* file.
*/
pd->net = get_net_ns_by_pid(current->pid);
if (IS_ERR(pd->net)) {
rc = PTR_ERR(pd->net);
goto err_free_pd;
}
netns_tracker_alloc(pd->net, &pd->ns_tracker, GFP_KERNEL);
rc = seq_open(file, &l2tp_dfs_seq_ops);
if (rc)
goto err_free_net;
seq = file->private_data;
seq->private = pd;
out:
return rc;
err_free_net:
put_net_track(pd->net, &pd->ns_tracker);
err_free_pd:
kfree(pd);
goto out;
}
static int l2tp_dfs_seq_release(struct inode *inode, struct file *file)
{
struct l2tp_dfs_seq_data *pd;
struct seq_file *seq;
seq = file->private_data;
pd = seq->private;
if (pd->net)
put_net_track(pd->net, &pd->ns_tracker);
kfree(pd);
seq_release(inode, file);
return 0;
}
static const struct file_operations l2tp_dfs_fops = {
.owner = THIS_MODULE,
.open = l2tp_dfs_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = l2tp_dfs_seq_release,
};
static int __init l2tp_debugfs_init(void)
{
rootdir = debugfs_create_dir("l2tp", NULL);
debugfs_create_file("tunnels", 0600, rootdir, NULL, &l2tp_dfs_fops);
pr_info("L2TP debugfs support\n");
return 0;
}
static void __exit l2tp_debugfs_exit(void)
{
debugfs_remove_recursive(rootdir);
}
module_init(l2tp_debugfs_init);
module_exit(l2tp_debugfs_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("James Chapman <[email protected]>");
MODULE_DESCRIPTION("L2TP debugfs driver");
MODULE_VERSION("1.0");
| linux-master | net/l2tp/l2tp_debugfs.c |
// SPDX-License-Identifier: GPL-2.0-only
/* L2TP core.
*
* Copyright (c) 2008,2009,2010 Katalix Systems Ltd
*
* This file contains some code of the original L2TPv2 pppol2tp
* driver, which has the following copyright:
*
* Authors: Martijn van Oosterhout <[email protected]>
* James Chapman ([email protected])
* Contributors:
* Michal Ostrowski <[email protected]>
* Arnaldo Carvalho de Melo <[email protected]>
* David S. Miller ([email protected])
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/string.h>
#include <linux/list.h>
#include <linux/rculist.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/jiffies.h>
#include <linux/netdevice.h>
#include <linux/net.h>
#include <linux/inetdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <linux/l2tp.h>
#include <linux/hash.h>
#include <linux/sort.h>
#include <linux/file.h>
#include <linux/nsproxy.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/dst.h>
#include <net/ip.h>
#include <net/udp.h>
#include <net/udp_tunnel.h>
#include <net/inet_common.h>
#include <net/xfrm.h>
#include <net/protocol.h>
#include <net/inet6_connection_sock.h>
#include <net/inet_ecn.h>
#include <net/ip6_route.h>
#include <net/ip6_checksum.h>
#include <asm/byteorder.h>
#include <linux/atomic.h>
#include "l2tp_core.h"
#include "trace.h"
#define CREATE_TRACE_POINTS
#include "trace.h"
#define L2TP_DRV_VERSION "V2.0"
/* L2TP header constants */
#define L2TP_HDRFLAG_T 0x8000
#define L2TP_HDRFLAG_L 0x4000
#define L2TP_HDRFLAG_S 0x0800
#define L2TP_HDRFLAG_O 0x0200
#define L2TP_HDRFLAG_P 0x0100
#define L2TP_HDR_VER_MASK 0x000F
#define L2TP_HDR_VER_2 0x0002
#define L2TP_HDR_VER_3 0x0003
/* L2TPv3 default L2-specific sublayer */
#define L2TP_SLFLAG_S 0x40000000
#define L2TP_SL_SEQ_MASK 0x00ffffff
#define L2TP_HDR_SIZE_MAX 14
/* Default trace flags */
#define L2TP_DEFAULT_DEBUG_FLAGS 0
/* Private data stored for received packets in the skb.
*/
struct l2tp_skb_cb {
u32 ns;
u16 has_seq;
u16 length;
unsigned long expires;
};
#define L2TP_SKB_CB(skb) ((struct l2tp_skb_cb *)&(skb)->cb[sizeof(struct inet_skb_parm)])
static struct workqueue_struct *l2tp_wq;
/* per-net private data for this module */
static unsigned int l2tp_net_id;
struct l2tp_net {
/* Lock for write access to l2tp_tunnel_idr */
spinlock_t l2tp_tunnel_idr_lock;
struct idr l2tp_tunnel_idr;
struct hlist_head l2tp_session_hlist[L2TP_HASH_SIZE_2];
/* Lock for write access to l2tp_session_hlist */
spinlock_t l2tp_session_hlist_lock;
};
#if IS_ENABLED(CONFIG_IPV6)
static bool l2tp_sk_is_v6(struct sock *sk)
{
return sk->sk_family == PF_INET6 &&
!ipv6_addr_v4mapped(&sk->sk_v6_daddr);
}
#endif
static inline struct l2tp_net *l2tp_pernet(const struct net *net)
{
return net_generic(net, l2tp_net_id);
}
/* Session hash global list for L2TPv3.
* The session_id SHOULD be random according to RFC3931, but several
* L2TP implementations use incrementing session_ids. So we do a real
* hash on the session_id, rather than a simple bitmask.
*/
static inline struct hlist_head *
l2tp_session_id_hash_2(struct l2tp_net *pn, u32 session_id)
{
return &pn->l2tp_session_hlist[hash_32(session_id, L2TP_HASH_BITS_2)];
}
/* Session hash list.
* The session_id SHOULD be random according to RFC2661, but several
* L2TP implementations (Cisco and Microsoft) use incrementing
* session_ids. So we do a real hash on the session_id, rather than a
* simple bitmask.
*/
static inline struct hlist_head *
l2tp_session_id_hash(struct l2tp_tunnel *tunnel, u32 session_id)
{
return &tunnel->session_hlist[hash_32(session_id, L2TP_HASH_BITS)];
}
static void l2tp_tunnel_free(struct l2tp_tunnel *tunnel)
{
trace_free_tunnel(tunnel);
sock_put(tunnel->sock);
/* the tunnel is freed in the socket destructor */
}
static void l2tp_session_free(struct l2tp_session *session)
{
trace_free_session(session);
if (session->tunnel)
l2tp_tunnel_dec_refcount(session->tunnel);
kfree(session);
}
struct l2tp_tunnel *l2tp_sk_to_tunnel(struct sock *sk)
{
struct l2tp_tunnel *tunnel = sk->sk_user_data;
if (tunnel)
if (WARN_ON(tunnel->magic != L2TP_TUNNEL_MAGIC))
return NULL;
return tunnel;
}
EXPORT_SYMBOL_GPL(l2tp_sk_to_tunnel);
void l2tp_tunnel_inc_refcount(struct l2tp_tunnel *tunnel)
{
refcount_inc(&tunnel->ref_count);
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_inc_refcount);
void l2tp_tunnel_dec_refcount(struct l2tp_tunnel *tunnel)
{
if (refcount_dec_and_test(&tunnel->ref_count))
l2tp_tunnel_free(tunnel);
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_dec_refcount);
void l2tp_session_inc_refcount(struct l2tp_session *session)
{
refcount_inc(&session->ref_count);
}
EXPORT_SYMBOL_GPL(l2tp_session_inc_refcount);
void l2tp_session_dec_refcount(struct l2tp_session *session)
{
if (refcount_dec_and_test(&session->ref_count))
l2tp_session_free(session);
}
EXPORT_SYMBOL_GPL(l2tp_session_dec_refcount);
/* Lookup a tunnel. A new reference is held on the returned tunnel. */
struct l2tp_tunnel *l2tp_tunnel_get(const struct net *net, u32 tunnel_id)
{
const struct l2tp_net *pn = l2tp_pernet(net);
struct l2tp_tunnel *tunnel;
rcu_read_lock_bh();
tunnel = idr_find(&pn->l2tp_tunnel_idr, tunnel_id);
if (tunnel && refcount_inc_not_zero(&tunnel->ref_count)) {
rcu_read_unlock_bh();
return tunnel;
}
rcu_read_unlock_bh();
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_get);
struct l2tp_tunnel *l2tp_tunnel_get_nth(const struct net *net, int nth)
{
struct l2tp_net *pn = l2tp_pernet(net);
unsigned long tunnel_id, tmp;
struct l2tp_tunnel *tunnel;
int count = 0;
rcu_read_lock_bh();
idr_for_each_entry_ul(&pn->l2tp_tunnel_idr, tunnel, tmp, tunnel_id) {
if (tunnel && ++count > nth &&
refcount_inc_not_zero(&tunnel->ref_count)) {
rcu_read_unlock_bh();
return tunnel;
}
}
rcu_read_unlock_bh();
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_get_nth);
struct l2tp_session *l2tp_tunnel_get_session(struct l2tp_tunnel *tunnel,
u32 session_id)
{
struct hlist_head *session_list;
struct l2tp_session *session;
session_list = l2tp_session_id_hash(tunnel, session_id);
rcu_read_lock_bh();
hlist_for_each_entry_rcu(session, session_list, hlist)
if (session->session_id == session_id) {
l2tp_session_inc_refcount(session);
rcu_read_unlock_bh();
return session;
}
rcu_read_unlock_bh();
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_get_session);
struct l2tp_session *l2tp_session_get(const struct net *net, u32 session_id)
{
struct hlist_head *session_list;
struct l2tp_session *session;
session_list = l2tp_session_id_hash_2(l2tp_pernet(net), session_id);
rcu_read_lock_bh();
hlist_for_each_entry_rcu(session, session_list, global_hlist)
if (session->session_id == session_id) {
l2tp_session_inc_refcount(session);
rcu_read_unlock_bh();
return session;
}
rcu_read_unlock_bh();
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_session_get);
struct l2tp_session *l2tp_session_get_nth(struct l2tp_tunnel *tunnel, int nth)
{
int hash;
struct l2tp_session *session;
int count = 0;
rcu_read_lock_bh();
for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
hlist_for_each_entry_rcu(session, &tunnel->session_hlist[hash], hlist) {
if (++count > nth) {
l2tp_session_inc_refcount(session);
rcu_read_unlock_bh();
return session;
}
}
}
rcu_read_unlock_bh();
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_session_get_nth);
/* Lookup a session by interface name.
* This is very inefficient but is only used by management interfaces.
*/
struct l2tp_session *l2tp_session_get_by_ifname(const struct net *net,
const char *ifname)
{
struct l2tp_net *pn = l2tp_pernet(net);
int hash;
struct l2tp_session *session;
rcu_read_lock_bh();
for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++) {
hlist_for_each_entry_rcu(session, &pn->l2tp_session_hlist[hash], global_hlist) {
if (!strcmp(session->ifname, ifname)) {
l2tp_session_inc_refcount(session);
rcu_read_unlock_bh();
return session;
}
}
}
rcu_read_unlock_bh();
return NULL;
}
EXPORT_SYMBOL_GPL(l2tp_session_get_by_ifname);
int l2tp_session_register(struct l2tp_session *session,
struct l2tp_tunnel *tunnel)
{
struct l2tp_session *session_walk;
struct hlist_head *g_head;
struct hlist_head *head;
struct l2tp_net *pn;
int err;
head = l2tp_session_id_hash(tunnel, session->session_id);
spin_lock_bh(&tunnel->hlist_lock);
if (!tunnel->acpt_newsess) {
err = -ENODEV;
goto err_tlock;
}
hlist_for_each_entry(session_walk, head, hlist)
if (session_walk->session_id == session->session_id) {
err = -EEXIST;
goto err_tlock;
}
if (tunnel->version == L2TP_HDR_VER_3) {
pn = l2tp_pernet(tunnel->l2tp_net);
g_head = l2tp_session_id_hash_2(pn, session->session_id);
spin_lock_bh(&pn->l2tp_session_hlist_lock);
/* IP encap expects session IDs to be globally unique, while
* UDP encap doesn't.
*/
hlist_for_each_entry(session_walk, g_head, global_hlist)
if (session_walk->session_id == session->session_id &&
(session_walk->tunnel->encap == L2TP_ENCAPTYPE_IP ||
tunnel->encap == L2TP_ENCAPTYPE_IP)) {
err = -EEXIST;
goto err_tlock_pnlock;
}
l2tp_tunnel_inc_refcount(tunnel);
hlist_add_head_rcu(&session->global_hlist, g_head);
spin_unlock_bh(&pn->l2tp_session_hlist_lock);
} else {
l2tp_tunnel_inc_refcount(tunnel);
}
hlist_add_head_rcu(&session->hlist, head);
spin_unlock_bh(&tunnel->hlist_lock);
trace_register_session(session);
return 0;
err_tlock_pnlock:
spin_unlock_bh(&pn->l2tp_session_hlist_lock);
err_tlock:
spin_unlock_bh(&tunnel->hlist_lock);
return err;
}
EXPORT_SYMBOL_GPL(l2tp_session_register);
/*****************************************************************************
* Receive data handling
*****************************************************************************/
/* Queue a skb in order. We come here only if the skb has an L2TP sequence
* number.
*/
static void l2tp_recv_queue_skb(struct l2tp_session *session, struct sk_buff *skb)
{
struct sk_buff *skbp;
struct sk_buff *tmp;
u32 ns = L2TP_SKB_CB(skb)->ns;
spin_lock_bh(&session->reorder_q.lock);
skb_queue_walk_safe(&session->reorder_q, skbp, tmp) {
if (L2TP_SKB_CB(skbp)->ns > ns) {
__skb_queue_before(&session->reorder_q, skbp, skb);
atomic_long_inc(&session->stats.rx_oos_packets);
goto out;
}
}
__skb_queue_tail(&session->reorder_q, skb);
out:
spin_unlock_bh(&session->reorder_q.lock);
}
/* Dequeue a single skb.
*/
static void l2tp_recv_dequeue_skb(struct l2tp_session *session, struct sk_buff *skb)
{
struct l2tp_tunnel *tunnel = session->tunnel;
int length = L2TP_SKB_CB(skb)->length;
/* We're about to requeue the skb, so return resources
* to its current owner (a socket receive buffer).
*/
skb_orphan(skb);
atomic_long_inc(&tunnel->stats.rx_packets);
atomic_long_add(length, &tunnel->stats.rx_bytes);
atomic_long_inc(&session->stats.rx_packets);
atomic_long_add(length, &session->stats.rx_bytes);
if (L2TP_SKB_CB(skb)->has_seq) {
/* Bump our Nr */
session->nr++;
session->nr &= session->nr_max;
trace_session_seqnum_update(session);
}
/* call private receive handler */
if (session->recv_skb)
(*session->recv_skb)(session, skb, L2TP_SKB_CB(skb)->length);
else
kfree_skb(skb);
}
/* Dequeue skbs from the session's reorder_q, subject to packet order.
* Skbs that have been in the queue for too long are simply discarded.
*/
static void l2tp_recv_dequeue(struct l2tp_session *session)
{
struct sk_buff *skb;
struct sk_buff *tmp;
/* If the pkt at the head of the queue has the nr that we
* expect to send up next, dequeue it and any other
* in-sequence packets behind it.
*/
start:
spin_lock_bh(&session->reorder_q.lock);
skb_queue_walk_safe(&session->reorder_q, skb, tmp) {
struct l2tp_skb_cb *cb = L2TP_SKB_CB(skb);
/* If the packet has been pending on the queue for too long, discard it */
if (time_after(jiffies, cb->expires)) {
atomic_long_inc(&session->stats.rx_seq_discards);
atomic_long_inc(&session->stats.rx_errors);
trace_session_pkt_expired(session, cb->ns);
session->reorder_skip = 1;
__skb_unlink(skb, &session->reorder_q);
kfree_skb(skb);
continue;
}
if (cb->has_seq) {
if (session->reorder_skip) {
session->reorder_skip = 0;
session->nr = cb->ns;
trace_session_seqnum_reset(session);
}
if (cb->ns != session->nr)
goto out;
}
__skb_unlink(skb, &session->reorder_q);
/* Process the skb. We release the queue lock while we
* do so to let other contexts process the queue.
*/
spin_unlock_bh(&session->reorder_q.lock);
l2tp_recv_dequeue_skb(session, skb);
goto start;
}
out:
spin_unlock_bh(&session->reorder_q.lock);
}
static int l2tp_seq_check_rx_window(struct l2tp_session *session, u32 nr)
{
u32 nws;
if (nr >= session->nr)
nws = nr - session->nr;
else
nws = (session->nr_max + 1) - (session->nr - nr);
return nws < session->nr_window_size;
}
/* If packet has sequence numbers, queue it if acceptable. Returns 0 if
* acceptable, else non-zero.
*/
static int l2tp_recv_data_seq(struct l2tp_session *session, struct sk_buff *skb)
{
struct l2tp_skb_cb *cb = L2TP_SKB_CB(skb);
if (!l2tp_seq_check_rx_window(session, cb->ns)) {
/* Packet sequence number is outside allowed window.
* Discard it.
*/
trace_session_pkt_outside_rx_window(session, cb->ns);
goto discard;
}
if (session->reorder_timeout != 0) {
/* Packet reordering enabled. Add skb to session's
* reorder queue, in order of ns.
*/
l2tp_recv_queue_skb(session, skb);
goto out;
}
/* Packet reordering disabled. Discard out-of-sequence packets, while
* tracking the number if in-sequence packets after the first OOS packet
* is seen. After nr_oos_count_max in-sequence packets, reset the
* sequence number to re-enable packet reception.
*/
if (cb->ns == session->nr) {
skb_queue_tail(&session->reorder_q, skb);
} else {
u32 nr_oos = cb->ns;
u32 nr_next = (session->nr_oos + 1) & session->nr_max;
if (nr_oos == nr_next)
session->nr_oos_count++;
else
session->nr_oos_count = 0;
session->nr_oos = nr_oos;
if (session->nr_oos_count > session->nr_oos_count_max) {
session->reorder_skip = 1;
}
if (!session->reorder_skip) {
atomic_long_inc(&session->stats.rx_seq_discards);
trace_session_pkt_oos(session, cb->ns);
goto discard;
}
skb_queue_tail(&session->reorder_q, skb);
}
out:
return 0;
discard:
return 1;
}
/* Do receive processing of L2TP data frames. We handle both L2TPv2
* and L2TPv3 data frames here.
*
* L2TPv2 Data Message Header
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |T|L|x|x|S|x|O|P|x|x|x|x| Ver | Length (opt) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Tunnel ID | Session ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Ns (opt) | Nr (opt) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Offset Size (opt) | Offset pad... (opt)
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Data frames are marked by T=0. All other fields are the same as
* those in L2TP control frames.
*
* L2TPv3 Data Message Header
*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | L2TP Session Header |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | L2-Specific Sublayer |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Tunnel Payload ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* L2TPv3 Session Header Over IP
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Session ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Cookie (optional, maximum 64 bits)...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* L2TPv3 L2-Specific Sublayer Format
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |x|S|x|x|x|x|x|x| Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Cookie value and sublayer format are negotiated with the peer when
* the session is set up. Unlike L2TPv2, we do not need to parse the
* packet header to determine if optional fields are present.
*
* Caller must already have parsed the frame and determined that it is
* a data (not control) frame before coming here. Fields up to the
* session-id have already been parsed and ptr points to the data
* after the session-id.
*/
void l2tp_recv_common(struct l2tp_session *session, struct sk_buff *skb,
unsigned char *ptr, unsigned char *optr, u16 hdrflags,
int length)
{
struct l2tp_tunnel *tunnel = session->tunnel;
int offset;
/* Parse and check optional cookie */
if (session->peer_cookie_len > 0) {
if (memcmp(ptr, &session->peer_cookie[0], session->peer_cookie_len)) {
pr_debug_ratelimited("%s: cookie mismatch (%u/%u). Discarding.\n",
tunnel->name, tunnel->tunnel_id,
session->session_id);
atomic_long_inc(&session->stats.rx_cookie_discards);
goto discard;
}
ptr += session->peer_cookie_len;
}
/* Handle the optional sequence numbers. Sequence numbers are
* in different places for L2TPv2 and L2TPv3.
*
* If we are the LAC, enable/disable sequence numbers under
* the control of the LNS. If no sequence numbers present but
* we were expecting them, discard frame.
*/
L2TP_SKB_CB(skb)->has_seq = 0;
if (tunnel->version == L2TP_HDR_VER_2) {
if (hdrflags & L2TP_HDRFLAG_S) {
/* Store L2TP info in the skb */
L2TP_SKB_CB(skb)->ns = ntohs(*(__be16 *)ptr);
L2TP_SKB_CB(skb)->has_seq = 1;
ptr += 2;
/* Skip past nr in the header */
ptr += 2;
}
} else if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
u32 l2h = ntohl(*(__be32 *)ptr);
if (l2h & 0x40000000) {
/* Store L2TP info in the skb */
L2TP_SKB_CB(skb)->ns = l2h & 0x00ffffff;
L2TP_SKB_CB(skb)->has_seq = 1;
}
ptr += 4;
}
if (L2TP_SKB_CB(skb)->has_seq) {
/* Received a packet with sequence numbers. If we're the LAC,
* check if we sre sending sequence numbers and if not,
* configure it so.
*/
if (!session->lns_mode && !session->send_seq) {
trace_session_seqnum_lns_enable(session);
session->send_seq = 1;
l2tp_session_set_header_len(session, tunnel->version);
}
} else {
/* No sequence numbers.
* If user has configured mandatory sequence numbers, discard.
*/
if (session->recv_seq) {
pr_debug_ratelimited("%s: recv data has no seq numbers when required. Discarding.\n",
session->name);
atomic_long_inc(&session->stats.rx_seq_discards);
goto discard;
}
/* If we're the LAC and we're sending sequence numbers, the
* LNS has requested that we no longer send sequence numbers.
* If we're the LNS and we're sending sequence numbers, the
* LAC is broken. Discard the frame.
*/
if (!session->lns_mode && session->send_seq) {
trace_session_seqnum_lns_disable(session);
session->send_seq = 0;
l2tp_session_set_header_len(session, tunnel->version);
} else if (session->send_seq) {
pr_debug_ratelimited("%s: recv data has no seq numbers when required. Discarding.\n",
session->name);
atomic_long_inc(&session->stats.rx_seq_discards);
goto discard;
}
}
/* Session data offset is defined only for L2TPv2 and is
* indicated by an optional 16-bit value in the header.
*/
if (tunnel->version == L2TP_HDR_VER_2) {
/* If offset bit set, skip it. */
if (hdrflags & L2TP_HDRFLAG_O) {
offset = ntohs(*(__be16 *)ptr);
ptr += 2 + offset;
}
}
offset = ptr - optr;
if (!pskb_may_pull(skb, offset))
goto discard;
__skb_pull(skb, offset);
/* Prepare skb for adding to the session's reorder_q. Hold
* packets for max reorder_timeout or 1 second if not
* reordering.
*/
L2TP_SKB_CB(skb)->length = length;
L2TP_SKB_CB(skb)->expires = jiffies +
(session->reorder_timeout ? session->reorder_timeout : HZ);
/* Add packet to the session's receive queue. Reordering is done here, if
* enabled. Saved L2TP protocol info is stored in skb->sb[].
*/
if (L2TP_SKB_CB(skb)->has_seq) {
if (l2tp_recv_data_seq(session, skb))
goto discard;
} else {
/* No sequence numbers. Add the skb to the tail of the
* reorder queue. This ensures that it will be
* delivered after all previous sequenced skbs.
*/
skb_queue_tail(&session->reorder_q, skb);
}
/* Try to dequeue as many skbs from reorder_q as we can. */
l2tp_recv_dequeue(session);
return;
discard:
atomic_long_inc(&session->stats.rx_errors);
kfree_skb(skb);
}
EXPORT_SYMBOL_GPL(l2tp_recv_common);
/* Drop skbs from the session's reorder_q
*/
static void l2tp_session_queue_purge(struct l2tp_session *session)
{
struct sk_buff *skb = NULL;
while ((skb = skb_dequeue(&session->reorder_q))) {
atomic_long_inc(&session->stats.rx_errors);
kfree_skb(skb);
}
}
/* Internal UDP receive frame. Do the real work of receiving an L2TP data frame
* here. The skb is not on a list when we get here.
* Returns 0 if the packet was a data packet and was successfully passed on.
* Returns 1 if the packet was not a good data packet and could not be
* forwarded. All such packets are passed up to userspace to deal with.
*/
static int l2tp_udp_recv_core(struct l2tp_tunnel *tunnel, struct sk_buff *skb)
{
struct l2tp_session *session = NULL;
unsigned char *ptr, *optr;
u16 hdrflags;
u32 tunnel_id, session_id;
u16 version;
int length;
/* UDP has verified checksum */
/* UDP always verifies the packet length. */
__skb_pull(skb, sizeof(struct udphdr));
/* Short packet? */
if (!pskb_may_pull(skb, L2TP_HDR_SIZE_MAX)) {
pr_debug_ratelimited("%s: recv short packet (len=%d)\n",
tunnel->name, skb->len);
goto invalid;
}
/* Point to L2TP header */
optr = skb->data;
ptr = skb->data;
/* Get L2TP header flags */
hdrflags = ntohs(*(__be16 *)ptr);
/* Check protocol version */
version = hdrflags & L2TP_HDR_VER_MASK;
if (version != tunnel->version) {
pr_debug_ratelimited("%s: recv protocol version mismatch: got %d expected %d\n",
tunnel->name, version, tunnel->version);
goto invalid;
}
/* Get length of L2TP packet */
length = skb->len;
/* If type is control packet, it is handled by userspace. */
if (hdrflags & L2TP_HDRFLAG_T)
goto pass;
/* Skip flags */
ptr += 2;
if (tunnel->version == L2TP_HDR_VER_2) {
/* If length is present, skip it */
if (hdrflags & L2TP_HDRFLAG_L)
ptr += 2;
/* Extract tunnel and session ID */
tunnel_id = ntohs(*(__be16 *)ptr);
ptr += 2;
session_id = ntohs(*(__be16 *)ptr);
ptr += 2;
} else {
ptr += 2; /* skip reserved bits */
tunnel_id = tunnel->tunnel_id;
session_id = ntohl(*(__be32 *)ptr);
ptr += 4;
}
/* Find the session context */
session = l2tp_tunnel_get_session(tunnel, session_id);
if (!session || !session->recv_skb) {
if (session)
l2tp_session_dec_refcount(session);
/* Not found? Pass to userspace to deal with */
pr_debug_ratelimited("%s: no session found (%u/%u). Passing up.\n",
tunnel->name, tunnel_id, session_id);
goto pass;
}
if (tunnel->version == L2TP_HDR_VER_3 &&
l2tp_v3_ensure_opt_in_linear(session, skb, &ptr, &optr)) {
l2tp_session_dec_refcount(session);
goto invalid;
}
l2tp_recv_common(session, skb, ptr, optr, hdrflags, length);
l2tp_session_dec_refcount(session);
return 0;
invalid:
atomic_long_inc(&tunnel->stats.rx_invalid);
pass:
/* Put UDP header back */
__skb_push(skb, sizeof(struct udphdr));
return 1;
}
/* UDP encapsulation receive handler. See net/ipv4/udp.c.
* Return codes:
* 0 : success.
* <0: error
* >0: skb should be passed up to userspace as UDP.
*/
int l2tp_udp_encap_recv(struct sock *sk, struct sk_buff *skb)
{
struct l2tp_tunnel *tunnel;
/* Note that this is called from the encap_rcv hook inside an
* RCU-protected region, but without the socket being locked.
* Hence we use rcu_dereference_sk_user_data to access the
* tunnel data structure rather the usual l2tp_sk_to_tunnel
* accessor function.
*/
tunnel = rcu_dereference_sk_user_data(sk);
if (!tunnel)
goto pass_up;
if (WARN_ON(tunnel->magic != L2TP_TUNNEL_MAGIC))
goto pass_up;
if (l2tp_udp_recv_core(tunnel, skb))
goto pass_up;
return 0;
pass_up:
return 1;
}
EXPORT_SYMBOL_GPL(l2tp_udp_encap_recv);
/************************************************************************
* Transmit handling
***********************************************************************/
/* Build an L2TP header for the session into the buffer provided.
*/
static int l2tp_build_l2tpv2_header(struct l2tp_session *session, void *buf)
{
struct l2tp_tunnel *tunnel = session->tunnel;
__be16 *bufp = buf;
__be16 *optr = buf;
u16 flags = L2TP_HDR_VER_2;
u32 tunnel_id = tunnel->peer_tunnel_id;
u32 session_id = session->peer_session_id;
if (session->send_seq)
flags |= L2TP_HDRFLAG_S;
/* Setup L2TP header. */
*bufp++ = htons(flags);
*bufp++ = htons(tunnel_id);
*bufp++ = htons(session_id);
if (session->send_seq) {
*bufp++ = htons(session->ns);
*bufp++ = 0;
session->ns++;
session->ns &= 0xffff;
trace_session_seqnum_update(session);
}
return bufp - optr;
}
static int l2tp_build_l2tpv3_header(struct l2tp_session *session, void *buf)
{
struct l2tp_tunnel *tunnel = session->tunnel;
char *bufp = buf;
char *optr = bufp;
/* Setup L2TP header. The header differs slightly for UDP and
* IP encapsulations. For UDP, there is 4 bytes of flags.
*/
if (tunnel->encap == L2TP_ENCAPTYPE_UDP) {
u16 flags = L2TP_HDR_VER_3;
*((__be16 *)bufp) = htons(flags);
bufp += 2;
*((__be16 *)bufp) = 0;
bufp += 2;
}
*((__be32 *)bufp) = htonl(session->peer_session_id);
bufp += 4;
if (session->cookie_len) {
memcpy(bufp, &session->cookie[0], session->cookie_len);
bufp += session->cookie_len;
}
if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
u32 l2h = 0;
if (session->send_seq) {
l2h = 0x40000000 | session->ns;
session->ns++;
session->ns &= 0xffffff;
trace_session_seqnum_update(session);
}
*((__be32 *)bufp) = htonl(l2h);
bufp += 4;
}
return bufp - optr;
}
/* Queue the packet to IP for output: tunnel socket lock must be held */
static int l2tp_xmit_queue(struct l2tp_tunnel *tunnel, struct sk_buff *skb, struct flowi *fl)
{
int err;
skb->ignore_df = 1;
skb_dst_drop(skb);
#if IS_ENABLED(CONFIG_IPV6)
if (l2tp_sk_is_v6(tunnel->sock))
err = inet6_csk_xmit(tunnel->sock, skb, NULL);
else
#endif
err = ip_queue_xmit(tunnel->sock, skb, fl);
return err >= 0 ? NET_XMIT_SUCCESS : NET_XMIT_DROP;
}
static int l2tp_xmit_core(struct l2tp_session *session, struct sk_buff *skb, unsigned int *len)
{
struct l2tp_tunnel *tunnel = session->tunnel;
unsigned int data_len = skb->len;
struct sock *sk = tunnel->sock;
int headroom, uhlen, udp_len;
int ret = NET_XMIT_SUCCESS;
struct inet_sock *inet;
struct udphdr *uh;
/* Check that there's enough headroom in the skb to insert IP,
* UDP and L2TP headers. If not enough, expand it to
* make room. Adjust truesize.
*/
uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(*uh) : 0;
headroom = NET_SKB_PAD + sizeof(struct iphdr) + uhlen + session->hdr_len;
if (skb_cow_head(skb, headroom)) {
kfree_skb(skb);
return NET_XMIT_DROP;
}
/* Setup L2TP header */
if (tunnel->version == L2TP_HDR_VER_2)
l2tp_build_l2tpv2_header(session, __skb_push(skb, session->hdr_len));
else
l2tp_build_l2tpv3_header(session, __skb_push(skb, session->hdr_len));
/* Reset skb netfilter state */
memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
IPCB(skb)->flags &= ~(IPSKB_XFRM_TUNNEL_SIZE | IPSKB_XFRM_TRANSFORMED | IPSKB_REROUTED);
nf_reset_ct(skb);
bh_lock_sock_nested(sk);
if (sock_owned_by_user(sk)) {
kfree_skb(skb);
ret = NET_XMIT_DROP;
goto out_unlock;
}
/* The user-space may change the connection status for the user-space
* provided socket at run time: we must check it under the socket lock
*/
if (tunnel->fd >= 0 && sk->sk_state != TCP_ESTABLISHED) {
kfree_skb(skb);
ret = NET_XMIT_DROP;
goto out_unlock;
}
/* Report transmitted length before we add encap header, which keeps
* statistics consistent for both UDP and IP encap tx/rx paths.
*/
*len = skb->len;
inet = inet_sk(sk);
switch (tunnel->encap) {
case L2TP_ENCAPTYPE_UDP:
/* Setup UDP header */
__skb_push(skb, sizeof(*uh));
skb_reset_transport_header(skb);
uh = udp_hdr(skb);
uh->source = inet->inet_sport;
uh->dest = inet->inet_dport;
udp_len = uhlen + session->hdr_len + data_len;
uh->len = htons(udp_len);
/* Calculate UDP checksum if configured to do so */
#if IS_ENABLED(CONFIG_IPV6)
if (l2tp_sk_is_v6(sk))
udp6_set_csum(udp_get_no_check6_tx(sk),
skb, &inet6_sk(sk)->saddr,
&sk->sk_v6_daddr, udp_len);
else
#endif
udp_set_csum(sk->sk_no_check_tx, skb, inet->inet_saddr,
inet->inet_daddr, udp_len);
break;
case L2TP_ENCAPTYPE_IP:
break;
}
ret = l2tp_xmit_queue(tunnel, skb, &inet->cork.fl);
out_unlock:
bh_unlock_sock(sk);
return ret;
}
/* If caller requires the skb to have a ppp header, the header must be
* inserted in the skb data before calling this function.
*/
int l2tp_xmit_skb(struct l2tp_session *session, struct sk_buff *skb)
{
unsigned int len = 0;
int ret;
ret = l2tp_xmit_core(session, skb, &len);
if (ret == NET_XMIT_SUCCESS) {
atomic_long_inc(&session->tunnel->stats.tx_packets);
atomic_long_add(len, &session->tunnel->stats.tx_bytes);
atomic_long_inc(&session->stats.tx_packets);
atomic_long_add(len, &session->stats.tx_bytes);
} else {
atomic_long_inc(&session->tunnel->stats.tx_errors);
atomic_long_inc(&session->stats.tx_errors);
}
return ret;
}
EXPORT_SYMBOL_GPL(l2tp_xmit_skb);
/*****************************************************************************
* Tinnel and session create/destroy.
*****************************************************************************/
/* Tunnel socket destruct hook.
* The tunnel context is deleted only when all session sockets have been
* closed.
*/
static void l2tp_tunnel_destruct(struct sock *sk)
{
struct l2tp_tunnel *tunnel = l2tp_sk_to_tunnel(sk);
if (!tunnel)
goto end;
/* Disable udp encapsulation */
switch (tunnel->encap) {
case L2TP_ENCAPTYPE_UDP:
/* No longer an encapsulation socket. See net/ipv4/udp.c */
(udp_sk(sk))->encap_type = 0;
(udp_sk(sk))->encap_rcv = NULL;
(udp_sk(sk))->encap_destroy = NULL;
break;
case L2TP_ENCAPTYPE_IP:
break;
}
/* Remove hooks into tunnel socket */
write_lock_bh(&sk->sk_callback_lock);
sk->sk_destruct = tunnel->old_sk_destruct;
sk->sk_user_data = NULL;
write_unlock_bh(&sk->sk_callback_lock);
/* Call the original destructor */
if (sk->sk_destruct)
(*sk->sk_destruct)(sk);
kfree_rcu(tunnel, rcu);
end:
return;
}
/* Remove an l2tp session from l2tp_core's hash lists. */
static void l2tp_session_unhash(struct l2tp_session *session)
{
struct l2tp_tunnel *tunnel = session->tunnel;
/* Remove the session from core hashes */
if (tunnel) {
/* Remove from the per-tunnel hash */
spin_lock_bh(&tunnel->hlist_lock);
hlist_del_init_rcu(&session->hlist);
spin_unlock_bh(&tunnel->hlist_lock);
/* For L2TPv3 we have a per-net hash: remove from there, too */
if (tunnel->version != L2TP_HDR_VER_2) {
struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
spin_lock_bh(&pn->l2tp_session_hlist_lock);
hlist_del_init_rcu(&session->global_hlist);
spin_unlock_bh(&pn->l2tp_session_hlist_lock);
}
synchronize_rcu();
}
}
/* When the tunnel is closed, all the attached sessions need to go too.
*/
static void l2tp_tunnel_closeall(struct l2tp_tunnel *tunnel)
{
struct l2tp_session *session;
int hash;
spin_lock_bh(&tunnel->hlist_lock);
tunnel->acpt_newsess = false;
for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
again:
hlist_for_each_entry_rcu(session, &tunnel->session_hlist[hash], hlist) {
hlist_del_init_rcu(&session->hlist);
spin_unlock_bh(&tunnel->hlist_lock);
l2tp_session_delete(session);
spin_lock_bh(&tunnel->hlist_lock);
/* Now restart from the beginning of this hash
* chain. We always remove a session from the
* list so we are guaranteed to make forward
* progress.
*/
goto again;
}
}
spin_unlock_bh(&tunnel->hlist_lock);
}
/* Tunnel socket destroy hook for UDP encapsulation */
static void l2tp_udp_encap_destroy(struct sock *sk)
{
struct l2tp_tunnel *tunnel = l2tp_sk_to_tunnel(sk);
if (tunnel)
l2tp_tunnel_delete(tunnel);
}
static void l2tp_tunnel_remove(struct net *net, struct l2tp_tunnel *tunnel)
{
struct l2tp_net *pn = l2tp_pernet(net);
spin_lock_bh(&pn->l2tp_tunnel_idr_lock);
idr_remove(&pn->l2tp_tunnel_idr, tunnel->tunnel_id);
spin_unlock_bh(&pn->l2tp_tunnel_idr_lock);
}
/* Workqueue tunnel deletion function */
static void l2tp_tunnel_del_work(struct work_struct *work)
{
struct l2tp_tunnel *tunnel = container_of(work, struct l2tp_tunnel,
del_work);
struct sock *sk = tunnel->sock;
struct socket *sock = sk->sk_socket;
l2tp_tunnel_closeall(tunnel);
/* If the tunnel socket was created within the kernel, use
* the sk API to release it here.
*/
if (tunnel->fd < 0) {
if (sock) {
kernel_sock_shutdown(sock, SHUT_RDWR);
sock_release(sock);
}
}
l2tp_tunnel_remove(tunnel->l2tp_net, tunnel);
/* drop initial ref */
l2tp_tunnel_dec_refcount(tunnel);
/* drop workqueue ref */
l2tp_tunnel_dec_refcount(tunnel);
}
/* Create a socket for the tunnel, if one isn't set up by
* userspace. This is used for static tunnels where there is no
* managing L2TP daemon.
*
* Since we don't want these sockets to keep a namespace alive by
* themselves, we drop the socket's namespace refcount after creation.
* These sockets are freed when the namespace exits using the pernet
* exit hook.
*/
static int l2tp_tunnel_sock_create(struct net *net,
u32 tunnel_id,
u32 peer_tunnel_id,
struct l2tp_tunnel_cfg *cfg,
struct socket **sockp)
{
int err = -EINVAL;
struct socket *sock = NULL;
struct udp_port_cfg udp_conf;
switch (cfg->encap) {
case L2TP_ENCAPTYPE_UDP:
memset(&udp_conf, 0, sizeof(udp_conf));
#if IS_ENABLED(CONFIG_IPV6)
if (cfg->local_ip6 && cfg->peer_ip6) {
udp_conf.family = AF_INET6;
memcpy(&udp_conf.local_ip6, cfg->local_ip6,
sizeof(udp_conf.local_ip6));
memcpy(&udp_conf.peer_ip6, cfg->peer_ip6,
sizeof(udp_conf.peer_ip6));
udp_conf.use_udp6_tx_checksums =
!cfg->udp6_zero_tx_checksums;
udp_conf.use_udp6_rx_checksums =
!cfg->udp6_zero_rx_checksums;
} else
#endif
{
udp_conf.family = AF_INET;
udp_conf.local_ip = cfg->local_ip;
udp_conf.peer_ip = cfg->peer_ip;
udp_conf.use_udp_checksums = cfg->use_udp_checksums;
}
udp_conf.local_udp_port = htons(cfg->local_udp_port);
udp_conf.peer_udp_port = htons(cfg->peer_udp_port);
err = udp_sock_create(net, &udp_conf, &sock);
if (err < 0)
goto out;
break;
case L2TP_ENCAPTYPE_IP:
#if IS_ENABLED(CONFIG_IPV6)
if (cfg->local_ip6 && cfg->peer_ip6) {
struct sockaddr_l2tpip6 ip6_addr = {0};
err = sock_create_kern(net, AF_INET6, SOCK_DGRAM,
IPPROTO_L2TP, &sock);
if (err < 0)
goto out;
ip6_addr.l2tp_family = AF_INET6;
memcpy(&ip6_addr.l2tp_addr, cfg->local_ip6,
sizeof(ip6_addr.l2tp_addr));
ip6_addr.l2tp_conn_id = tunnel_id;
err = kernel_bind(sock, (struct sockaddr *)&ip6_addr,
sizeof(ip6_addr));
if (err < 0)
goto out;
ip6_addr.l2tp_family = AF_INET6;
memcpy(&ip6_addr.l2tp_addr, cfg->peer_ip6,
sizeof(ip6_addr.l2tp_addr));
ip6_addr.l2tp_conn_id = peer_tunnel_id;
err = kernel_connect(sock,
(struct sockaddr *)&ip6_addr,
sizeof(ip6_addr), 0);
if (err < 0)
goto out;
} else
#endif
{
struct sockaddr_l2tpip ip_addr = {0};
err = sock_create_kern(net, AF_INET, SOCK_DGRAM,
IPPROTO_L2TP, &sock);
if (err < 0)
goto out;
ip_addr.l2tp_family = AF_INET;
ip_addr.l2tp_addr = cfg->local_ip;
ip_addr.l2tp_conn_id = tunnel_id;
err = kernel_bind(sock, (struct sockaddr *)&ip_addr,
sizeof(ip_addr));
if (err < 0)
goto out;
ip_addr.l2tp_family = AF_INET;
ip_addr.l2tp_addr = cfg->peer_ip;
ip_addr.l2tp_conn_id = peer_tunnel_id;
err = kernel_connect(sock, (struct sockaddr *)&ip_addr,
sizeof(ip_addr), 0);
if (err < 0)
goto out;
}
break;
default:
goto out;
}
out:
*sockp = sock;
if (err < 0 && sock) {
kernel_sock_shutdown(sock, SHUT_RDWR);
sock_release(sock);
*sockp = NULL;
}
return err;
}
int l2tp_tunnel_create(int fd, int version, u32 tunnel_id, u32 peer_tunnel_id,
struct l2tp_tunnel_cfg *cfg, struct l2tp_tunnel **tunnelp)
{
struct l2tp_tunnel *tunnel = NULL;
int err;
enum l2tp_encap_type encap = L2TP_ENCAPTYPE_UDP;
if (cfg)
encap = cfg->encap;
tunnel = kzalloc(sizeof(*tunnel), GFP_KERNEL);
if (!tunnel) {
err = -ENOMEM;
goto err;
}
tunnel->version = version;
tunnel->tunnel_id = tunnel_id;
tunnel->peer_tunnel_id = peer_tunnel_id;
tunnel->magic = L2TP_TUNNEL_MAGIC;
sprintf(&tunnel->name[0], "tunl %u", tunnel_id);
spin_lock_init(&tunnel->hlist_lock);
tunnel->acpt_newsess = true;
tunnel->encap = encap;
refcount_set(&tunnel->ref_count, 1);
tunnel->fd = fd;
/* Init delete workqueue struct */
INIT_WORK(&tunnel->del_work, l2tp_tunnel_del_work);
INIT_LIST_HEAD(&tunnel->list);
err = 0;
err:
if (tunnelp)
*tunnelp = tunnel;
return err;
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_create);
static int l2tp_validate_socket(const struct sock *sk, const struct net *net,
enum l2tp_encap_type encap)
{
if (!net_eq(sock_net(sk), net))
return -EINVAL;
if (sk->sk_type != SOCK_DGRAM)
return -EPROTONOSUPPORT;
if (sk->sk_family != PF_INET && sk->sk_family != PF_INET6)
return -EPROTONOSUPPORT;
if ((encap == L2TP_ENCAPTYPE_UDP && sk->sk_protocol != IPPROTO_UDP) ||
(encap == L2TP_ENCAPTYPE_IP && sk->sk_protocol != IPPROTO_L2TP))
return -EPROTONOSUPPORT;
if (sk->sk_user_data)
return -EBUSY;
return 0;
}
int l2tp_tunnel_register(struct l2tp_tunnel *tunnel, struct net *net,
struct l2tp_tunnel_cfg *cfg)
{
struct l2tp_net *pn = l2tp_pernet(net);
u32 tunnel_id = tunnel->tunnel_id;
struct socket *sock;
struct sock *sk;
int ret;
spin_lock_bh(&pn->l2tp_tunnel_idr_lock);
ret = idr_alloc_u32(&pn->l2tp_tunnel_idr, NULL, &tunnel_id, tunnel_id,
GFP_ATOMIC);
spin_unlock_bh(&pn->l2tp_tunnel_idr_lock);
if (ret)
return ret == -ENOSPC ? -EEXIST : ret;
if (tunnel->fd < 0) {
ret = l2tp_tunnel_sock_create(net, tunnel->tunnel_id,
tunnel->peer_tunnel_id, cfg,
&sock);
if (ret < 0)
goto err;
} else {
sock = sockfd_lookup(tunnel->fd, &ret);
if (!sock)
goto err;
}
sk = sock->sk;
lock_sock(sk);
write_lock_bh(&sk->sk_callback_lock);
ret = l2tp_validate_socket(sk, net, tunnel->encap);
if (ret < 0)
goto err_inval_sock;
rcu_assign_sk_user_data(sk, tunnel);
write_unlock_bh(&sk->sk_callback_lock);
if (tunnel->encap == L2TP_ENCAPTYPE_UDP) {
struct udp_tunnel_sock_cfg udp_cfg = {
.sk_user_data = tunnel,
.encap_type = UDP_ENCAP_L2TPINUDP,
.encap_rcv = l2tp_udp_encap_recv,
.encap_destroy = l2tp_udp_encap_destroy,
};
setup_udp_tunnel_sock(net, sock, &udp_cfg);
}
tunnel->old_sk_destruct = sk->sk_destruct;
sk->sk_destruct = &l2tp_tunnel_destruct;
sk->sk_allocation = GFP_ATOMIC;
release_sock(sk);
sock_hold(sk);
tunnel->sock = sk;
tunnel->l2tp_net = net;
spin_lock_bh(&pn->l2tp_tunnel_idr_lock);
idr_replace(&pn->l2tp_tunnel_idr, tunnel, tunnel->tunnel_id);
spin_unlock_bh(&pn->l2tp_tunnel_idr_lock);
trace_register_tunnel(tunnel);
if (tunnel->fd >= 0)
sockfd_put(sock);
return 0;
err_inval_sock:
write_unlock_bh(&sk->sk_callback_lock);
release_sock(sk);
if (tunnel->fd < 0)
sock_release(sock);
else
sockfd_put(sock);
err:
l2tp_tunnel_remove(net, tunnel);
return ret;
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_register);
/* This function is used by the netlink TUNNEL_DELETE command.
*/
void l2tp_tunnel_delete(struct l2tp_tunnel *tunnel)
{
if (!test_and_set_bit(0, &tunnel->dead)) {
trace_delete_tunnel(tunnel);
l2tp_tunnel_inc_refcount(tunnel);
queue_work(l2tp_wq, &tunnel->del_work);
}
}
EXPORT_SYMBOL_GPL(l2tp_tunnel_delete);
void l2tp_session_delete(struct l2tp_session *session)
{
if (test_and_set_bit(0, &session->dead))
return;
trace_delete_session(session);
l2tp_session_unhash(session);
l2tp_session_queue_purge(session);
if (session->session_close)
(*session->session_close)(session);
l2tp_session_dec_refcount(session);
}
EXPORT_SYMBOL_GPL(l2tp_session_delete);
/* We come here whenever a session's send_seq, cookie_len or
* l2specific_type parameters are set.
*/
void l2tp_session_set_header_len(struct l2tp_session *session, int version)
{
if (version == L2TP_HDR_VER_2) {
session->hdr_len = 6;
if (session->send_seq)
session->hdr_len += 4;
} else {
session->hdr_len = 4 + session->cookie_len;
session->hdr_len += l2tp_get_l2specific_len(session);
if (session->tunnel->encap == L2TP_ENCAPTYPE_UDP)
session->hdr_len += 4;
}
}
EXPORT_SYMBOL_GPL(l2tp_session_set_header_len);
struct l2tp_session *l2tp_session_create(int priv_size, struct l2tp_tunnel *tunnel, u32 session_id,
u32 peer_session_id, struct l2tp_session_cfg *cfg)
{
struct l2tp_session *session;
session = kzalloc(sizeof(*session) + priv_size, GFP_KERNEL);
if (session) {
session->magic = L2TP_SESSION_MAGIC;
session->tunnel = tunnel;
session->session_id = session_id;
session->peer_session_id = peer_session_id;
session->nr = 0;
if (tunnel->version == L2TP_HDR_VER_2)
session->nr_max = 0xffff;
else
session->nr_max = 0xffffff;
session->nr_window_size = session->nr_max / 2;
session->nr_oos_count_max = 4;
/* Use NR of first received packet */
session->reorder_skip = 1;
sprintf(&session->name[0], "sess %u/%u",
tunnel->tunnel_id, session->session_id);
skb_queue_head_init(&session->reorder_q);
INIT_HLIST_NODE(&session->hlist);
INIT_HLIST_NODE(&session->global_hlist);
if (cfg) {
session->pwtype = cfg->pw_type;
session->send_seq = cfg->send_seq;
session->recv_seq = cfg->recv_seq;
session->lns_mode = cfg->lns_mode;
session->reorder_timeout = cfg->reorder_timeout;
session->l2specific_type = cfg->l2specific_type;
session->cookie_len = cfg->cookie_len;
memcpy(&session->cookie[0], &cfg->cookie[0], cfg->cookie_len);
session->peer_cookie_len = cfg->peer_cookie_len;
memcpy(&session->peer_cookie[0], &cfg->peer_cookie[0], cfg->peer_cookie_len);
}
l2tp_session_set_header_len(session, tunnel->version);
refcount_set(&session->ref_count, 1);
return session;
}
return ERR_PTR(-ENOMEM);
}
EXPORT_SYMBOL_GPL(l2tp_session_create);
/*****************************************************************************
* Init and cleanup
*****************************************************************************/
static __net_init int l2tp_init_net(struct net *net)
{
struct l2tp_net *pn = net_generic(net, l2tp_net_id);
int hash;
idr_init(&pn->l2tp_tunnel_idr);
spin_lock_init(&pn->l2tp_tunnel_idr_lock);
for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++)
INIT_HLIST_HEAD(&pn->l2tp_session_hlist[hash]);
spin_lock_init(&pn->l2tp_session_hlist_lock);
return 0;
}
static __net_exit void l2tp_exit_net(struct net *net)
{
struct l2tp_net *pn = l2tp_pernet(net);
struct l2tp_tunnel *tunnel = NULL;
unsigned long tunnel_id, tmp;
int hash;
rcu_read_lock_bh();
idr_for_each_entry_ul(&pn->l2tp_tunnel_idr, tunnel, tmp, tunnel_id) {
if (tunnel)
l2tp_tunnel_delete(tunnel);
}
rcu_read_unlock_bh();
if (l2tp_wq)
flush_workqueue(l2tp_wq);
rcu_barrier();
for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++)
WARN_ON_ONCE(!hlist_empty(&pn->l2tp_session_hlist[hash]));
idr_destroy(&pn->l2tp_tunnel_idr);
}
static struct pernet_operations l2tp_net_ops = {
.init = l2tp_init_net,
.exit = l2tp_exit_net,
.id = &l2tp_net_id,
.size = sizeof(struct l2tp_net),
};
static int __init l2tp_init(void)
{
int rc = 0;
rc = register_pernet_device(&l2tp_net_ops);
if (rc)
goto out;
l2tp_wq = alloc_workqueue("l2tp", WQ_UNBOUND, 0);
if (!l2tp_wq) {
pr_err("alloc_workqueue failed\n");
unregister_pernet_device(&l2tp_net_ops);
rc = -ENOMEM;
goto out;
}
pr_info("L2TP core driver, %s\n", L2TP_DRV_VERSION);
out:
return rc;
}
static void __exit l2tp_exit(void)
{
unregister_pernet_device(&l2tp_net_ops);
if (l2tp_wq) {
destroy_workqueue(l2tp_wq);
l2tp_wq = NULL;
}
}
module_init(l2tp_init);
module_exit(l2tp_exit);
MODULE_AUTHOR("James Chapman <[email protected]>");
MODULE_DESCRIPTION("L2TP core");
MODULE_LICENSE("GPL");
MODULE_VERSION(L2TP_DRV_VERSION);
| linux-master | net/l2tp/l2tp_core.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*****************************************************************************
* Linux PPP over L2TP (PPPoX/PPPoL2TP) Sockets
*
* PPPoX --- Generic PPP encapsulation socket family
* PPPoL2TP --- PPP over L2TP (RFC 2661)
*
* Version: 2.0.0
*
* Authors: James Chapman ([email protected])
*
* Based on original work by Martijn van Oosterhout <[email protected]>
*
* License:
*/
/* This driver handles only L2TP data frames; control frames are handled by a
* userspace application.
*
* To send data in an L2TP session, userspace opens a PPPoL2TP socket and
* attaches it to a bound UDP socket with local tunnel_id / session_id and
* peer tunnel_id / session_id set. Data can then be sent or received using
* regular socket sendmsg() / recvmsg() calls. Kernel parameters of the socket
* can be read or modified using ioctl() or [gs]etsockopt() calls.
*
* When a PPPoL2TP socket is connected with local and peer session_id values
* zero, the socket is treated as a special tunnel management socket.
*
* Here's example userspace code to create a socket for sending/receiving data
* over an L2TP session:-
*
* struct sockaddr_pppol2tp sax;
* int fd;
* int session_fd;
*
* fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP);
*
* sax.sa_family = AF_PPPOX;
* sax.sa_protocol = PX_PROTO_OL2TP;
* sax.pppol2tp.fd = tunnel_fd; // bound UDP socket
* sax.pppol2tp.addr.sin_addr.s_addr = addr->sin_addr.s_addr;
* sax.pppol2tp.addr.sin_port = addr->sin_port;
* sax.pppol2tp.addr.sin_family = AF_INET;
* sax.pppol2tp.s_tunnel = tunnel_id;
* sax.pppol2tp.s_session = session_id;
* sax.pppol2tp.d_tunnel = peer_tunnel_id;
* sax.pppol2tp.d_session = peer_session_id;
*
* session_fd = connect(fd, (struct sockaddr *)&sax, sizeof(sax));
*
* A pppd plugin that allows PPP traffic to be carried over L2TP using
* this driver is available from the OpenL2TP project at
* http://openl2tp.sourceforge.net.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/string.h>
#include <linux/list.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/jiffies.h>
#include <linux/netdevice.h>
#include <linux/net.h>
#include <linux/inetdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <linux/if_pppox.h>
#include <linux/if_pppol2tp.h>
#include <net/sock.h>
#include <linux/ppp_channel.h>
#include <linux/ppp_defs.h>
#include <linux/ppp-ioctl.h>
#include <linux/file.h>
#include <linux/hash.h>
#include <linux/sort.h>
#include <linux/proc_fs.h>
#include <linux/l2tp.h>
#include <linux/nsproxy.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/ip.h>
#include <net/udp.h>
#include <net/inet_common.h>
#include <asm/byteorder.h>
#include <linux/atomic.h>
#include "l2tp_core.h"
#define PPPOL2TP_DRV_VERSION "V2.0"
/* Space for UDP, L2TP and PPP headers */
#define PPPOL2TP_HEADER_OVERHEAD 40
/* Number of bytes to build transmit L2TP headers.
* Unfortunately the size is different depending on whether sequence numbers
* are enabled.
*/
#define PPPOL2TP_L2TP_HDR_SIZE_SEQ 10
#define PPPOL2TP_L2TP_HDR_SIZE_NOSEQ 6
/* Private data of each session. This data lives at the end of struct
* l2tp_session, referenced via session->priv[].
*/
struct pppol2tp_session {
int owner; /* pid that opened the socket */
struct mutex sk_lock; /* Protects .sk */
struct sock __rcu *sk; /* Pointer to the session PPPoX socket */
struct sock *__sk; /* Copy of .sk, for cleanup */
struct rcu_head rcu; /* For asynchronous release */
};
static int pppol2tp_xmit(struct ppp_channel *chan, struct sk_buff *skb);
static const struct ppp_channel_ops pppol2tp_chan_ops = {
.start_xmit = pppol2tp_xmit,
};
static const struct proto_ops pppol2tp_ops;
/* Retrieves the pppol2tp socket associated to a session.
* A reference is held on the returned socket, so this function must be paired
* with sock_put().
*/
static struct sock *pppol2tp_session_get_sock(struct l2tp_session *session)
{
struct pppol2tp_session *ps = l2tp_session_priv(session);
struct sock *sk;
rcu_read_lock();
sk = rcu_dereference(ps->sk);
if (sk)
sock_hold(sk);
rcu_read_unlock();
return sk;
}
/* Helpers to obtain tunnel/session contexts from sockets.
*/
static inline struct l2tp_session *pppol2tp_sock_to_session(struct sock *sk)
{
struct l2tp_session *session;
if (!sk)
return NULL;
sock_hold(sk);
session = (struct l2tp_session *)(sk->sk_user_data);
if (!session) {
sock_put(sk);
goto out;
}
if (WARN_ON(session->magic != L2TP_SESSION_MAGIC)) {
session = NULL;
sock_put(sk);
goto out;
}
out:
return session;
}
/*****************************************************************************
* Receive data handling
*****************************************************************************/
/* Receive message. This is the recvmsg for the PPPoL2TP socket.
*/
static int pppol2tp_recvmsg(struct socket *sock, struct msghdr *msg,
size_t len, int flags)
{
int err;
struct sk_buff *skb;
struct sock *sk = sock->sk;
err = -EIO;
if (sk->sk_state & PPPOX_BOUND)
goto end;
err = 0;
skb = skb_recv_datagram(sk, flags, &err);
if (!skb)
goto end;
if (len > skb->len)
len = skb->len;
else if (len < skb->len)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_msg(skb, 0, msg, len);
if (likely(err == 0))
err = len;
kfree_skb(skb);
end:
return err;
}
static void pppol2tp_recv(struct l2tp_session *session, struct sk_buff *skb, int data_len)
{
struct pppol2tp_session *ps = l2tp_session_priv(session);
struct sock *sk = NULL;
/* If the socket is bound, send it in to PPP's input queue. Otherwise
* queue it on the session socket.
*/
rcu_read_lock();
sk = rcu_dereference(ps->sk);
if (!sk)
goto no_sock;
/* If the first two bytes are 0xFF03, consider that it is the PPP's
* Address and Control fields and skip them. The L2TP module has always
* worked this way, although, in theory, the use of these fields should
* be negotiated and handled at the PPP layer. These fields are
* constant: 0xFF is the All-Stations Address and 0x03 the Unnumbered
* Information command with Poll/Final bit set to zero (RFC 1662).
*/
if (pskb_may_pull(skb, 2) && skb->data[0] == PPP_ALLSTATIONS &&
skb->data[1] == PPP_UI)
skb_pull(skb, 2);
if (sk->sk_state & PPPOX_BOUND) {
struct pppox_sock *po;
po = pppox_sk(sk);
ppp_input(&po->chan, skb);
} else {
if (sock_queue_rcv_skb(sk, skb) < 0) {
atomic_long_inc(&session->stats.rx_errors);
kfree_skb(skb);
}
}
rcu_read_unlock();
return;
no_sock:
rcu_read_unlock();
pr_warn_ratelimited("%s: no socket in recv\n", session->name);
kfree_skb(skb);
}
/************************************************************************
* Transmit handling
***********************************************************************/
/* This is the sendmsg for the PPPoL2TP pppol2tp_session socket. We come here
* when a user application does a sendmsg() on the session socket. L2TP and
* PPP headers must be inserted into the user's data.
*/
static int pppol2tp_sendmsg(struct socket *sock, struct msghdr *m,
size_t total_len)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int error;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
int uhlen;
error = -ENOTCONN;
if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED))
goto error;
/* Get session and tunnel contexts */
error = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (!session)
goto error;
tunnel = session->tunnel;
uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
/* Allocate a socket buffer */
error = -ENOMEM;
skb = sock_wmalloc(sk, NET_SKB_PAD + sizeof(struct iphdr) +
uhlen + session->hdr_len +
2 + total_len, /* 2 bytes for PPP_ALLSTATIONS & PPP_UI */
0, GFP_KERNEL);
if (!skb)
goto error_put_sess;
/* Reserve space for headers. */
skb_reserve(skb, NET_SKB_PAD);
skb_reset_network_header(skb);
skb_reserve(skb, sizeof(struct iphdr));
skb_reset_transport_header(skb);
skb_reserve(skb, uhlen);
/* Add PPP header */
skb->data[0] = PPP_ALLSTATIONS;
skb->data[1] = PPP_UI;
skb_put(skb, 2);
/* Copy user data into skb */
error = memcpy_from_msg(skb_put(skb, total_len), m, total_len);
if (error < 0) {
kfree_skb(skb);
goto error_put_sess;
}
local_bh_disable();
l2tp_xmit_skb(session, skb);
local_bh_enable();
sock_put(sk);
return total_len;
error_put_sess:
sock_put(sk);
error:
return error;
}
/* Transmit function called by generic PPP driver. Sends PPP frame
* over PPPoL2TP socket.
*
* This is almost the same as pppol2tp_sendmsg(), but rather than
* being called with a msghdr from userspace, it is called with a skb
* from the kernel.
*
* The supplied skb from ppp doesn't have enough headroom for the
* insertion of L2TP, UDP and IP headers so we need to allocate more
* headroom in the skb. This will create a cloned skb. But we must be
* careful in the error case because the caller will expect to free
* the skb it supplied, not our cloned skb. So we take care to always
* leave the original skb unfreed if we return an error.
*/
static int pppol2tp_xmit(struct ppp_channel *chan, struct sk_buff *skb)
{
struct sock *sk = (struct sock *)chan->private;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
int uhlen, headroom;
if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED))
goto abort;
/* Get session and tunnel contexts from the socket */
session = pppol2tp_sock_to_session(sk);
if (!session)
goto abort;
tunnel = session->tunnel;
uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
headroom = NET_SKB_PAD +
sizeof(struct iphdr) + /* IP header */
uhlen + /* UDP header (if L2TP_ENCAPTYPE_UDP) */
session->hdr_len + /* L2TP header */
2; /* 2 bytes for PPP_ALLSTATIONS & PPP_UI */
if (skb_cow_head(skb, headroom))
goto abort_put_sess;
/* Setup PPP header */
__skb_push(skb, 2);
skb->data[0] = PPP_ALLSTATIONS;
skb->data[1] = PPP_UI;
local_bh_disable();
l2tp_xmit_skb(session, skb);
local_bh_enable();
sock_put(sk);
return 1;
abort_put_sess:
sock_put(sk);
abort:
/* Free the original skb */
kfree_skb(skb);
return 1;
}
/*****************************************************************************
* Session (and tunnel control) socket create/destroy.
*****************************************************************************/
static void pppol2tp_put_sk(struct rcu_head *head)
{
struct pppol2tp_session *ps;
ps = container_of(head, typeof(*ps), rcu);
sock_put(ps->__sk);
}
/* Really kill the session socket. (Called from sock_put() if
* refcnt == 0.)
*/
static void pppol2tp_session_destruct(struct sock *sk)
{
struct l2tp_session *session = sk->sk_user_data;
skb_queue_purge(&sk->sk_receive_queue);
skb_queue_purge(&sk->sk_write_queue);
if (session) {
sk->sk_user_data = NULL;
if (WARN_ON(session->magic != L2TP_SESSION_MAGIC))
return;
l2tp_session_dec_refcount(session);
}
}
/* Called when the PPPoX socket (session) is closed.
*/
static int pppol2tp_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
int error;
if (!sk)
return 0;
error = -EBADF;
lock_sock(sk);
if (sock_flag(sk, SOCK_DEAD) != 0)
goto error;
pppox_unbind_sock(sk);
/* Signal the death of the socket. */
sk->sk_state = PPPOX_DEAD;
sock_orphan(sk);
sock->sk = NULL;
session = pppol2tp_sock_to_session(sk);
if (session) {
struct pppol2tp_session *ps;
l2tp_session_delete(session);
ps = l2tp_session_priv(session);
mutex_lock(&ps->sk_lock);
ps->__sk = rcu_dereference_protected(ps->sk,
lockdep_is_held(&ps->sk_lock));
RCU_INIT_POINTER(ps->sk, NULL);
mutex_unlock(&ps->sk_lock);
call_rcu(&ps->rcu, pppol2tp_put_sk);
/* Rely on the sock_put() call at the end of the function for
* dropping the reference held by pppol2tp_sock_to_session().
* The last reference will be dropped by pppol2tp_put_sk().
*/
}
release_sock(sk);
/* This will delete the session context via
* pppol2tp_session_destruct() if the socket's refcnt drops to
* zero.
*/
sock_put(sk);
return 0;
error:
release_sock(sk);
return error;
}
static struct proto pppol2tp_sk_proto = {
.name = "PPPOL2TP",
.owner = THIS_MODULE,
.obj_size = sizeof(struct pppox_sock),
};
static int pppol2tp_backlog_recv(struct sock *sk, struct sk_buff *skb)
{
int rc;
rc = l2tp_udp_encap_recv(sk, skb);
if (rc)
kfree_skb(skb);
return NET_RX_SUCCESS;
}
/* socket() handler. Initialize a new struct sock.
*/
static int pppol2tp_create(struct net *net, struct socket *sock, int kern)
{
int error = -ENOMEM;
struct sock *sk;
sk = sk_alloc(net, PF_PPPOX, GFP_KERNEL, &pppol2tp_sk_proto, kern);
if (!sk)
goto out;
sock_init_data(sock, sk);
sock->state = SS_UNCONNECTED;
sock->ops = &pppol2tp_ops;
sk->sk_backlog_rcv = pppol2tp_backlog_recv;
sk->sk_protocol = PX_PROTO_OL2TP;
sk->sk_family = PF_PPPOX;
sk->sk_state = PPPOX_NONE;
sk->sk_type = SOCK_STREAM;
sk->sk_destruct = pppol2tp_session_destruct;
error = 0;
out:
return error;
}
static void pppol2tp_show(struct seq_file *m, void *arg)
{
struct l2tp_session *session = arg;
struct sock *sk;
sk = pppol2tp_session_get_sock(session);
if (sk) {
struct pppox_sock *po = pppox_sk(sk);
seq_printf(m, " interface %s\n", ppp_dev_name(&po->chan));
sock_put(sk);
}
}
static void pppol2tp_session_init(struct l2tp_session *session)
{
struct pppol2tp_session *ps;
session->recv_skb = pppol2tp_recv;
if (IS_ENABLED(CONFIG_L2TP_DEBUGFS))
session->show = pppol2tp_show;
ps = l2tp_session_priv(session);
mutex_init(&ps->sk_lock);
ps->owner = current->pid;
}
struct l2tp_connect_info {
u8 version;
int fd;
u32 tunnel_id;
u32 peer_tunnel_id;
u32 session_id;
u32 peer_session_id;
};
static int pppol2tp_sockaddr_get_info(const void *sa, int sa_len,
struct l2tp_connect_info *info)
{
switch (sa_len) {
case sizeof(struct sockaddr_pppol2tp):
{
const struct sockaddr_pppol2tp *sa_v2in4 = sa;
if (sa_v2in4->sa_protocol != PX_PROTO_OL2TP)
return -EINVAL;
info->version = 2;
info->fd = sa_v2in4->pppol2tp.fd;
info->tunnel_id = sa_v2in4->pppol2tp.s_tunnel;
info->peer_tunnel_id = sa_v2in4->pppol2tp.d_tunnel;
info->session_id = sa_v2in4->pppol2tp.s_session;
info->peer_session_id = sa_v2in4->pppol2tp.d_session;
break;
}
case sizeof(struct sockaddr_pppol2tpv3):
{
const struct sockaddr_pppol2tpv3 *sa_v3in4 = sa;
if (sa_v3in4->sa_protocol != PX_PROTO_OL2TP)
return -EINVAL;
info->version = 3;
info->fd = sa_v3in4->pppol2tp.fd;
info->tunnel_id = sa_v3in4->pppol2tp.s_tunnel;
info->peer_tunnel_id = sa_v3in4->pppol2tp.d_tunnel;
info->session_id = sa_v3in4->pppol2tp.s_session;
info->peer_session_id = sa_v3in4->pppol2tp.d_session;
break;
}
case sizeof(struct sockaddr_pppol2tpin6):
{
const struct sockaddr_pppol2tpin6 *sa_v2in6 = sa;
if (sa_v2in6->sa_protocol != PX_PROTO_OL2TP)
return -EINVAL;
info->version = 2;
info->fd = sa_v2in6->pppol2tp.fd;
info->tunnel_id = sa_v2in6->pppol2tp.s_tunnel;
info->peer_tunnel_id = sa_v2in6->pppol2tp.d_tunnel;
info->session_id = sa_v2in6->pppol2tp.s_session;
info->peer_session_id = sa_v2in6->pppol2tp.d_session;
break;
}
case sizeof(struct sockaddr_pppol2tpv3in6):
{
const struct sockaddr_pppol2tpv3in6 *sa_v3in6 = sa;
if (sa_v3in6->sa_protocol != PX_PROTO_OL2TP)
return -EINVAL;
info->version = 3;
info->fd = sa_v3in6->pppol2tp.fd;
info->tunnel_id = sa_v3in6->pppol2tp.s_tunnel;
info->peer_tunnel_id = sa_v3in6->pppol2tp.d_tunnel;
info->session_id = sa_v3in6->pppol2tp.s_session;
info->peer_session_id = sa_v3in6->pppol2tp.d_session;
break;
}
default:
return -EINVAL;
}
return 0;
}
/* Rough estimation of the maximum payload size a tunnel can transmit without
* fragmenting at the lower IP layer. Assumes L2TPv2 with sequence
* numbers and no IP option. Not quite accurate, but the result is mostly
* unused anyway.
*/
static int pppol2tp_tunnel_mtu(const struct l2tp_tunnel *tunnel)
{
int mtu;
mtu = l2tp_tunnel_dst_mtu(tunnel);
if (mtu <= PPPOL2TP_HEADER_OVERHEAD)
return 1500 - PPPOL2TP_HEADER_OVERHEAD;
return mtu - PPPOL2TP_HEADER_OVERHEAD;
}
static struct l2tp_tunnel *pppol2tp_tunnel_get(struct net *net,
const struct l2tp_connect_info *info,
bool *new_tunnel)
{
struct l2tp_tunnel *tunnel;
int error;
*new_tunnel = false;
tunnel = l2tp_tunnel_get(net, info->tunnel_id);
/* Special case: create tunnel context if session_id and
* peer_session_id is 0. Otherwise look up tunnel using supplied
* tunnel id.
*/
if (!info->session_id && !info->peer_session_id) {
if (!tunnel) {
struct l2tp_tunnel_cfg tcfg = {
.encap = L2TP_ENCAPTYPE_UDP,
};
/* Prevent l2tp_tunnel_register() from trying to set up
* a kernel socket.
*/
if (info->fd < 0)
return ERR_PTR(-EBADF);
error = l2tp_tunnel_create(info->fd,
info->version,
info->tunnel_id,
info->peer_tunnel_id, &tcfg,
&tunnel);
if (error < 0)
return ERR_PTR(error);
l2tp_tunnel_inc_refcount(tunnel);
error = l2tp_tunnel_register(tunnel, net, &tcfg);
if (error < 0) {
kfree(tunnel);
return ERR_PTR(error);
}
*new_tunnel = true;
}
} else {
/* Error if we can't find the tunnel */
if (!tunnel)
return ERR_PTR(-ENOENT);
/* Error if socket is not prepped */
if (!tunnel->sock) {
l2tp_tunnel_dec_refcount(tunnel);
return ERR_PTR(-ENOENT);
}
}
return tunnel;
}
/* connect() handler. Attach a PPPoX socket to a tunnel UDP socket
*/
static int pppol2tp_connect(struct socket *sock, struct sockaddr *uservaddr,
int sockaddr_len, int flags)
{
struct sock *sk = sock->sk;
struct pppox_sock *po = pppox_sk(sk);
struct l2tp_session *session = NULL;
struct l2tp_connect_info info;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
struct l2tp_session_cfg cfg = { 0, };
bool drop_refcnt = false;
bool new_session = false;
bool new_tunnel = false;
int error;
error = pppol2tp_sockaddr_get_info(uservaddr, sockaddr_len, &info);
if (error < 0)
return error;
/* Don't bind if tunnel_id is 0 */
if (!info.tunnel_id)
return -EINVAL;
tunnel = pppol2tp_tunnel_get(sock_net(sk), &info, &new_tunnel);
if (IS_ERR(tunnel))
return PTR_ERR(tunnel);
lock_sock(sk);
/* Check for already bound sockets */
error = -EBUSY;
if (sk->sk_state & PPPOX_CONNECTED)
goto end;
/* We don't supporting rebinding anyway */
error = -EALREADY;
if (sk->sk_user_data)
goto end; /* socket is already attached */
if (tunnel->peer_tunnel_id == 0)
tunnel->peer_tunnel_id = info.peer_tunnel_id;
session = l2tp_tunnel_get_session(tunnel, info.session_id);
if (session) {
drop_refcnt = true;
if (session->pwtype != L2TP_PWTYPE_PPP) {
error = -EPROTOTYPE;
goto end;
}
ps = l2tp_session_priv(session);
/* Using a pre-existing session is fine as long as it hasn't
* been connected yet.
*/
mutex_lock(&ps->sk_lock);
if (rcu_dereference_protected(ps->sk,
lockdep_is_held(&ps->sk_lock)) ||
ps->__sk) {
mutex_unlock(&ps->sk_lock);
error = -EEXIST;
goto end;
}
} else {
cfg.pw_type = L2TP_PWTYPE_PPP;
session = l2tp_session_create(sizeof(struct pppol2tp_session),
tunnel, info.session_id,
info.peer_session_id, &cfg);
if (IS_ERR(session)) {
error = PTR_ERR(session);
goto end;
}
pppol2tp_session_init(session);
ps = l2tp_session_priv(session);
l2tp_session_inc_refcount(session);
mutex_lock(&ps->sk_lock);
error = l2tp_session_register(session, tunnel);
if (error < 0) {
mutex_unlock(&ps->sk_lock);
kfree(session);
goto end;
}
drop_refcnt = true;
new_session = true;
}
/* Special case: if source & dest session_id == 0x0000, this
* socket is being created to manage the tunnel. Just set up
* the internal context for use by ioctl() and sockopt()
* handlers.
*/
if (session->session_id == 0 && session->peer_session_id == 0) {
error = 0;
goto out_no_ppp;
}
/* The only header we need to worry about is the L2TP
* header. This size is different depending on whether
* sequence numbers are enabled for the data channel.
*/
po->chan.hdrlen = PPPOL2TP_L2TP_HDR_SIZE_NOSEQ;
po->chan.private = sk;
po->chan.ops = &pppol2tp_chan_ops;
po->chan.mtu = pppol2tp_tunnel_mtu(tunnel);
error = ppp_register_net_channel(sock_net(sk), &po->chan);
if (error) {
mutex_unlock(&ps->sk_lock);
goto end;
}
out_no_ppp:
/* This is how we get the session context from the socket. */
sk->sk_user_data = session;
rcu_assign_pointer(ps->sk, sk);
mutex_unlock(&ps->sk_lock);
/* Keep the reference we've grabbed on the session: sk doesn't expect
* the session to disappear. pppol2tp_session_destruct() is responsible
* for dropping it.
*/
drop_refcnt = false;
sk->sk_state = PPPOX_CONNECTED;
end:
if (error) {
if (new_session)
l2tp_session_delete(session);
if (new_tunnel)
l2tp_tunnel_delete(tunnel);
}
if (drop_refcnt)
l2tp_session_dec_refcount(session);
l2tp_tunnel_dec_refcount(tunnel);
release_sock(sk);
return error;
}
#ifdef CONFIG_L2TP_V3
/* Called when creating sessions via the netlink interface. */
static int pppol2tp_session_create(struct net *net, struct l2tp_tunnel *tunnel,
u32 session_id, u32 peer_session_id,
struct l2tp_session_cfg *cfg)
{
int error;
struct l2tp_session *session;
/* Error if tunnel socket is not prepped */
if (!tunnel->sock) {
error = -ENOENT;
goto err;
}
/* Allocate and initialize a new session context. */
session = l2tp_session_create(sizeof(struct pppol2tp_session),
tunnel, session_id,
peer_session_id, cfg);
if (IS_ERR(session)) {
error = PTR_ERR(session);
goto err;
}
pppol2tp_session_init(session);
error = l2tp_session_register(session, tunnel);
if (error < 0)
goto err_sess;
return 0;
err_sess:
kfree(session);
err:
return error;
}
#endif /* CONFIG_L2TP_V3 */
/* getname() support.
*/
static int pppol2tp_getname(struct socket *sock, struct sockaddr *uaddr,
int peer)
{
int len = 0;
int error = 0;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct sock *sk = sock->sk;
struct inet_sock *inet;
struct pppol2tp_session *pls;
error = -ENOTCONN;
if (!sk)
goto end;
if (!(sk->sk_state & PPPOX_CONNECTED))
goto end;
error = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (!session)
goto end;
pls = l2tp_session_priv(session);
tunnel = session->tunnel;
inet = inet_sk(tunnel->sock);
if (tunnel->version == 2 && tunnel->sock->sk_family == AF_INET) {
struct sockaddr_pppol2tp sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin_family = AF_INET;
sp.pppol2tp.addr.sin_port = inet->inet_dport;
sp.pppol2tp.addr.sin_addr.s_addr = inet->inet_daddr;
memcpy(uaddr, &sp, len);
#if IS_ENABLED(CONFIG_IPV6)
} else if (tunnel->version == 2 && tunnel->sock->sk_family == AF_INET6) {
struct sockaddr_pppol2tpin6 sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin6_family = AF_INET6;
sp.pppol2tp.addr.sin6_port = inet->inet_dport;
memcpy(&sp.pppol2tp.addr.sin6_addr, &tunnel->sock->sk_v6_daddr,
sizeof(tunnel->sock->sk_v6_daddr));
memcpy(uaddr, &sp, len);
} else if (tunnel->version == 3 && tunnel->sock->sk_family == AF_INET6) {
struct sockaddr_pppol2tpv3in6 sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin6_family = AF_INET6;
sp.pppol2tp.addr.sin6_port = inet->inet_dport;
memcpy(&sp.pppol2tp.addr.sin6_addr, &tunnel->sock->sk_v6_daddr,
sizeof(tunnel->sock->sk_v6_daddr));
memcpy(uaddr, &sp, len);
#endif
} else if (tunnel->version == 3) {
struct sockaddr_pppol2tpv3 sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin_family = AF_INET;
sp.pppol2tp.addr.sin_port = inet->inet_dport;
sp.pppol2tp.addr.sin_addr.s_addr = inet->inet_daddr;
memcpy(uaddr, &sp, len);
}
error = len;
sock_put(sk);
end:
return error;
}
/****************************************************************************
* ioctl() handlers.
*
* The PPPoX socket is created for L2TP sessions: tunnels have their own UDP
* sockets. However, in order to control kernel tunnel features, we allow
* userspace to create a special "tunnel" PPPoX socket which is used for
* control only. Tunnel PPPoX sockets have session_id == 0 and simply allow
* the user application to issue L2TP setsockopt(), getsockopt() and ioctl()
* calls.
****************************************************************************/
static void pppol2tp_copy_stats(struct pppol2tp_ioc_stats *dest,
const struct l2tp_stats *stats)
{
memset(dest, 0, sizeof(*dest));
dest->tx_packets = atomic_long_read(&stats->tx_packets);
dest->tx_bytes = atomic_long_read(&stats->tx_bytes);
dest->tx_errors = atomic_long_read(&stats->tx_errors);
dest->rx_packets = atomic_long_read(&stats->rx_packets);
dest->rx_bytes = atomic_long_read(&stats->rx_bytes);
dest->rx_seq_discards = atomic_long_read(&stats->rx_seq_discards);
dest->rx_oos_packets = atomic_long_read(&stats->rx_oos_packets);
dest->rx_errors = atomic_long_read(&stats->rx_errors);
}
static int pppol2tp_tunnel_copy_stats(struct pppol2tp_ioc_stats *stats,
struct l2tp_tunnel *tunnel)
{
struct l2tp_session *session;
if (!stats->session_id) {
pppol2tp_copy_stats(stats, &tunnel->stats);
return 0;
}
/* If session_id is set, search the corresponding session in the
* context of this tunnel and record the session's statistics.
*/
session = l2tp_tunnel_get_session(tunnel, stats->session_id);
if (!session)
return -EBADR;
if (session->pwtype != L2TP_PWTYPE_PPP) {
l2tp_session_dec_refcount(session);
return -EBADR;
}
pppol2tp_copy_stats(stats, &session->stats);
l2tp_session_dec_refcount(session);
return 0;
}
static int pppol2tp_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct pppol2tp_ioc_stats stats;
struct l2tp_session *session;
switch (cmd) {
case PPPIOCGMRU:
case PPPIOCGFLAGS:
session = sock->sk->sk_user_data;
if (!session)
return -ENOTCONN;
if (WARN_ON(session->magic != L2TP_SESSION_MAGIC))
return -EBADF;
/* Not defined for tunnels */
if (!session->session_id && !session->peer_session_id)
return -ENOSYS;
if (put_user(0, (int __user *)arg))
return -EFAULT;
break;
case PPPIOCSMRU:
case PPPIOCSFLAGS:
session = sock->sk->sk_user_data;
if (!session)
return -ENOTCONN;
if (WARN_ON(session->magic != L2TP_SESSION_MAGIC))
return -EBADF;
/* Not defined for tunnels */
if (!session->session_id && !session->peer_session_id)
return -ENOSYS;
if (!access_ok((int __user *)arg, sizeof(int)))
return -EFAULT;
break;
case PPPIOCGL2TPSTATS:
session = sock->sk->sk_user_data;
if (!session)
return -ENOTCONN;
if (WARN_ON(session->magic != L2TP_SESSION_MAGIC))
return -EBADF;
/* Session 0 represents the parent tunnel */
if (!session->session_id && !session->peer_session_id) {
u32 session_id;
int err;
if (copy_from_user(&stats, (void __user *)arg,
sizeof(stats)))
return -EFAULT;
session_id = stats.session_id;
err = pppol2tp_tunnel_copy_stats(&stats,
session->tunnel);
if (err < 0)
return err;
stats.session_id = session_id;
} else {
pppol2tp_copy_stats(&stats, &session->stats);
stats.session_id = session->session_id;
}
stats.tunnel_id = session->tunnel->tunnel_id;
stats.using_ipsec = l2tp_tunnel_uses_xfrm(session->tunnel);
if (copy_to_user((void __user *)arg, &stats, sizeof(stats)))
return -EFAULT;
break;
default:
return -ENOIOCTLCMD;
}
return 0;
}
/*****************************************************************************
* setsockopt() / getsockopt() support.
*
* The PPPoX socket is created for L2TP sessions: tunnels have their own UDP
* sockets. In order to control kernel tunnel features, we allow userspace to
* create a special "tunnel" PPPoX socket which is used for control only.
* Tunnel PPPoX sockets have session_id == 0 and simply allow the user
* application to issue L2TP setsockopt(), getsockopt() and ioctl() calls.
*****************************************************************************/
/* Tunnel setsockopt() helper.
*/
static int pppol2tp_tunnel_setsockopt(struct sock *sk,
struct l2tp_tunnel *tunnel,
int optname, int val)
{
int err = 0;
switch (optname) {
case PPPOL2TP_SO_DEBUG:
/* Tunnel debug flags option is deprecated */
break;
default:
err = -ENOPROTOOPT;
break;
}
return err;
}
/* Session setsockopt helper.
*/
static int pppol2tp_session_setsockopt(struct sock *sk,
struct l2tp_session *session,
int optname, int val)
{
int err = 0;
switch (optname) {
case PPPOL2TP_SO_RECVSEQ:
if (val != 0 && val != 1) {
err = -EINVAL;
break;
}
session->recv_seq = !!val;
break;
case PPPOL2TP_SO_SENDSEQ:
if (val != 0 && val != 1) {
err = -EINVAL;
break;
}
session->send_seq = !!val;
{
struct pppox_sock *po = pppox_sk(sk);
po->chan.hdrlen = val ? PPPOL2TP_L2TP_HDR_SIZE_SEQ :
PPPOL2TP_L2TP_HDR_SIZE_NOSEQ;
}
l2tp_session_set_header_len(session, session->tunnel->version);
break;
case PPPOL2TP_SO_LNSMODE:
if (val != 0 && val != 1) {
err = -EINVAL;
break;
}
session->lns_mode = !!val;
break;
case PPPOL2TP_SO_DEBUG:
/* Session debug flags option is deprecated */
break;
case PPPOL2TP_SO_REORDERTO:
session->reorder_timeout = msecs_to_jiffies(val);
break;
default:
err = -ENOPROTOOPT;
break;
}
return err;
}
/* Main setsockopt() entry point.
* Does API checks, then calls either the tunnel or session setsockopt
* handler, according to whether the PPPoL2TP socket is a for a regular
* session or the special tunnel type.
*/
static int pppol2tp_setsockopt(struct socket *sock, int level, int optname,
sockptr_t optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
int val;
int err;
if (level != SOL_PPPOL2TP)
return -EINVAL;
if (optlen < sizeof(int))
return -EINVAL;
if (copy_from_sockptr(&val, optval, sizeof(int)))
return -EFAULT;
err = -ENOTCONN;
if (!sk->sk_user_data)
goto end;
/* Get session context from the socket */
err = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (!session)
goto end;
/* Special case: if session_id == 0x0000, treat as operation on tunnel
*/
if (session->session_id == 0 && session->peer_session_id == 0) {
tunnel = session->tunnel;
err = pppol2tp_tunnel_setsockopt(sk, tunnel, optname, val);
} else {
err = pppol2tp_session_setsockopt(sk, session, optname, val);
}
sock_put(sk);
end:
return err;
}
/* Tunnel getsockopt helper. Called with sock locked.
*/
static int pppol2tp_tunnel_getsockopt(struct sock *sk,
struct l2tp_tunnel *tunnel,
int optname, int *val)
{
int err = 0;
switch (optname) {
case PPPOL2TP_SO_DEBUG:
/* Tunnel debug flags option is deprecated */
*val = 0;
break;
default:
err = -ENOPROTOOPT;
break;
}
return err;
}
/* Session getsockopt helper. Called with sock locked.
*/
static int pppol2tp_session_getsockopt(struct sock *sk,
struct l2tp_session *session,
int optname, int *val)
{
int err = 0;
switch (optname) {
case PPPOL2TP_SO_RECVSEQ:
*val = session->recv_seq;
break;
case PPPOL2TP_SO_SENDSEQ:
*val = session->send_seq;
break;
case PPPOL2TP_SO_LNSMODE:
*val = session->lns_mode;
break;
case PPPOL2TP_SO_DEBUG:
/* Session debug flags option is deprecated */
*val = 0;
break;
case PPPOL2TP_SO_REORDERTO:
*val = (int)jiffies_to_msecs(session->reorder_timeout);
break;
default:
err = -ENOPROTOOPT;
}
return err;
}
/* Main getsockopt() entry point.
* Does API checks, then calls either the tunnel or session getsockopt
* handler, according to whether the PPPoX socket is a for a regular session
* or the special tunnel type.
*/
static int pppol2tp_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
int val, len;
int err;
if (level != SOL_PPPOL2TP)
return -EINVAL;
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, sizeof(int));
if (len < 0)
return -EINVAL;
err = -ENOTCONN;
if (!sk->sk_user_data)
goto end;
/* Get the session context */
err = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (!session)
goto end;
/* Special case: if session_id == 0x0000, treat as operation on tunnel */
if (session->session_id == 0 && session->peer_session_id == 0) {
tunnel = session->tunnel;
err = pppol2tp_tunnel_getsockopt(sk, tunnel, optname, &val);
if (err)
goto end_put_sess;
} else {
err = pppol2tp_session_getsockopt(sk, session, optname, &val);
if (err)
goto end_put_sess;
}
err = -EFAULT;
if (put_user(len, optlen))
goto end_put_sess;
if (copy_to_user((void __user *)optval, &val, len))
goto end_put_sess;
err = 0;
end_put_sess:
sock_put(sk);
end:
return err;
}
/*****************************************************************************
* /proc filesystem for debug
* Since the original pppol2tp driver provided /proc/net/pppol2tp for
* L2TPv2, we dump only L2TPv2 tunnels and sessions here.
*****************************************************************************/
static unsigned int pppol2tp_net_id;
#ifdef CONFIG_PROC_FS
struct pppol2tp_seq_data {
struct seq_net_private p;
int tunnel_idx; /* current tunnel */
int session_idx; /* index of session within current tunnel */
struct l2tp_tunnel *tunnel;
struct l2tp_session *session; /* NULL means get next tunnel */
};
static void pppol2tp_next_tunnel(struct net *net, struct pppol2tp_seq_data *pd)
{
/* Drop reference taken during previous invocation */
if (pd->tunnel)
l2tp_tunnel_dec_refcount(pd->tunnel);
for (;;) {
pd->tunnel = l2tp_tunnel_get_nth(net, pd->tunnel_idx);
pd->tunnel_idx++;
/* Only accept L2TPv2 tunnels */
if (!pd->tunnel || pd->tunnel->version == 2)
return;
l2tp_tunnel_dec_refcount(pd->tunnel);
}
}
static void pppol2tp_next_session(struct net *net, struct pppol2tp_seq_data *pd)
{
/* Drop reference taken during previous invocation */
if (pd->session)
l2tp_session_dec_refcount(pd->session);
pd->session = l2tp_session_get_nth(pd->tunnel, pd->session_idx);
pd->session_idx++;
if (!pd->session) {
pd->session_idx = 0;
pppol2tp_next_tunnel(net, pd);
}
}
static void *pppol2tp_seq_start(struct seq_file *m, loff_t *offs)
{
struct pppol2tp_seq_data *pd = SEQ_START_TOKEN;
loff_t pos = *offs;
struct net *net;
if (!pos)
goto out;
if (WARN_ON(!m->private)) {
pd = NULL;
goto out;
}
pd = m->private;
net = seq_file_net(m);
if (!pd->tunnel)
pppol2tp_next_tunnel(net, pd);
else
pppol2tp_next_session(net, pd);
/* NULL tunnel and session indicates end of list */
if (!pd->tunnel && !pd->session)
pd = NULL;
out:
return pd;
}
static void *pppol2tp_seq_next(struct seq_file *m, void *v, loff_t *pos)
{
(*pos)++;
return NULL;
}
static void pppol2tp_seq_stop(struct seq_file *p, void *v)
{
struct pppol2tp_seq_data *pd = v;
if (!pd || pd == SEQ_START_TOKEN)
return;
/* Drop reference taken by last invocation of pppol2tp_next_session()
* or pppol2tp_next_tunnel().
*/
if (pd->session) {
l2tp_session_dec_refcount(pd->session);
pd->session = NULL;
}
if (pd->tunnel) {
l2tp_tunnel_dec_refcount(pd->tunnel);
pd->tunnel = NULL;
}
}
static void pppol2tp_seq_tunnel_show(struct seq_file *m, void *v)
{
struct l2tp_tunnel *tunnel = v;
seq_printf(m, "\nTUNNEL '%s', %c %d\n",
tunnel->name,
(tunnel == tunnel->sock->sk_user_data) ? 'Y' : 'N',
refcount_read(&tunnel->ref_count) - 1);
seq_printf(m, " %08x %ld/%ld/%ld %ld/%ld/%ld\n",
0,
atomic_long_read(&tunnel->stats.tx_packets),
atomic_long_read(&tunnel->stats.tx_bytes),
atomic_long_read(&tunnel->stats.tx_errors),
atomic_long_read(&tunnel->stats.rx_packets),
atomic_long_read(&tunnel->stats.rx_bytes),
atomic_long_read(&tunnel->stats.rx_errors));
}
static void pppol2tp_seq_session_show(struct seq_file *m, void *v)
{
struct l2tp_session *session = v;
struct l2tp_tunnel *tunnel = session->tunnel;
unsigned char state;
char user_data_ok;
struct sock *sk;
u32 ip = 0;
u16 port = 0;
if (tunnel->sock) {
struct inet_sock *inet = inet_sk(tunnel->sock);
ip = ntohl(inet->inet_saddr);
port = ntohs(inet->inet_sport);
}
sk = pppol2tp_session_get_sock(session);
if (sk) {
state = sk->sk_state;
user_data_ok = (session == sk->sk_user_data) ? 'Y' : 'N';
} else {
state = 0;
user_data_ok = 'N';
}
seq_printf(m, " SESSION '%s' %08X/%d %04X/%04X -> %04X/%04X %d %c\n",
session->name, ip, port,
tunnel->tunnel_id,
session->session_id,
tunnel->peer_tunnel_id,
session->peer_session_id,
state, user_data_ok);
seq_printf(m, " 0/0/%c/%c/%s %08x %u\n",
session->recv_seq ? 'R' : '-',
session->send_seq ? 'S' : '-',
session->lns_mode ? "LNS" : "LAC",
0,
jiffies_to_msecs(session->reorder_timeout));
seq_printf(m, " %u/%u %ld/%ld/%ld %ld/%ld/%ld\n",
session->nr, session->ns,
atomic_long_read(&session->stats.tx_packets),
atomic_long_read(&session->stats.tx_bytes),
atomic_long_read(&session->stats.tx_errors),
atomic_long_read(&session->stats.rx_packets),
atomic_long_read(&session->stats.rx_bytes),
atomic_long_read(&session->stats.rx_errors));
if (sk) {
struct pppox_sock *po = pppox_sk(sk);
seq_printf(m, " interface %s\n", ppp_dev_name(&po->chan));
sock_put(sk);
}
}
static int pppol2tp_seq_show(struct seq_file *m, void *v)
{
struct pppol2tp_seq_data *pd = v;
/* display header on line 1 */
if (v == SEQ_START_TOKEN) {
seq_puts(m, "PPPoL2TP driver info, " PPPOL2TP_DRV_VERSION "\n");
seq_puts(m, "TUNNEL name, user-data-ok session-count\n");
seq_puts(m, " debug tx-pkts/bytes/errs rx-pkts/bytes/errs\n");
seq_puts(m, " SESSION name, addr/port src-tid/sid dest-tid/sid state user-data-ok\n");
seq_puts(m, " mtu/mru/rcvseq/sendseq/lns debug reorderto\n");
seq_puts(m, " nr/ns tx-pkts/bytes/errs rx-pkts/bytes/errs\n");
goto out;
}
if (!pd->session)
pppol2tp_seq_tunnel_show(m, pd->tunnel);
else
pppol2tp_seq_session_show(m, pd->session);
out:
return 0;
}
static const struct seq_operations pppol2tp_seq_ops = {
.start = pppol2tp_seq_start,
.next = pppol2tp_seq_next,
.stop = pppol2tp_seq_stop,
.show = pppol2tp_seq_show,
};
#endif /* CONFIG_PROC_FS */
/*****************************************************************************
* Network namespace
*****************************************************************************/
static __net_init int pppol2tp_init_net(struct net *net)
{
struct proc_dir_entry *pde;
int err = 0;
pde = proc_create_net("pppol2tp", 0444, net->proc_net,
&pppol2tp_seq_ops, sizeof(struct pppol2tp_seq_data));
if (!pde) {
err = -ENOMEM;
goto out;
}
out:
return err;
}
static __net_exit void pppol2tp_exit_net(struct net *net)
{
remove_proc_entry("pppol2tp", net->proc_net);
}
static struct pernet_operations pppol2tp_net_ops = {
.init = pppol2tp_init_net,
.exit = pppol2tp_exit_net,
.id = &pppol2tp_net_id,
};
/*****************************************************************************
* Init and cleanup
*****************************************************************************/
static const struct proto_ops pppol2tp_ops = {
.family = AF_PPPOX,
.owner = THIS_MODULE,
.release = pppol2tp_release,
.bind = sock_no_bind,
.connect = pppol2tp_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = pppol2tp_getname,
.poll = datagram_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = pppol2tp_setsockopt,
.getsockopt = pppol2tp_getsockopt,
.sendmsg = pppol2tp_sendmsg,
.recvmsg = pppol2tp_recvmsg,
.mmap = sock_no_mmap,
.ioctl = pppox_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = pppox_compat_ioctl,
#endif
};
static const struct pppox_proto pppol2tp_proto = {
.create = pppol2tp_create,
.ioctl = pppol2tp_ioctl,
.owner = THIS_MODULE,
};
#ifdef CONFIG_L2TP_V3
static const struct l2tp_nl_cmd_ops pppol2tp_nl_cmd_ops = {
.session_create = pppol2tp_session_create,
.session_delete = l2tp_session_delete,
};
#endif /* CONFIG_L2TP_V3 */
static int __init pppol2tp_init(void)
{
int err;
err = register_pernet_device(&pppol2tp_net_ops);
if (err)
goto out;
err = proto_register(&pppol2tp_sk_proto, 0);
if (err)
goto out_unregister_pppol2tp_pernet;
err = register_pppox_proto(PX_PROTO_OL2TP, &pppol2tp_proto);
if (err)
goto out_unregister_pppol2tp_proto;
#ifdef CONFIG_L2TP_V3
err = l2tp_nl_register_ops(L2TP_PWTYPE_PPP, &pppol2tp_nl_cmd_ops);
if (err)
goto out_unregister_pppox;
#endif
pr_info("PPPoL2TP kernel driver, %s\n", PPPOL2TP_DRV_VERSION);
out:
return err;
#ifdef CONFIG_L2TP_V3
out_unregister_pppox:
unregister_pppox_proto(PX_PROTO_OL2TP);
#endif
out_unregister_pppol2tp_proto:
proto_unregister(&pppol2tp_sk_proto);
out_unregister_pppol2tp_pernet:
unregister_pernet_device(&pppol2tp_net_ops);
goto out;
}
static void __exit pppol2tp_exit(void)
{
#ifdef CONFIG_L2TP_V3
l2tp_nl_unregister_ops(L2TP_PWTYPE_PPP);
#endif
unregister_pppox_proto(PX_PROTO_OL2TP);
proto_unregister(&pppol2tp_sk_proto);
unregister_pernet_device(&pppol2tp_net_ops);
}
module_init(pppol2tp_init);
module_exit(pppol2tp_exit);
MODULE_AUTHOR("James Chapman <[email protected]>");
MODULE_DESCRIPTION("PPP over L2TP over UDP");
MODULE_LICENSE("GPL");
MODULE_VERSION(PPPOL2TP_DRV_VERSION);
MODULE_ALIAS_NET_PF_PROTO(PF_PPPOX, PX_PROTO_OL2TP);
MODULE_ALIAS_L2TP_PWTYPE(7);
| linux-master | net/l2tp/l2tp_ppp.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* L2TPv3 ethernet pseudowire driver
*
* Copyright (c) 2008,2009,2010 Katalix Systems Ltd
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
#include <linux/hash.h>
#include <linux/l2tp.h>
#include <linux/in.h>
#include <linux/etherdevice.h>
#include <linux/spinlock.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/udp.h>
#include <net/inet_common.h>
#include <net/inet_hashtables.h>
#include <net/tcp_states.h>
#include <net/protocol.h>
#include <net/xfrm.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/udp.h>
#include "l2tp_core.h"
/* Default device name. May be overridden by name specified by user */
#define L2TP_ETH_DEV_NAME "l2tpeth%d"
/* via netdev_priv() */
struct l2tp_eth {
struct l2tp_session *session;
atomic_long_t tx_bytes;
atomic_long_t tx_packets;
atomic_long_t tx_dropped;
atomic_long_t rx_bytes;
atomic_long_t rx_packets;
atomic_long_t rx_errors;
};
/* via l2tp_session_priv() */
struct l2tp_eth_sess {
struct net_device __rcu *dev;
};
static int l2tp_eth_dev_init(struct net_device *dev)
{
eth_hw_addr_random(dev);
eth_broadcast_addr(dev->broadcast);
netdev_lockdep_set_classes(dev);
return 0;
}
static void l2tp_eth_dev_uninit(struct net_device *dev)
{
struct l2tp_eth *priv = netdev_priv(dev);
struct l2tp_eth_sess *spriv;
spriv = l2tp_session_priv(priv->session);
RCU_INIT_POINTER(spriv->dev, NULL);
/* No need for synchronize_net() here. We're called by
* unregister_netdev*(), which does the synchronisation for us.
*/
}
static netdev_tx_t l2tp_eth_dev_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct l2tp_eth *priv = netdev_priv(dev);
struct l2tp_session *session = priv->session;
unsigned int len = skb->len;
int ret = l2tp_xmit_skb(session, skb);
if (likely(ret == NET_XMIT_SUCCESS)) {
atomic_long_add(len, &priv->tx_bytes);
atomic_long_inc(&priv->tx_packets);
} else {
atomic_long_inc(&priv->tx_dropped);
}
return NETDEV_TX_OK;
}
static void l2tp_eth_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *stats)
{
struct l2tp_eth *priv = netdev_priv(dev);
stats->tx_bytes = (unsigned long)atomic_long_read(&priv->tx_bytes);
stats->tx_packets = (unsigned long)atomic_long_read(&priv->tx_packets);
stats->tx_dropped = (unsigned long)atomic_long_read(&priv->tx_dropped);
stats->rx_bytes = (unsigned long)atomic_long_read(&priv->rx_bytes);
stats->rx_packets = (unsigned long)atomic_long_read(&priv->rx_packets);
stats->rx_errors = (unsigned long)atomic_long_read(&priv->rx_errors);
}
static const struct net_device_ops l2tp_eth_netdev_ops = {
.ndo_init = l2tp_eth_dev_init,
.ndo_uninit = l2tp_eth_dev_uninit,
.ndo_start_xmit = l2tp_eth_dev_xmit,
.ndo_get_stats64 = l2tp_eth_get_stats64,
.ndo_set_mac_address = eth_mac_addr,
};
static struct device_type l2tpeth_type = {
.name = "l2tpeth",
};
static void l2tp_eth_dev_setup(struct net_device *dev)
{
SET_NETDEV_DEVTYPE(dev, &l2tpeth_type);
ether_setup(dev);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->features |= NETIF_F_LLTX;
dev->netdev_ops = &l2tp_eth_netdev_ops;
dev->needs_free_netdev = true;
}
static void l2tp_eth_dev_recv(struct l2tp_session *session, struct sk_buff *skb, int data_len)
{
struct l2tp_eth_sess *spriv = l2tp_session_priv(session);
struct net_device *dev;
struct l2tp_eth *priv;
if (!pskb_may_pull(skb, ETH_HLEN))
goto error;
secpath_reset(skb);
/* checksums verified by L2TP */
skb->ip_summed = CHECKSUM_NONE;
skb_dst_drop(skb);
nf_reset_ct(skb);
rcu_read_lock();
dev = rcu_dereference(spriv->dev);
if (!dev)
goto error_rcu;
priv = netdev_priv(dev);
if (dev_forward_skb(dev, skb) == NET_RX_SUCCESS) {
atomic_long_inc(&priv->rx_packets);
atomic_long_add(data_len, &priv->rx_bytes);
} else {
atomic_long_inc(&priv->rx_errors);
}
rcu_read_unlock();
return;
error_rcu:
rcu_read_unlock();
error:
kfree_skb(skb);
}
static void l2tp_eth_delete(struct l2tp_session *session)
{
struct l2tp_eth_sess *spriv;
struct net_device *dev;
if (session) {
spriv = l2tp_session_priv(session);
rtnl_lock();
dev = rtnl_dereference(spriv->dev);
if (dev) {
unregister_netdevice(dev);
rtnl_unlock();
module_put(THIS_MODULE);
} else {
rtnl_unlock();
}
}
}
static void l2tp_eth_show(struct seq_file *m, void *arg)
{
struct l2tp_session *session = arg;
struct l2tp_eth_sess *spriv = l2tp_session_priv(session);
struct net_device *dev;
rcu_read_lock();
dev = rcu_dereference(spriv->dev);
if (!dev) {
rcu_read_unlock();
return;
}
dev_hold(dev);
rcu_read_unlock();
seq_printf(m, " interface %s\n", dev->name);
dev_put(dev);
}
static void l2tp_eth_adjust_mtu(struct l2tp_tunnel *tunnel,
struct l2tp_session *session,
struct net_device *dev)
{
unsigned int overhead = 0;
u32 l3_overhead = 0;
u32 mtu;
/* if the encap is UDP, account for UDP header size */
if (tunnel->encap == L2TP_ENCAPTYPE_UDP) {
overhead += sizeof(struct udphdr);
dev->needed_headroom += sizeof(struct udphdr);
}
lock_sock(tunnel->sock);
l3_overhead = kernel_sock_ip_overhead(tunnel->sock);
release_sock(tunnel->sock);
if (l3_overhead == 0) {
/* L3 Overhead couldn't be identified, this could be
* because tunnel->sock was NULL or the socket's
* address family was not IPv4 or IPv6,
* dev mtu stays at 1500.
*/
return;
}
/* Adjust MTU, factor overhead - underlay L3, overlay L2 hdr
* UDP overhead, if any, was already factored in above.
*/
overhead += session->hdr_len + ETH_HLEN + l3_overhead;
mtu = l2tp_tunnel_dst_mtu(tunnel) - overhead;
if (mtu < dev->min_mtu || mtu > dev->max_mtu)
dev->mtu = ETH_DATA_LEN - overhead;
else
dev->mtu = mtu;
dev->needed_headroom += session->hdr_len;
}
static int l2tp_eth_create(struct net *net, struct l2tp_tunnel *tunnel,
u32 session_id, u32 peer_session_id,
struct l2tp_session_cfg *cfg)
{
unsigned char name_assign_type;
struct net_device *dev;
char name[IFNAMSIZ];
struct l2tp_session *session;
struct l2tp_eth *priv;
struct l2tp_eth_sess *spriv;
int rc;
if (cfg->ifname) {
strscpy(name, cfg->ifname, IFNAMSIZ);
name_assign_type = NET_NAME_USER;
} else {
strcpy(name, L2TP_ETH_DEV_NAME);
name_assign_type = NET_NAME_ENUM;
}
session = l2tp_session_create(sizeof(*spriv), tunnel, session_id,
peer_session_id, cfg);
if (IS_ERR(session)) {
rc = PTR_ERR(session);
goto err;
}
dev = alloc_netdev(sizeof(*priv), name, name_assign_type,
l2tp_eth_dev_setup);
if (!dev) {
rc = -ENOMEM;
goto err_sess;
}
dev_net_set(dev, net);
dev->min_mtu = 0;
dev->max_mtu = ETH_MAX_MTU;
l2tp_eth_adjust_mtu(tunnel, session, dev);
priv = netdev_priv(dev);
priv->session = session;
session->recv_skb = l2tp_eth_dev_recv;
session->session_close = l2tp_eth_delete;
if (IS_ENABLED(CONFIG_L2TP_DEBUGFS))
session->show = l2tp_eth_show;
spriv = l2tp_session_priv(session);
l2tp_session_inc_refcount(session);
rtnl_lock();
/* Register both device and session while holding the rtnl lock. This
* ensures that l2tp_eth_delete() will see that there's a device to
* unregister, even if it happened to run before we assign spriv->dev.
*/
rc = l2tp_session_register(session, tunnel);
if (rc < 0) {
rtnl_unlock();
goto err_sess_dev;
}
rc = register_netdevice(dev);
if (rc < 0) {
rtnl_unlock();
l2tp_session_delete(session);
l2tp_session_dec_refcount(session);
free_netdev(dev);
return rc;
}
strscpy(session->ifname, dev->name, IFNAMSIZ);
rcu_assign_pointer(spriv->dev, dev);
rtnl_unlock();
l2tp_session_dec_refcount(session);
__module_get(THIS_MODULE);
return 0;
err_sess_dev:
l2tp_session_dec_refcount(session);
free_netdev(dev);
err_sess:
kfree(session);
err:
return rc;
}
static const struct l2tp_nl_cmd_ops l2tp_eth_nl_cmd_ops = {
.session_create = l2tp_eth_create,
.session_delete = l2tp_session_delete,
};
static int __init l2tp_eth_init(void)
{
int err = 0;
err = l2tp_nl_register_ops(L2TP_PWTYPE_ETH, &l2tp_eth_nl_cmd_ops);
if (err)
goto err;
pr_info("L2TP ethernet pseudowire support (L2TPv3)\n");
return 0;
err:
return err;
}
static void __exit l2tp_eth_exit(void)
{
l2tp_nl_unregister_ops(L2TP_PWTYPE_ETH);
}
module_init(l2tp_eth_init);
module_exit(l2tp_eth_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("James Chapman <[email protected]>");
MODULE_DESCRIPTION("L2TP ethernet pseudowire driver");
MODULE_VERSION("1.0");
MODULE_ALIAS_L2TP_PWTYPE(5);
| linux-master | net/l2tp/l2tp_eth.c |
// SPDX-License-Identifier: GPL-2.0-only
/* L2TP netlink layer, for management
*
* Copyright (c) 2008,2009,2010 Katalix Systems Ltd
*
* Partly based on the IrDA nelink implementation
* (see net/irda/irnetlink.c) which is:
* Copyright (c) 2007 Samuel Ortiz <[email protected]>
* which is in turn partly based on the wireless netlink code:
* Copyright 2006 Johannes Berg <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <net/sock.h>
#include <net/genetlink.h>
#include <net/udp.h>
#include <linux/in.h>
#include <linux/udp.h>
#include <linux/socket.h>
#include <linux/module.h>
#include <linux/list.h>
#include <net/net_namespace.h>
#include <linux/l2tp.h>
#include "l2tp_core.h"
static struct genl_family l2tp_nl_family;
static const struct genl_multicast_group l2tp_multicast_group[] = {
{
.name = L2TP_GENL_MCGROUP,
},
};
static int l2tp_nl_tunnel_send(struct sk_buff *skb, u32 portid, u32 seq,
int flags, struct l2tp_tunnel *tunnel, u8 cmd);
static int l2tp_nl_session_send(struct sk_buff *skb, u32 portid, u32 seq,
int flags, struct l2tp_session *session,
u8 cmd);
/* Accessed under genl lock */
static const struct l2tp_nl_cmd_ops *l2tp_nl_cmd_ops[__L2TP_PWTYPE_MAX];
static struct l2tp_session *l2tp_nl_session_get(struct genl_info *info)
{
u32 tunnel_id;
u32 session_id;
char *ifname;
struct l2tp_tunnel *tunnel;
struct l2tp_session *session = NULL;
struct net *net = genl_info_net(info);
if (info->attrs[L2TP_ATTR_IFNAME]) {
ifname = nla_data(info->attrs[L2TP_ATTR_IFNAME]);
session = l2tp_session_get_by_ifname(net, ifname);
} else if ((info->attrs[L2TP_ATTR_SESSION_ID]) &&
(info->attrs[L2TP_ATTR_CONN_ID])) {
tunnel_id = nla_get_u32(info->attrs[L2TP_ATTR_CONN_ID]);
session_id = nla_get_u32(info->attrs[L2TP_ATTR_SESSION_ID]);
tunnel = l2tp_tunnel_get(net, tunnel_id);
if (tunnel) {
session = l2tp_tunnel_get_session(tunnel, session_id);
l2tp_tunnel_dec_refcount(tunnel);
}
}
return session;
}
static int l2tp_nl_cmd_noop(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
void *hdr;
int ret = -ENOBUFS;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg) {
ret = -ENOMEM;
goto out;
}
hdr = genlmsg_put(msg, info->snd_portid, info->snd_seq,
&l2tp_nl_family, 0, L2TP_CMD_NOOP);
if (!hdr) {
ret = -EMSGSIZE;
goto err_out;
}
genlmsg_end(msg, hdr);
return genlmsg_unicast(genl_info_net(info), msg, info->snd_portid);
err_out:
nlmsg_free(msg);
out:
return ret;
}
static int l2tp_tunnel_notify(struct genl_family *family,
struct genl_info *info,
struct l2tp_tunnel *tunnel,
u8 cmd)
{
struct sk_buff *msg;
int ret;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
ret = l2tp_nl_tunnel_send(msg, info->snd_portid, info->snd_seq,
NLM_F_ACK, tunnel, cmd);
if (ret >= 0) {
ret = genlmsg_multicast_allns(family, msg, 0, 0, GFP_ATOMIC);
/* We don't care if no one is listening */
if (ret == -ESRCH)
ret = 0;
return ret;
}
nlmsg_free(msg);
return ret;
}
static int l2tp_session_notify(struct genl_family *family,
struct genl_info *info,
struct l2tp_session *session,
u8 cmd)
{
struct sk_buff *msg;
int ret;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
ret = l2tp_nl_session_send(msg, info->snd_portid, info->snd_seq,
NLM_F_ACK, session, cmd);
if (ret >= 0) {
ret = genlmsg_multicast_allns(family, msg, 0, 0, GFP_ATOMIC);
/* We don't care if no one is listening */
if (ret == -ESRCH)
ret = 0;
return ret;
}
nlmsg_free(msg);
return ret;
}
static int l2tp_nl_cmd_tunnel_create_get_addr(struct nlattr **attrs, struct l2tp_tunnel_cfg *cfg)
{
if (attrs[L2TP_ATTR_UDP_SPORT])
cfg->local_udp_port = nla_get_u16(attrs[L2TP_ATTR_UDP_SPORT]);
if (attrs[L2TP_ATTR_UDP_DPORT])
cfg->peer_udp_port = nla_get_u16(attrs[L2TP_ATTR_UDP_DPORT]);
cfg->use_udp_checksums = nla_get_flag(attrs[L2TP_ATTR_UDP_CSUM]);
/* Must have either AF_INET or AF_INET6 address for source and destination */
#if IS_ENABLED(CONFIG_IPV6)
if (attrs[L2TP_ATTR_IP6_SADDR] && attrs[L2TP_ATTR_IP6_DADDR]) {
cfg->local_ip6 = nla_data(attrs[L2TP_ATTR_IP6_SADDR]);
cfg->peer_ip6 = nla_data(attrs[L2TP_ATTR_IP6_DADDR]);
cfg->udp6_zero_tx_checksums = nla_get_flag(attrs[L2TP_ATTR_UDP_ZERO_CSUM6_TX]);
cfg->udp6_zero_rx_checksums = nla_get_flag(attrs[L2TP_ATTR_UDP_ZERO_CSUM6_RX]);
return 0;
}
#endif
if (attrs[L2TP_ATTR_IP_SADDR] && attrs[L2TP_ATTR_IP_DADDR]) {
cfg->local_ip.s_addr = nla_get_in_addr(attrs[L2TP_ATTR_IP_SADDR]);
cfg->peer_ip.s_addr = nla_get_in_addr(attrs[L2TP_ATTR_IP_DADDR]);
return 0;
}
return -EINVAL;
}
static int l2tp_nl_cmd_tunnel_create(struct sk_buff *skb, struct genl_info *info)
{
u32 tunnel_id;
u32 peer_tunnel_id;
int proto_version;
int fd = -1;
int ret = 0;
struct l2tp_tunnel_cfg cfg = { 0, };
struct l2tp_tunnel *tunnel;
struct net *net = genl_info_net(info);
struct nlattr **attrs = info->attrs;
if (!attrs[L2TP_ATTR_CONN_ID]) {
ret = -EINVAL;
goto out;
}
tunnel_id = nla_get_u32(attrs[L2TP_ATTR_CONN_ID]);
if (!attrs[L2TP_ATTR_PEER_CONN_ID]) {
ret = -EINVAL;
goto out;
}
peer_tunnel_id = nla_get_u32(attrs[L2TP_ATTR_PEER_CONN_ID]);
if (!attrs[L2TP_ATTR_PROTO_VERSION]) {
ret = -EINVAL;
goto out;
}
proto_version = nla_get_u8(attrs[L2TP_ATTR_PROTO_VERSION]);
if (!attrs[L2TP_ATTR_ENCAP_TYPE]) {
ret = -EINVAL;
goto out;
}
cfg.encap = nla_get_u16(attrs[L2TP_ATTR_ENCAP_TYPE]);
/* Managed tunnels take the tunnel socket from userspace.
* Unmanaged tunnels must call out the source and destination addresses
* for the kernel to create the tunnel socket itself.
*/
if (attrs[L2TP_ATTR_FD]) {
fd = nla_get_u32(attrs[L2TP_ATTR_FD]);
} else {
ret = l2tp_nl_cmd_tunnel_create_get_addr(attrs, &cfg);
if (ret < 0)
goto out;
}
ret = -EINVAL;
switch (cfg.encap) {
case L2TP_ENCAPTYPE_UDP:
case L2TP_ENCAPTYPE_IP:
ret = l2tp_tunnel_create(fd, proto_version, tunnel_id,
peer_tunnel_id, &cfg, &tunnel);
break;
}
if (ret < 0)
goto out;
l2tp_tunnel_inc_refcount(tunnel);
ret = l2tp_tunnel_register(tunnel, net, &cfg);
if (ret < 0) {
kfree(tunnel);
goto out;
}
ret = l2tp_tunnel_notify(&l2tp_nl_family, info, tunnel,
L2TP_CMD_TUNNEL_CREATE);
l2tp_tunnel_dec_refcount(tunnel);
out:
return ret;
}
static int l2tp_nl_cmd_tunnel_delete(struct sk_buff *skb, struct genl_info *info)
{
struct l2tp_tunnel *tunnel;
u32 tunnel_id;
int ret = 0;
struct net *net = genl_info_net(info);
if (!info->attrs[L2TP_ATTR_CONN_ID]) {
ret = -EINVAL;
goto out;
}
tunnel_id = nla_get_u32(info->attrs[L2TP_ATTR_CONN_ID]);
tunnel = l2tp_tunnel_get(net, tunnel_id);
if (!tunnel) {
ret = -ENODEV;
goto out;
}
l2tp_tunnel_notify(&l2tp_nl_family, info,
tunnel, L2TP_CMD_TUNNEL_DELETE);
l2tp_tunnel_delete(tunnel);
l2tp_tunnel_dec_refcount(tunnel);
out:
return ret;
}
static int l2tp_nl_cmd_tunnel_modify(struct sk_buff *skb, struct genl_info *info)
{
struct l2tp_tunnel *tunnel;
u32 tunnel_id;
int ret = 0;
struct net *net = genl_info_net(info);
if (!info->attrs[L2TP_ATTR_CONN_ID]) {
ret = -EINVAL;
goto out;
}
tunnel_id = nla_get_u32(info->attrs[L2TP_ATTR_CONN_ID]);
tunnel = l2tp_tunnel_get(net, tunnel_id);
if (!tunnel) {
ret = -ENODEV;
goto out;
}
ret = l2tp_tunnel_notify(&l2tp_nl_family, info,
tunnel, L2TP_CMD_TUNNEL_MODIFY);
l2tp_tunnel_dec_refcount(tunnel);
out:
return ret;
}
#if IS_ENABLED(CONFIG_IPV6)
static int l2tp_nl_tunnel_send_addr6(struct sk_buff *skb, struct sock *sk,
enum l2tp_encap_type encap)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
switch (encap) {
case L2TP_ENCAPTYPE_UDP:
if (udp_get_no_check6_tx(sk) &&
nla_put_flag(skb, L2TP_ATTR_UDP_ZERO_CSUM6_TX))
return -1;
if (udp_get_no_check6_rx(sk) &&
nla_put_flag(skb, L2TP_ATTR_UDP_ZERO_CSUM6_RX))
return -1;
if (nla_put_u16(skb, L2TP_ATTR_UDP_SPORT, ntohs(inet->inet_sport)) ||
nla_put_u16(skb, L2TP_ATTR_UDP_DPORT, ntohs(inet->inet_dport)))
return -1;
fallthrough;
case L2TP_ENCAPTYPE_IP:
if (nla_put_in6_addr(skb, L2TP_ATTR_IP6_SADDR, &np->saddr) ||
nla_put_in6_addr(skb, L2TP_ATTR_IP6_DADDR, &sk->sk_v6_daddr))
return -1;
break;
}
return 0;
}
#endif
static int l2tp_nl_tunnel_send_addr4(struct sk_buff *skb, struct sock *sk,
enum l2tp_encap_type encap)
{
struct inet_sock *inet = inet_sk(sk);
switch (encap) {
case L2TP_ENCAPTYPE_UDP:
if (nla_put_u8(skb, L2TP_ATTR_UDP_CSUM, !sk->sk_no_check_tx) ||
nla_put_u16(skb, L2TP_ATTR_UDP_SPORT, ntohs(inet->inet_sport)) ||
nla_put_u16(skb, L2TP_ATTR_UDP_DPORT, ntohs(inet->inet_dport)))
return -1;
fallthrough;
case L2TP_ENCAPTYPE_IP:
if (nla_put_in_addr(skb, L2TP_ATTR_IP_SADDR, inet->inet_saddr) ||
nla_put_in_addr(skb, L2TP_ATTR_IP_DADDR, inet->inet_daddr))
return -1;
break;
}
return 0;
}
/* Append attributes for the tunnel address, handling the different attribute types
* used for different tunnel encapsulation and AF_INET v.s. AF_INET6.
*/
static int l2tp_nl_tunnel_send_addr(struct sk_buff *skb, struct l2tp_tunnel *tunnel)
{
struct sock *sk = tunnel->sock;
if (!sk)
return 0;
#if IS_ENABLED(CONFIG_IPV6)
if (sk->sk_family == AF_INET6)
return l2tp_nl_tunnel_send_addr6(skb, sk, tunnel->encap);
#endif
return l2tp_nl_tunnel_send_addr4(skb, sk, tunnel->encap);
}
static int l2tp_nl_tunnel_send(struct sk_buff *skb, u32 portid, u32 seq, int flags,
struct l2tp_tunnel *tunnel, u8 cmd)
{
void *hdr;
struct nlattr *nest;
hdr = genlmsg_put(skb, portid, seq, &l2tp_nl_family, flags, cmd);
if (!hdr)
return -EMSGSIZE;
if (nla_put_u8(skb, L2TP_ATTR_PROTO_VERSION, tunnel->version) ||
nla_put_u32(skb, L2TP_ATTR_CONN_ID, tunnel->tunnel_id) ||
nla_put_u32(skb, L2TP_ATTR_PEER_CONN_ID, tunnel->peer_tunnel_id) ||
nla_put_u32(skb, L2TP_ATTR_DEBUG, 0) ||
nla_put_u16(skb, L2TP_ATTR_ENCAP_TYPE, tunnel->encap))
goto nla_put_failure;
nest = nla_nest_start_noflag(skb, L2TP_ATTR_STATS);
if (!nest)
goto nla_put_failure;
if (nla_put_u64_64bit(skb, L2TP_ATTR_TX_PACKETS,
atomic_long_read(&tunnel->stats.tx_packets),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_TX_BYTES,
atomic_long_read(&tunnel->stats.tx_bytes),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_TX_ERRORS,
atomic_long_read(&tunnel->stats.tx_errors),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_PACKETS,
atomic_long_read(&tunnel->stats.rx_packets),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_BYTES,
atomic_long_read(&tunnel->stats.rx_bytes),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_SEQ_DISCARDS,
atomic_long_read(&tunnel->stats.rx_seq_discards),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_COOKIE_DISCARDS,
atomic_long_read(&tunnel->stats.rx_cookie_discards),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_OOS_PACKETS,
atomic_long_read(&tunnel->stats.rx_oos_packets),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_ERRORS,
atomic_long_read(&tunnel->stats.rx_errors),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_INVALID,
atomic_long_read(&tunnel->stats.rx_invalid),
L2TP_ATTR_STATS_PAD))
goto nla_put_failure;
nla_nest_end(skb, nest);
if (l2tp_nl_tunnel_send_addr(skb, tunnel))
goto nla_put_failure;
genlmsg_end(skb, hdr);
return 0;
nla_put_failure:
genlmsg_cancel(skb, hdr);
return -1;
}
static int l2tp_nl_cmd_tunnel_get(struct sk_buff *skb, struct genl_info *info)
{
struct l2tp_tunnel *tunnel;
struct sk_buff *msg;
u32 tunnel_id;
int ret = -ENOBUFS;
struct net *net = genl_info_net(info);
if (!info->attrs[L2TP_ATTR_CONN_ID]) {
ret = -EINVAL;
goto err;
}
tunnel_id = nla_get_u32(info->attrs[L2TP_ATTR_CONN_ID]);
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg) {
ret = -ENOMEM;
goto err;
}
tunnel = l2tp_tunnel_get(net, tunnel_id);
if (!tunnel) {
ret = -ENODEV;
goto err_nlmsg;
}
ret = l2tp_nl_tunnel_send(msg, info->snd_portid, info->snd_seq,
NLM_F_ACK, tunnel, L2TP_CMD_TUNNEL_GET);
if (ret < 0)
goto err_nlmsg_tunnel;
l2tp_tunnel_dec_refcount(tunnel);
return genlmsg_unicast(net, msg, info->snd_portid);
err_nlmsg_tunnel:
l2tp_tunnel_dec_refcount(tunnel);
err_nlmsg:
nlmsg_free(msg);
err:
return ret;
}
static int l2tp_nl_cmd_tunnel_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
int ti = cb->args[0];
struct l2tp_tunnel *tunnel;
struct net *net = sock_net(skb->sk);
for (;;) {
tunnel = l2tp_tunnel_get_nth(net, ti);
if (!tunnel)
goto out;
if (l2tp_nl_tunnel_send(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
tunnel, L2TP_CMD_TUNNEL_GET) < 0) {
l2tp_tunnel_dec_refcount(tunnel);
goto out;
}
l2tp_tunnel_dec_refcount(tunnel);
ti++;
}
out:
cb->args[0] = ti;
return skb->len;
}
static int l2tp_nl_cmd_session_create(struct sk_buff *skb, struct genl_info *info)
{
u32 tunnel_id = 0;
u32 session_id;
u32 peer_session_id;
int ret = 0;
struct l2tp_tunnel *tunnel;
struct l2tp_session *session;
struct l2tp_session_cfg cfg = { 0, };
struct net *net = genl_info_net(info);
if (!info->attrs[L2TP_ATTR_CONN_ID]) {
ret = -EINVAL;
goto out;
}
tunnel_id = nla_get_u32(info->attrs[L2TP_ATTR_CONN_ID]);
tunnel = l2tp_tunnel_get(net, tunnel_id);
if (!tunnel) {
ret = -ENODEV;
goto out;
}
if (!info->attrs[L2TP_ATTR_SESSION_ID]) {
ret = -EINVAL;
goto out_tunnel;
}
session_id = nla_get_u32(info->attrs[L2TP_ATTR_SESSION_ID]);
if (!info->attrs[L2TP_ATTR_PEER_SESSION_ID]) {
ret = -EINVAL;
goto out_tunnel;
}
peer_session_id = nla_get_u32(info->attrs[L2TP_ATTR_PEER_SESSION_ID]);
if (!info->attrs[L2TP_ATTR_PW_TYPE]) {
ret = -EINVAL;
goto out_tunnel;
}
cfg.pw_type = nla_get_u16(info->attrs[L2TP_ATTR_PW_TYPE]);
if (cfg.pw_type >= __L2TP_PWTYPE_MAX) {
ret = -EINVAL;
goto out_tunnel;
}
/* L2TPv2 only accepts PPP pseudo-wires */
if (tunnel->version == 2 && cfg.pw_type != L2TP_PWTYPE_PPP) {
ret = -EPROTONOSUPPORT;
goto out_tunnel;
}
if (tunnel->version > 2) {
if (info->attrs[L2TP_ATTR_L2SPEC_TYPE]) {
cfg.l2specific_type = nla_get_u8(info->attrs[L2TP_ATTR_L2SPEC_TYPE]);
if (cfg.l2specific_type != L2TP_L2SPECTYPE_DEFAULT &&
cfg.l2specific_type != L2TP_L2SPECTYPE_NONE) {
ret = -EINVAL;
goto out_tunnel;
}
} else {
cfg.l2specific_type = L2TP_L2SPECTYPE_DEFAULT;
}
if (info->attrs[L2TP_ATTR_COOKIE]) {
u16 len = nla_len(info->attrs[L2TP_ATTR_COOKIE]);
if (len > 8) {
ret = -EINVAL;
goto out_tunnel;
}
cfg.cookie_len = len;
memcpy(&cfg.cookie[0], nla_data(info->attrs[L2TP_ATTR_COOKIE]), len);
}
if (info->attrs[L2TP_ATTR_PEER_COOKIE]) {
u16 len = nla_len(info->attrs[L2TP_ATTR_PEER_COOKIE]);
if (len > 8) {
ret = -EINVAL;
goto out_tunnel;
}
cfg.peer_cookie_len = len;
memcpy(&cfg.peer_cookie[0], nla_data(info->attrs[L2TP_ATTR_PEER_COOKIE]), len);
}
if (info->attrs[L2TP_ATTR_IFNAME])
cfg.ifname = nla_data(info->attrs[L2TP_ATTR_IFNAME]);
}
if (info->attrs[L2TP_ATTR_RECV_SEQ])
cfg.recv_seq = nla_get_u8(info->attrs[L2TP_ATTR_RECV_SEQ]);
if (info->attrs[L2TP_ATTR_SEND_SEQ])
cfg.send_seq = nla_get_u8(info->attrs[L2TP_ATTR_SEND_SEQ]);
if (info->attrs[L2TP_ATTR_LNS_MODE])
cfg.lns_mode = nla_get_u8(info->attrs[L2TP_ATTR_LNS_MODE]);
if (info->attrs[L2TP_ATTR_RECV_TIMEOUT])
cfg.reorder_timeout = nla_get_msecs(info->attrs[L2TP_ATTR_RECV_TIMEOUT]);
#ifdef CONFIG_MODULES
if (!l2tp_nl_cmd_ops[cfg.pw_type]) {
genl_unlock();
request_module("net-l2tp-type-%u", cfg.pw_type);
genl_lock();
}
#endif
if (!l2tp_nl_cmd_ops[cfg.pw_type] || !l2tp_nl_cmd_ops[cfg.pw_type]->session_create) {
ret = -EPROTONOSUPPORT;
goto out_tunnel;
}
ret = l2tp_nl_cmd_ops[cfg.pw_type]->session_create(net, tunnel,
session_id,
peer_session_id,
&cfg);
if (ret >= 0) {
session = l2tp_tunnel_get_session(tunnel, session_id);
if (session) {
ret = l2tp_session_notify(&l2tp_nl_family, info, session,
L2TP_CMD_SESSION_CREATE);
l2tp_session_dec_refcount(session);
}
}
out_tunnel:
l2tp_tunnel_dec_refcount(tunnel);
out:
return ret;
}
static int l2tp_nl_cmd_session_delete(struct sk_buff *skb, struct genl_info *info)
{
int ret = 0;
struct l2tp_session *session;
u16 pw_type;
session = l2tp_nl_session_get(info);
if (!session) {
ret = -ENODEV;
goto out;
}
l2tp_session_notify(&l2tp_nl_family, info,
session, L2TP_CMD_SESSION_DELETE);
pw_type = session->pwtype;
if (pw_type < __L2TP_PWTYPE_MAX)
if (l2tp_nl_cmd_ops[pw_type] && l2tp_nl_cmd_ops[pw_type]->session_delete)
l2tp_nl_cmd_ops[pw_type]->session_delete(session);
l2tp_session_dec_refcount(session);
out:
return ret;
}
static int l2tp_nl_cmd_session_modify(struct sk_buff *skb, struct genl_info *info)
{
int ret = 0;
struct l2tp_session *session;
session = l2tp_nl_session_get(info);
if (!session) {
ret = -ENODEV;
goto out;
}
if (info->attrs[L2TP_ATTR_RECV_SEQ])
session->recv_seq = nla_get_u8(info->attrs[L2TP_ATTR_RECV_SEQ]);
if (info->attrs[L2TP_ATTR_SEND_SEQ]) {
session->send_seq = nla_get_u8(info->attrs[L2TP_ATTR_SEND_SEQ]);
l2tp_session_set_header_len(session, session->tunnel->version);
}
if (info->attrs[L2TP_ATTR_LNS_MODE])
session->lns_mode = nla_get_u8(info->attrs[L2TP_ATTR_LNS_MODE]);
if (info->attrs[L2TP_ATTR_RECV_TIMEOUT])
session->reorder_timeout = nla_get_msecs(info->attrs[L2TP_ATTR_RECV_TIMEOUT]);
ret = l2tp_session_notify(&l2tp_nl_family, info,
session, L2TP_CMD_SESSION_MODIFY);
l2tp_session_dec_refcount(session);
out:
return ret;
}
static int l2tp_nl_session_send(struct sk_buff *skb, u32 portid, u32 seq, int flags,
struct l2tp_session *session, u8 cmd)
{
void *hdr;
struct nlattr *nest;
struct l2tp_tunnel *tunnel = session->tunnel;
hdr = genlmsg_put(skb, portid, seq, &l2tp_nl_family, flags, cmd);
if (!hdr)
return -EMSGSIZE;
if (nla_put_u32(skb, L2TP_ATTR_CONN_ID, tunnel->tunnel_id) ||
nla_put_u32(skb, L2TP_ATTR_SESSION_ID, session->session_id) ||
nla_put_u32(skb, L2TP_ATTR_PEER_CONN_ID, tunnel->peer_tunnel_id) ||
nla_put_u32(skb, L2TP_ATTR_PEER_SESSION_ID, session->peer_session_id) ||
nla_put_u32(skb, L2TP_ATTR_DEBUG, 0) ||
nla_put_u16(skb, L2TP_ATTR_PW_TYPE, session->pwtype))
goto nla_put_failure;
if ((session->ifname[0] &&
nla_put_string(skb, L2TP_ATTR_IFNAME, session->ifname)) ||
(session->cookie_len &&
nla_put(skb, L2TP_ATTR_COOKIE, session->cookie_len, session->cookie)) ||
(session->peer_cookie_len &&
nla_put(skb, L2TP_ATTR_PEER_COOKIE, session->peer_cookie_len, session->peer_cookie)) ||
nla_put_u8(skb, L2TP_ATTR_RECV_SEQ, session->recv_seq) ||
nla_put_u8(skb, L2TP_ATTR_SEND_SEQ, session->send_seq) ||
nla_put_u8(skb, L2TP_ATTR_LNS_MODE, session->lns_mode) ||
(l2tp_tunnel_uses_xfrm(tunnel) &&
nla_put_u8(skb, L2TP_ATTR_USING_IPSEC, 1)) ||
(session->reorder_timeout &&
nla_put_msecs(skb, L2TP_ATTR_RECV_TIMEOUT,
session->reorder_timeout, L2TP_ATTR_PAD)))
goto nla_put_failure;
nest = nla_nest_start_noflag(skb, L2TP_ATTR_STATS);
if (!nest)
goto nla_put_failure;
if (nla_put_u64_64bit(skb, L2TP_ATTR_TX_PACKETS,
atomic_long_read(&session->stats.tx_packets),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_TX_BYTES,
atomic_long_read(&session->stats.tx_bytes),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_TX_ERRORS,
atomic_long_read(&session->stats.tx_errors),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_PACKETS,
atomic_long_read(&session->stats.rx_packets),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_BYTES,
atomic_long_read(&session->stats.rx_bytes),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_SEQ_DISCARDS,
atomic_long_read(&session->stats.rx_seq_discards),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_COOKIE_DISCARDS,
atomic_long_read(&session->stats.rx_cookie_discards),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_OOS_PACKETS,
atomic_long_read(&session->stats.rx_oos_packets),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_ERRORS,
atomic_long_read(&session->stats.rx_errors),
L2TP_ATTR_STATS_PAD) ||
nla_put_u64_64bit(skb, L2TP_ATTR_RX_INVALID,
atomic_long_read(&session->stats.rx_invalid),
L2TP_ATTR_STATS_PAD))
goto nla_put_failure;
nla_nest_end(skb, nest);
genlmsg_end(skb, hdr);
return 0;
nla_put_failure:
genlmsg_cancel(skb, hdr);
return -1;
}
static int l2tp_nl_cmd_session_get(struct sk_buff *skb, struct genl_info *info)
{
struct l2tp_session *session;
struct sk_buff *msg;
int ret;
session = l2tp_nl_session_get(info);
if (!session) {
ret = -ENODEV;
goto err;
}
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg) {
ret = -ENOMEM;
goto err_ref;
}
ret = l2tp_nl_session_send(msg, info->snd_portid, info->snd_seq,
0, session, L2TP_CMD_SESSION_GET);
if (ret < 0)
goto err_ref_msg;
ret = genlmsg_unicast(genl_info_net(info), msg, info->snd_portid);
l2tp_session_dec_refcount(session);
return ret;
err_ref_msg:
nlmsg_free(msg);
err_ref:
l2tp_session_dec_refcount(session);
err:
return ret;
}
static int l2tp_nl_cmd_session_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct l2tp_session *session;
struct l2tp_tunnel *tunnel = NULL;
int ti = cb->args[0];
int si = cb->args[1];
for (;;) {
if (!tunnel) {
tunnel = l2tp_tunnel_get_nth(net, ti);
if (!tunnel)
goto out;
}
session = l2tp_session_get_nth(tunnel, si);
if (!session) {
ti++;
l2tp_tunnel_dec_refcount(tunnel);
tunnel = NULL;
si = 0;
continue;
}
if (l2tp_nl_session_send(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
session, L2TP_CMD_SESSION_GET) < 0) {
l2tp_session_dec_refcount(session);
l2tp_tunnel_dec_refcount(tunnel);
break;
}
l2tp_session_dec_refcount(session);
si++;
}
out:
cb->args[0] = ti;
cb->args[1] = si;
return skb->len;
}
static const struct nla_policy l2tp_nl_policy[L2TP_ATTR_MAX + 1] = {
[L2TP_ATTR_NONE] = { .type = NLA_UNSPEC, },
[L2TP_ATTR_PW_TYPE] = { .type = NLA_U16, },
[L2TP_ATTR_ENCAP_TYPE] = { .type = NLA_U16, },
[L2TP_ATTR_OFFSET] = { .type = NLA_U16, },
[L2TP_ATTR_DATA_SEQ] = { .type = NLA_U8, },
[L2TP_ATTR_L2SPEC_TYPE] = { .type = NLA_U8, },
[L2TP_ATTR_L2SPEC_LEN] = { .type = NLA_U8, },
[L2TP_ATTR_PROTO_VERSION] = { .type = NLA_U8, },
[L2TP_ATTR_CONN_ID] = { .type = NLA_U32, },
[L2TP_ATTR_PEER_CONN_ID] = { .type = NLA_U32, },
[L2TP_ATTR_SESSION_ID] = { .type = NLA_U32, },
[L2TP_ATTR_PEER_SESSION_ID] = { .type = NLA_U32, },
[L2TP_ATTR_UDP_CSUM] = { .type = NLA_U8, },
[L2TP_ATTR_VLAN_ID] = { .type = NLA_U16, },
[L2TP_ATTR_DEBUG] = { .type = NLA_U32, },
[L2TP_ATTR_RECV_SEQ] = { .type = NLA_U8, },
[L2TP_ATTR_SEND_SEQ] = { .type = NLA_U8, },
[L2TP_ATTR_LNS_MODE] = { .type = NLA_U8, },
[L2TP_ATTR_USING_IPSEC] = { .type = NLA_U8, },
[L2TP_ATTR_RECV_TIMEOUT] = { .type = NLA_MSECS, },
[L2TP_ATTR_FD] = { .type = NLA_U32, },
[L2TP_ATTR_IP_SADDR] = { .type = NLA_U32, },
[L2TP_ATTR_IP_DADDR] = { .type = NLA_U32, },
[L2TP_ATTR_UDP_SPORT] = { .type = NLA_U16, },
[L2TP_ATTR_UDP_DPORT] = { .type = NLA_U16, },
[L2TP_ATTR_MTU] = { .type = NLA_U16, },
[L2TP_ATTR_MRU] = { .type = NLA_U16, },
[L2TP_ATTR_STATS] = { .type = NLA_NESTED, },
[L2TP_ATTR_IP6_SADDR] = {
.type = NLA_BINARY,
.len = sizeof(struct in6_addr),
},
[L2TP_ATTR_IP6_DADDR] = {
.type = NLA_BINARY,
.len = sizeof(struct in6_addr),
},
[L2TP_ATTR_IFNAME] = {
.type = NLA_NUL_STRING,
.len = IFNAMSIZ - 1,
},
[L2TP_ATTR_COOKIE] = {
.type = NLA_BINARY,
.len = 8,
},
[L2TP_ATTR_PEER_COOKIE] = {
.type = NLA_BINARY,
.len = 8,
},
};
static const struct genl_small_ops l2tp_nl_ops[] = {
{
.cmd = L2TP_CMD_NOOP,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = l2tp_nl_cmd_noop,
/* can be retrieved by unprivileged users */
},
{
.cmd = L2TP_CMD_TUNNEL_CREATE,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = l2tp_nl_cmd_tunnel_create,
.flags = GENL_UNS_ADMIN_PERM,
},
{
.cmd = L2TP_CMD_TUNNEL_DELETE,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = l2tp_nl_cmd_tunnel_delete,
.flags = GENL_UNS_ADMIN_PERM,
},
{
.cmd = L2TP_CMD_TUNNEL_MODIFY,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = l2tp_nl_cmd_tunnel_modify,
.flags = GENL_UNS_ADMIN_PERM,
},
{
.cmd = L2TP_CMD_TUNNEL_GET,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = l2tp_nl_cmd_tunnel_get,
.dumpit = l2tp_nl_cmd_tunnel_dump,
.flags = GENL_UNS_ADMIN_PERM,
},
{
.cmd = L2TP_CMD_SESSION_CREATE,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = l2tp_nl_cmd_session_create,
.flags = GENL_UNS_ADMIN_PERM,
},
{
.cmd = L2TP_CMD_SESSION_DELETE,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = l2tp_nl_cmd_session_delete,
.flags = GENL_UNS_ADMIN_PERM,
},
{
.cmd = L2TP_CMD_SESSION_MODIFY,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = l2tp_nl_cmd_session_modify,
.flags = GENL_UNS_ADMIN_PERM,
},
{
.cmd = L2TP_CMD_SESSION_GET,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = l2tp_nl_cmd_session_get,
.dumpit = l2tp_nl_cmd_session_dump,
.flags = GENL_UNS_ADMIN_PERM,
},
};
static struct genl_family l2tp_nl_family __ro_after_init = {
.name = L2TP_GENL_NAME,
.version = L2TP_GENL_VERSION,
.hdrsize = 0,
.maxattr = L2TP_ATTR_MAX,
.policy = l2tp_nl_policy,
.netnsok = true,
.module = THIS_MODULE,
.small_ops = l2tp_nl_ops,
.n_small_ops = ARRAY_SIZE(l2tp_nl_ops),
.resv_start_op = L2TP_CMD_SESSION_GET + 1,
.mcgrps = l2tp_multicast_group,
.n_mcgrps = ARRAY_SIZE(l2tp_multicast_group),
};
int l2tp_nl_register_ops(enum l2tp_pwtype pw_type, const struct l2tp_nl_cmd_ops *ops)
{
int ret;
ret = -EINVAL;
if (pw_type >= __L2TP_PWTYPE_MAX)
goto err;
genl_lock();
ret = -EBUSY;
if (l2tp_nl_cmd_ops[pw_type])
goto out;
l2tp_nl_cmd_ops[pw_type] = ops;
ret = 0;
out:
genl_unlock();
err:
return ret;
}
EXPORT_SYMBOL_GPL(l2tp_nl_register_ops);
void l2tp_nl_unregister_ops(enum l2tp_pwtype pw_type)
{
if (pw_type < __L2TP_PWTYPE_MAX) {
genl_lock();
l2tp_nl_cmd_ops[pw_type] = NULL;
genl_unlock();
}
}
EXPORT_SYMBOL_GPL(l2tp_nl_unregister_ops);
static int __init l2tp_nl_init(void)
{
pr_info("L2TP netlink interface\n");
return genl_register_family(&l2tp_nl_family);
}
static void l2tp_nl_cleanup(void)
{
genl_unregister_family(&l2tp_nl_family);
}
module_init(l2tp_nl_init);
module_exit(l2tp_nl_cleanup);
MODULE_AUTHOR("James Chapman <[email protected]>");
MODULE_DESCRIPTION("L2TP netlink");
MODULE_LICENSE("GPL");
MODULE_VERSION("1.0");
MODULE_ALIAS_GENL_FAMILY("l2tp");
| linux-master | net/l2tp/l2tp_netlink.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This file is part of the SCTP kernel implementation
*
* This module provides the abstraction for an SCTP association.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Jon Grimm <[email protected]>
* Xingang Guo <[email protected]>
* Hui Huang <[email protected]>
* Sridhar Samudrala <[email protected]>
* Daisy Chang <[email protected]>
* Ryan Layer <[email protected]>
* Kevin Gao <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <net/ipv6.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
/* Forward declarations for internal functions. */
static void sctp_select_active_and_retran_path(struct sctp_association *asoc);
static void sctp_assoc_bh_rcv(struct work_struct *work);
static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc);
static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc);
/* 1st Level Abstractions. */
/* Initialize a new association from provided memory. */
static struct sctp_association *sctp_association_init(
struct sctp_association *asoc,
const struct sctp_endpoint *ep,
const struct sock *sk,
enum sctp_scope scope, gfp_t gfp)
{
struct sctp_sock *sp;
struct sctp_paramhdr *p;
int i;
/* Retrieve the SCTP per socket area. */
sp = sctp_sk((struct sock *)sk);
/* Discarding const is appropriate here. */
asoc->ep = (struct sctp_endpoint *)ep;
asoc->base.sk = (struct sock *)sk;
asoc->base.net = sock_net(sk);
sctp_endpoint_hold(asoc->ep);
sock_hold(asoc->base.sk);
/* Initialize the common base substructure. */
asoc->base.type = SCTP_EP_TYPE_ASSOCIATION;
/* Initialize the object handling fields. */
refcount_set(&asoc->base.refcnt, 1);
/* Initialize the bind addr area. */
sctp_bind_addr_init(&asoc->base.bind_addr, ep->base.bind_addr.port);
asoc->state = SCTP_STATE_CLOSED;
asoc->cookie_life = ms_to_ktime(sp->assocparams.sasoc_cookie_life);
asoc->user_frag = sp->user_frag;
/* Set the association max_retrans and RTO values from the
* socket values.
*/
asoc->max_retrans = sp->assocparams.sasoc_asocmaxrxt;
asoc->pf_retrans = sp->pf_retrans;
asoc->ps_retrans = sp->ps_retrans;
asoc->pf_expose = sp->pf_expose;
asoc->rto_initial = msecs_to_jiffies(sp->rtoinfo.srto_initial);
asoc->rto_max = msecs_to_jiffies(sp->rtoinfo.srto_max);
asoc->rto_min = msecs_to_jiffies(sp->rtoinfo.srto_min);
/* Initialize the association's heartbeat interval based on the
* sock configured value.
*/
asoc->hbinterval = msecs_to_jiffies(sp->hbinterval);
asoc->probe_interval = msecs_to_jiffies(sp->probe_interval);
asoc->encap_port = sp->encap_port;
/* Initialize path max retrans value. */
asoc->pathmaxrxt = sp->pathmaxrxt;
asoc->flowlabel = sp->flowlabel;
asoc->dscp = sp->dscp;
/* Set association default SACK delay */
asoc->sackdelay = msecs_to_jiffies(sp->sackdelay);
asoc->sackfreq = sp->sackfreq;
/* Set the association default flags controlling
* Heartbeat, SACK delay, and Path MTU Discovery.
*/
asoc->param_flags = sp->param_flags;
/* Initialize the maximum number of new data packets that can be sent
* in a burst.
*/
asoc->max_burst = sp->max_burst;
asoc->subscribe = sp->subscribe;
/* initialize association timers */
asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_COOKIE] = asoc->rto_initial;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_INIT] = asoc->rto_initial;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T2_SHUTDOWN] = asoc->rto_initial;
/* sctpimpguide Section 2.12.2
* If the 'T5-shutdown-guard' timer is used, it SHOULD be set to the
* recommended value of 5 times 'RTO.Max'.
*/
asoc->timeouts[SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD]
= 5 * asoc->rto_max;
asoc->timeouts[SCTP_EVENT_TIMEOUT_SACK] = asoc->sackdelay;
asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE] = sp->autoclose * HZ;
/* Initializes the timers */
for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i)
timer_setup(&asoc->timers[i], sctp_timer_events[i], 0);
/* Pull default initialization values from the sock options.
* Note: This assumes that the values have already been
* validated in the sock.
*/
asoc->c.sinit_max_instreams = sp->initmsg.sinit_max_instreams;
asoc->c.sinit_num_ostreams = sp->initmsg.sinit_num_ostreams;
asoc->max_init_attempts = sp->initmsg.sinit_max_attempts;
asoc->max_init_timeo =
msecs_to_jiffies(sp->initmsg.sinit_max_init_timeo);
/* Set the local window size for receive.
* This is also the rcvbuf space per association.
* RFC 6 - A SCTP receiver MUST be able to receive a minimum of
* 1500 bytes in one SCTP packet.
*/
if ((sk->sk_rcvbuf/2) < SCTP_DEFAULT_MINWINDOW)
asoc->rwnd = SCTP_DEFAULT_MINWINDOW;
else
asoc->rwnd = sk->sk_rcvbuf/2;
asoc->a_rwnd = asoc->rwnd;
/* Use my own max window until I learn something better. */
asoc->peer.rwnd = SCTP_DEFAULT_MAXWINDOW;
/* Initialize the receive memory counter */
atomic_set(&asoc->rmem_alloc, 0);
init_waitqueue_head(&asoc->wait);
asoc->c.my_vtag = sctp_generate_tag(ep);
asoc->c.my_port = ep->base.bind_addr.port;
asoc->c.initial_tsn = sctp_generate_tsn(ep);
asoc->next_tsn = asoc->c.initial_tsn;
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
asoc->highest_sacked = asoc->ctsn_ack_point;
asoc->last_cwr_tsn = asoc->ctsn_ack_point;
/* ADDIP Section 4.1 Asconf Chunk Procedures
*
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do the following:
* ...
* A2) a serial number should be assigned to the chunk. The serial
* number SHOULD be a monotonically increasing number. The serial
* numbers SHOULD be initialized at the start of the
* association to the same value as the initial TSN.
*/
asoc->addip_serial = asoc->c.initial_tsn;
asoc->strreset_outseq = asoc->c.initial_tsn;
INIT_LIST_HEAD(&asoc->addip_chunk_list);
INIT_LIST_HEAD(&asoc->asconf_ack_list);
/* Make an empty list of remote transport addresses. */
INIT_LIST_HEAD(&asoc->peer.transport_addr_list);
/* RFC 2960 5.1 Normal Establishment of an Association
*
* After the reception of the first data chunk in an
* association the endpoint must immediately respond with a
* sack to acknowledge the data chunk. Subsequent
* acknowledgements should be done as described in Section
* 6.2.
*
* [We implement this by telling a new association that it
* already received one packet.]
*/
asoc->peer.sack_needed = 1;
asoc->peer.sack_generation = 1;
/* Create an input queue. */
sctp_inq_init(&asoc->base.inqueue);
sctp_inq_set_th_handler(&asoc->base.inqueue, sctp_assoc_bh_rcv);
/* Create an output queue. */
sctp_outq_init(asoc, &asoc->outqueue);
sctp_ulpq_init(&asoc->ulpq, asoc);
if (sctp_stream_init(&asoc->stream, asoc->c.sinit_num_ostreams, 0, gfp))
goto stream_free;
/* Initialize default path MTU. */
asoc->pathmtu = sp->pathmtu;
sctp_assoc_update_frag_point(asoc);
/* Assume that peer would support both address types unless we are
* told otherwise.
*/
asoc->peer.ipv4_address = 1;
if (asoc->base.sk->sk_family == PF_INET6)
asoc->peer.ipv6_address = 1;
INIT_LIST_HEAD(&asoc->asocs);
asoc->default_stream = sp->default_stream;
asoc->default_ppid = sp->default_ppid;
asoc->default_flags = sp->default_flags;
asoc->default_context = sp->default_context;
asoc->default_timetolive = sp->default_timetolive;
asoc->default_rcv_context = sp->default_rcv_context;
/* AUTH related initializations */
INIT_LIST_HEAD(&asoc->endpoint_shared_keys);
if (sctp_auth_asoc_copy_shkeys(ep, asoc, gfp))
goto stream_free;
asoc->active_key_id = ep->active_key_id;
asoc->strreset_enable = ep->strreset_enable;
/* Save the hmacs and chunks list into this association */
if (ep->auth_hmacs_list)
memcpy(asoc->c.auth_hmacs, ep->auth_hmacs_list,
ntohs(ep->auth_hmacs_list->param_hdr.length));
if (ep->auth_chunk_list)
memcpy(asoc->c.auth_chunks, ep->auth_chunk_list,
ntohs(ep->auth_chunk_list->param_hdr.length));
/* Get the AUTH random number for this association */
p = (struct sctp_paramhdr *)asoc->c.auth_random;
p->type = SCTP_PARAM_RANDOM;
p->length = htons(sizeof(*p) + SCTP_AUTH_RANDOM_LENGTH);
get_random_bytes(p+1, SCTP_AUTH_RANDOM_LENGTH);
return asoc;
stream_free:
sctp_stream_free(&asoc->stream);
sock_put(asoc->base.sk);
sctp_endpoint_put(asoc->ep);
return NULL;
}
/* Allocate and initialize a new association */
struct sctp_association *sctp_association_new(const struct sctp_endpoint *ep,
const struct sock *sk,
enum sctp_scope scope, gfp_t gfp)
{
struct sctp_association *asoc;
asoc = kzalloc(sizeof(*asoc), gfp);
if (!asoc)
goto fail;
if (!sctp_association_init(asoc, ep, sk, scope, gfp))
goto fail_init;
SCTP_DBG_OBJCNT_INC(assoc);
pr_debug("Created asoc %p\n", asoc);
return asoc;
fail_init:
kfree(asoc);
fail:
return NULL;
}
/* Free this association if possible. There may still be users, so
* the actual deallocation may be delayed.
*/
void sctp_association_free(struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
struct sctp_transport *transport;
struct list_head *pos, *temp;
int i;
/* Only real associations count against the endpoint, so
* don't bother for if this is a temporary association.
*/
if (!list_empty(&asoc->asocs)) {
list_del(&asoc->asocs);
/* Decrement the backlog value for a TCP-style listening
* socket.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
sk_acceptq_removed(sk);
}
/* Mark as dead, so other users can know this structure is
* going away.
*/
asoc->base.dead = true;
/* Dispose of any data lying around in the outqueue. */
sctp_outq_free(&asoc->outqueue);
/* Dispose of any pending messages for the upper layer. */
sctp_ulpq_free(&asoc->ulpq);
/* Dispose of any pending chunks on the inqueue. */
sctp_inq_free(&asoc->base.inqueue);
sctp_tsnmap_free(&asoc->peer.tsn_map);
/* Free stream information. */
sctp_stream_free(&asoc->stream);
if (asoc->strreset_chunk)
sctp_chunk_free(asoc->strreset_chunk);
/* Clean up the bound address list. */
sctp_bind_addr_free(&asoc->base.bind_addr);
/* Do we need to go through all of our timers and
* delete them? To be safe we will try to delete all, but we
* should be able to go through and make a guess based
* on our state.
*/
for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) {
if (del_timer(&asoc->timers[i]))
sctp_association_put(asoc);
}
/* Free peer's cached cookie. */
kfree(asoc->peer.cookie);
kfree(asoc->peer.peer_random);
kfree(asoc->peer.peer_chunks);
kfree(asoc->peer.peer_hmacs);
/* Release the transport structures. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
list_del_rcu(pos);
sctp_unhash_transport(transport);
sctp_transport_free(transport);
}
asoc->peer.transport_count = 0;
sctp_asconf_queue_teardown(asoc);
/* Free pending address space being deleted */
kfree(asoc->asconf_addr_del_pending);
/* AUTH - Free the endpoint shared keys */
sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
/* AUTH - Free the association shared key */
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_association_put(asoc);
}
/* Cleanup and free up an association. */
static void sctp_association_destroy(struct sctp_association *asoc)
{
if (unlikely(!asoc->base.dead)) {
WARN(1, "Attempt to destroy undead association %p!\n", asoc);
return;
}
sctp_endpoint_put(asoc->ep);
sock_put(asoc->base.sk);
if (asoc->assoc_id != 0) {
spin_lock_bh(&sctp_assocs_id_lock);
idr_remove(&sctp_assocs_id, asoc->assoc_id);
spin_unlock_bh(&sctp_assocs_id_lock);
}
WARN_ON(atomic_read(&asoc->rmem_alloc));
kfree_rcu(asoc, rcu);
SCTP_DBG_OBJCNT_DEC(assoc);
}
/* Change the primary destination address for the peer. */
void sctp_assoc_set_primary(struct sctp_association *asoc,
struct sctp_transport *transport)
{
int changeover = 0;
/* it's a changeover only if we already have a primary path
* that we are changing
*/
if (asoc->peer.primary_path != NULL &&
asoc->peer.primary_path != transport)
changeover = 1 ;
asoc->peer.primary_path = transport;
sctp_ulpevent_notify_peer_addr_change(transport,
SCTP_ADDR_MADE_PRIM, 0);
/* Set a default msg_name for events. */
memcpy(&asoc->peer.primary_addr, &transport->ipaddr,
sizeof(union sctp_addr));
/* If the primary path is changing, assume that the
* user wants to use this new path.
*/
if ((transport->state == SCTP_ACTIVE) ||
(transport->state == SCTP_UNKNOWN))
asoc->peer.active_path = transport;
/*
* SFR-CACC algorithm:
* Upon the receipt of a request to change the primary
* destination address, on the data structure for the new
* primary destination, the sender MUST do the following:
*
* 1) If CHANGEOVER_ACTIVE is set, then there was a switch
* to this destination address earlier. The sender MUST set
* CYCLING_CHANGEOVER to indicate that this switch is a
* double switch to the same destination address.
*
* Really, only bother is we have data queued or outstanding on
* the association.
*/
if (!asoc->outqueue.outstanding_bytes && !asoc->outqueue.out_qlen)
return;
if (transport->cacc.changeover_active)
transport->cacc.cycling_changeover = changeover;
/* 2) The sender MUST set CHANGEOVER_ACTIVE to indicate that
* a changeover has occurred.
*/
transport->cacc.changeover_active = changeover;
/* 3) The sender MUST store the next TSN to be sent in
* next_tsn_at_change.
*/
transport->cacc.next_tsn_at_change = asoc->next_tsn;
}
/* Remove a transport from an association. */
void sctp_assoc_rm_peer(struct sctp_association *asoc,
struct sctp_transport *peer)
{
struct sctp_transport *transport;
struct list_head *pos;
struct sctp_chunk *ch;
pr_debug("%s: association:%p addr:%pISpc\n",
__func__, asoc, &peer->ipaddr.sa);
/* If we are to remove the current retran_path, update it
* to the next peer before removing this peer from the list.
*/
if (asoc->peer.retran_path == peer)
sctp_assoc_update_retran_path(asoc);
/* Remove this peer from the list. */
list_del_rcu(&peer->transports);
/* Remove this peer from the transport hashtable */
sctp_unhash_transport(peer);
/* Get the first transport of asoc. */
pos = asoc->peer.transport_addr_list.next;
transport = list_entry(pos, struct sctp_transport, transports);
/* Update any entries that match the peer to be deleted. */
if (asoc->peer.primary_path == peer)
sctp_assoc_set_primary(asoc, transport);
if (asoc->peer.active_path == peer)
asoc->peer.active_path = transport;
if (asoc->peer.retran_path == peer)
asoc->peer.retran_path = transport;
if (asoc->peer.last_data_from == peer)
asoc->peer.last_data_from = transport;
if (asoc->strreset_chunk &&
asoc->strreset_chunk->transport == peer) {
asoc->strreset_chunk->transport = transport;
sctp_transport_reset_reconf_timer(transport);
}
/* If we remove the transport an INIT was last sent to, set it to
* NULL. Combined with the update of the retran path above, this
* will cause the next INIT to be sent to the next available
* transport, maintaining the cycle.
*/
if (asoc->init_last_sent_to == peer)
asoc->init_last_sent_to = NULL;
/* If we remove the transport an SHUTDOWN was last sent to, set it
* to NULL. Combined with the update of the retran path above, this
* will cause the next SHUTDOWN to be sent to the next available
* transport, maintaining the cycle.
*/
if (asoc->shutdown_last_sent_to == peer)
asoc->shutdown_last_sent_to = NULL;
/* If we remove the transport an ASCONF was last sent to, set it to
* NULL.
*/
if (asoc->addip_last_asconf &&
asoc->addip_last_asconf->transport == peer)
asoc->addip_last_asconf->transport = NULL;
/* If we have something on the transmitted list, we have to
* save it off. The best place is the active path.
*/
if (!list_empty(&peer->transmitted)) {
struct sctp_transport *active = asoc->peer.active_path;
/* Reset the transport of each chunk on this list */
list_for_each_entry(ch, &peer->transmitted,
transmitted_list) {
ch->transport = NULL;
ch->rtt_in_progress = 0;
}
list_splice_tail_init(&peer->transmitted,
&active->transmitted);
/* Start a T3 timer here in case it wasn't running so
* that these migrated packets have a chance to get
* retransmitted.
*/
if (!timer_pending(&active->T3_rtx_timer))
if (!mod_timer(&active->T3_rtx_timer,
jiffies + active->rto))
sctp_transport_hold(active);
}
list_for_each_entry(ch, &asoc->outqueue.out_chunk_list, list)
if (ch->transport == peer)
ch->transport = NULL;
asoc->peer.transport_count--;
sctp_ulpevent_notify_peer_addr_change(peer, SCTP_ADDR_REMOVED, 0);
sctp_transport_free(peer);
}
/* Add a transport address to an association. */
struct sctp_transport *sctp_assoc_add_peer(struct sctp_association *asoc,
const union sctp_addr *addr,
const gfp_t gfp,
const int peer_state)
{
struct sctp_transport *peer;
struct sctp_sock *sp;
unsigned short port;
sp = sctp_sk(asoc->base.sk);
/* AF_INET and AF_INET6 share common port field. */
port = ntohs(addr->v4.sin_port);
pr_debug("%s: association:%p addr:%pISpc state:%d\n", __func__,
asoc, &addr->sa, peer_state);
/* Set the port if it has not been set yet. */
if (0 == asoc->peer.port)
asoc->peer.port = port;
/* Check to see if this is a duplicate. */
peer = sctp_assoc_lookup_paddr(asoc, addr);
if (peer) {
/* An UNKNOWN state is only set on transports added by
* user in sctp_connectx() call. Such transports should be
* considered CONFIRMED per RFC 4960, Section 5.4.
*/
if (peer->state == SCTP_UNKNOWN) {
peer->state = SCTP_ACTIVE;
}
return peer;
}
peer = sctp_transport_new(asoc->base.net, addr, gfp);
if (!peer)
return NULL;
sctp_transport_set_owner(peer, asoc);
/* Initialize the peer's heartbeat interval based on the
* association configured value.
*/
peer->hbinterval = asoc->hbinterval;
peer->probe_interval = asoc->probe_interval;
peer->encap_port = asoc->encap_port;
/* Set the path max_retrans. */
peer->pathmaxrxt = asoc->pathmaxrxt;
/* And the partial failure retrans threshold */
peer->pf_retrans = asoc->pf_retrans;
/* And the primary path switchover retrans threshold */
peer->ps_retrans = asoc->ps_retrans;
/* Initialize the peer's SACK delay timeout based on the
* association configured value.
*/
peer->sackdelay = asoc->sackdelay;
peer->sackfreq = asoc->sackfreq;
if (addr->sa.sa_family == AF_INET6) {
__be32 info = addr->v6.sin6_flowinfo;
if (info) {
peer->flowlabel = ntohl(info & IPV6_FLOWLABEL_MASK);
peer->flowlabel |= SCTP_FLOWLABEL_SET_MASK;
} else {
peer->flowlabel = asoc->flowlabel;
}
}
peer->dscp = asoc->dscp;
/* Enable/disable heartbeat, SACK delay, and path MTU discovery
* based on association setting.
*/
peer->param_flags = asoc->param_flags;
/* Initialize the pmtu of the transport. */
sctp_transport_route(peer, NULL, sp);
/* If this is the first transport addr on this association,
* initialize the association PMTU to the peer's PMTU.
* If not and the current association PMTU is higher than the new
* peer's PMTU, reset the association PMTU to the new peer's PMTU.
*/
sctp_assoc_set_pmtu(asoc, asoc->pathmtu ?
min_t(int, peer->pathmtu, asoc->pathmtu) :
peer->pathmtu);
peer->pmtu_pending = 0;
/* The asoc->peer.port might not be meaningful yet, but
* initialize the packet structure anyway.
*/
sctp_packet_init(&peer->packet, peer, asoc->base.bind_addr.port,
asoc->peer.port);
/* 7.2.1 Slow-Start
*
* o The initial cwnd before DATA transmission or after a sufficiently
* long idle period MUST be set to
* min(4*MTU, max(2*MTU, 4380 bytes))
*
* o The initial value of ssthresh MAY be arbitrarily high
* (for example, implementations MAY use the size of the
* receiver advertised window).
*/
peer->cwnd = min(4*asoc->pathmtu, max_t(__u32, 2*asoc->pathmtu, 4380));
/* At this point, we may not have the receiver's advertised window,
* so initialize ssthresh to the default value and it will be set
* later when we process the INIT.
*/
peer->ssthresh = SCTP_DEFAULT_MAXWINDOW;
peer->partial_bytes_acked = 0;
peer->flight_size = 0;
peer->burst_limited = 0;
/* Set the transport's RTO.initial value */
peer->rto = asoc->rto_initial;
sctp_max_rto(asoc, peer);
/* Set the peer's active state. */
peer->state = peer_state;
/* Add this peer into the transport hashtable */
if (sctp_hash_transport(peer)) {
sctp_transport_free(peer);
return NULL;
}
sctp_transport_pl_reset(peer);
/* Attach the remote transport to our asoc. */
list_add_tail_rcu(&peer->transports, &asoc->peer.transport_addr_list);
asoc->peer.transport_count++;
sctp_ulpevent_notify_peer_addr_change(peer, SCTP_ADDR_ADDED, 0);
/* If we do not yet have a primary path, set one. */
if (!asoc->peer.primary_path) {
sctp_assoc_set_primary(asoc, peer);
asoc->peer.retran_path = peer;
}
if (asoc->peer.active_path == asoc->peer.retran_path &&
peer->state != SCTP_UNCONFIRMED) {
asoc->peer.retran_path = peer;
}
return peer;
}
/* Delete a transport address from an association. */
void sctp_assoc_del_peer(struct sctp_association *asoc,
const union sctp_addr *addr)
{
struct list_head *pos;
struct list_head *temp;
struct sctp_transport *transport;
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
if (sctp_cmp_addr_exact(addr, &transport->ipaddr)) {
/* Do book keeping for removing the peer and free it. */
sctp_assoc_rm_peer(asoc, transport);
break;
}
}
}
/* Lookup a transport by address. */
struct sctp_transport *sctp_assoc_lookup_paddr(
const struct sctp_association *asoc,
const union sctp_addr *address)
{
struct sctp_transport *t;
/* Cycle through all transports searching for a peer address. */
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
if (sctp_cmp_addr_exact(address, &t->ipaddr))
return t;
}
return NULL;
}
/* Remove all transports except a give one */
void sctp_assoc_del_nonprimary_peers(struct sctp_association *asoc,
struct sctp_transport *primary)
{
struct sctp_transport *temp;
struct sctp_transport *t;
list_for_each_entry_safe(t, temp, &asoc->peer.transport_addr_list,
transports) {
/* if the current transport is not the primary one, delete it */
if (t != primary)
sctp_assoc_rm_peer(asoc, t);
}
}
/* Engage in transport control operations.
* Mark the transport up or down and send a notification to the user.
* Select and update the new active and retran paths.
*/
void sctp_assoc_control_transport(struct sctp_association *asoc,
struct sctp_transport *transport,
enum sctp_transport_cmd command,
sctp_sn_error_t error)
{
int spc_state = SCTP_ADDR_AVAILABLE;
bool ulp_notify = true;
/* Record the transition on the transport. */
switch (command) {
case SCTP_TRANSPORT_UP:
/* If we are moving from UNCONFIRMED state due
* to heartbeat success, report the SCTP_ADDR_CONFIRMED
* state to the user, otherwise report SCTP_ADDR_AVAILABLE.
*/
if (transport->state == SCTP_PF &&
asoc->pf_expose != SCTP_PF_EXPOSE_ENABLE)
ulp_notify = false;
else if (transport->state == SCTP_UNCONFIRMED &&
error == SCTP_HEARTBEAT_SUCCESS)
spc_state = SCTP_ADDR_CONFIRMED;
transport->state = SCTP_ACTIVE;
sctp_transport_pl_reset(transport);
break;
case SCTP_TRANSPORT_DOWN:
/* If the transport was never confirmed, do not transition it
* to inactive state. Also, release the cached route since
* there may be a better route next time.
*/
if (transport->state != SCTP_UNCONFIRMED) {
transport->state = SCTP_INACTIVE;
sctp_transport_pl_reset(transport);
spc_state = SCTP_ADDR_UNREACHABLE;
} else {
sctp_transport_dst_release(transport);
ulp_notify = false;
}
break;
case SCTP_TRANSPORT_PF:
transport->state = SCTP_PF;
if (asoc->pf_expose != SCTP_PF_EXPOSE_ENABLE)
ulp_notify = false;
else
spc_state = SCTP_ADDR_POTENTIALLY_FAILED;
break;
default:
return;
}
/* Generate and send a SCTP_PEER_ADDR_CHANGE notification
* to the user.
*/
if (ulp_notify)
sctp_ulpevent_notify_peer_addr_change(transport,
spc_state, error);
/* Select new active and retran paths. */
sctp_select_active_and_retran_path(asoc);
}
/* Hold a reference to an association. */
void sctp_association_hold(struct sctp_association *asoc)
{
refcount_inc(&asoc->base.refcnt);
}
/* Release a reference to an association and cleanup
* if there are no more references.
*/
void sctp_association_put(struct sctp_association *asoc)
{
if (refcount_dec_and_test(&asoc->base.refcnt))
sctp_association_destroy(asoc);
}
/* Allocate the next TSN, Transmission Sequence Number, for the given
* association.
*/
__u32 sctp_association_get_next_tsn(struct sctp_association *asoc)
{
/* From Section 1.6 Serial Number Arithmetic:
* Transmission Sequence Numbers wrap around when they reach
* 2**32 - 1. That is, the next TSN a DATA chunk MUST use
* after transmitting TSN = 2*32 - 1 is TSN = 0.
*/
__u32 retval = asoc->next_tsn;
asoc->next_tsn++;
asoc->unack_data++;
return retval;
}
/* Compare two addresses to see if they match. Wildcard addresses
* only match themselves.
*/
int sctp_cmp_addr_exact(const union sctp_addr *ss1,
const union sctp_addr *ss2)
{
struct sctp_af *af;
af = sctp_get_af_specific(ss1->sa.sa_family);
if (unlikely(!af))
return 0;
return af->cmp_addr(ss1, ss2);
}
/* Return an ecne chunk to get prepended to a packet.
* Note: We are sly and return a shared, prealloced chunk. FIXME:
* No we don't, but we could/should.
*/
struct sctp_chunk *sctp_get_ecne_prepend(struct sctp_association *asoc)
{
if (!asoc->need_ecne)
return NULL;
/* Send ECNE if needed.
* Not being able to allocate a chunk here is not deadly.
*/
return sctp_make_ecne(asoc, asoc->last_ecne_tsn);
}
/*
* Find which transport this TSN was sent on.
*/
struct sctp_transport *sctp_assoc_lookup_tsn(struct sctp_association *asoc,
__u32 tsn)
{
struct sctp_transport *active;
struct sctp_transport *match;
struct sctp_transport *transport;
struct sctp_chunk *chunk;
__be32 key = htonl(tsn);
match = NULL;
/*
* FIXME: In general, find a more efficient data structure for
* searching.
*/
/*
* The general strategy is to search each transport's transmitted
* list. Return which transport this TSN lives on.
*
* Let's be hopeful and check the active_path first.
* Another optimization would be to know if there is only one
* outbound path and not have to look for the TSN at all.
*
*/
active = asoc->peer.active_path;
list_for_each_entry(chunk, &active->transmitted,
transmitted_list) {
if (key == chunk->subh.data_hdr->tsn) {
match = active;
goto out;
}
}
/* If not found, go search all the other transports. */
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
if (transport == active)
continue;
list_for_each_entry(chunk, &transport->transmitted,
transmitted_list) {
if (key == chunk->subh.data_hdr->tsn) {
match = transport;
goto out;
}
}
}
out:
return match;
}
/* Do delayed input processing. This is scheduled by sctp_rcv(). */
static void sctp_assoc_bh_rcv(struct work_struct *work)
{
struct sctp_association *asoc =
container_of(work, struct sctp_association,
base.inqueue.immediate);
struct net *net = asoc->base.net;
union sctp_subtype subtype;
struct sctp_endpoint *ep;
struct sctp_chunk *chunk;
struct sctp_inq *inqueue;
int first_time = 1; /* is this the first time through the loop */
int error = 0;
int state;
/* The association should be held so we should be safe. */
ep = asoc->ep;
inqueue = &asoc->base.inqueue;
sctp_association_hold(asoc);
while (NULL != (chunk = sctp_inq_pop(inqueue))) {
state = asoc->state;
subtype = SCTP_ST_CHUNK(chunk->chunk_hdr->type);
/* If the first chunk in the packet is AUTH, do special
* processing specified in Section 6.3 of SCTP-AUTH spec
*/
if (first_time && subtype.chunk == SCTP_CID_AUTH) {
struct sctp_chunkhdr *next_hdr;
next_hdr = sctp_inq_peek(inqueue);
if (!next_hdr)
goto normal;
/* If the next chunk is COOKIE-ECHO, skip the AUTH
* chunk while saving a pointer to it so we can do
* Authentication later (during cookie-echo
* processing).
*/
if (next_hdr->type == SCTP_CID_COOKIE_ECHO) {
chunk->auth_chunk = skb_clone(chunk->skb,
GFP_ATOMIC);
chunk->auth = 1;
continue;
}
}
normal:
/* SCTP-AUTH, Section 6.3:
* The receiver has a list of chunk types which it expects
* to be received only after an AUTH-chunk. This list has
* been sent to the peer during the association setup. It
* MUST silently discard these chunks if they are not placed
* after an AUTH chunk in the packet.
*/
if (sctp_auth_recv_cid(subtype.chunk, asoc) && !chunk->auth)
continue;
/* Remember where the last DATA chunk came from so we
* know where to send the SACK.
*/
if (sctp_chunk_is_data(chunk))
asoc->peer.last_data_from = chunk->transport;
else {
SCTP_INC_STATS(net, SCTP_MIB_INCTRLCHUNKS);
asoc->stats.ictrlchunks++;
if (chunk->chunk_hdr->type == SCTP_CID_SACK)
asoc->stats.isacks++;
}
if (chunk->transport)
chunk->transport->last_time_heard = ktime_get();
/* Run through the state machine. */
error = sctp_do_sm(net, SCTP_EVENT_T_CHUNK, subtype,
state, ep, asoc, chunk, GFP_ATOMIC);
/* Check to see if the association is freed in response to
* the incoming chunk. If so, get out of the while loop.
*/
if (asoc->base.dead)
break;
/* If there is an error on chunk, discard this packet. */
if (error && chunk)
chunk->pdiscard = 1;
if (first_time)
first_time = 0;
}
sctp_association_put(asoc);
}
/* This routine moves an association from its old sk to a new sk. */
void sctp_assoc_migrate(struct sctp_association *assoc, struct sock *newsk)
{
struct sctp_sock *newsp = sctp_sk(newsk);
struct sock *oldsk = assoc->base.sk;
/* Delete the association from the old endpoint's list of
* associations.
*/
list_del_init(&assoc->asocs);
/* Decrement the backlog value for a TCP-style socket. */
if (sctp_style(oldsk, TCP))
sk_acceptq_removed(oldsk);
/* Release references to the old endpoint and the sock. */
sctp_endpoint_put(assoc->ep);
sock_put(assoc->base.sk);
/* Get a reference to the new endpoint. */
assoc->ep = newsp->ep;
sctp_endpoint_hold(assoc->ep);
/* Get a reference to the new sock. */
assoc->base.sk = newsk;
sock_hold(assoc->base.sk);
/* Add the association to the new endpoint's list of associations. */
sctp_endpoint_add_asoc(newsp->ep, assoc);
}
/* Update an association (possibly from unexpected COOKIE-ECHO processing). */
int sctp_assoc_update(struct sctp_association *asoc,
struct sctp_association *new)
{
struct sctp_transport *trans;
struct list_head *pos, *temp;
/* Copy in new parameters of peer. */
asoc->c = new->c;
asoc->peer.rwnd = new->peer.rwnd;
asoc->peer.sack_needed = new->peer.sack_needed;
asoc->peer.auth_capable = new->peer.auth_capable;
asoc->peer.i = new->peer.i;
if (!sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, GFP_ATOMIC))
return -ENOMEM;
/* Remove any peer addresses not present in the new association. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
trans = list_entry(pos, struct sctp_transport, transports);
if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {
sctp_assoc_rm_peer(asoc, trans);
continue;
}
if (asoc->state >= SCTP_STATE_ESTABLISHED)
sctp_transport_reset(trans);
}
/* If the case is A (association restart), use
* initial_tsn as next_tsn. If the case is B, use
* current next_tsn in case data sent to peer
* has been discarded and needs retransmission.
*/
if (asoc->state >= SCTP_STATE_ESTABLISHED) {
asoc->next_tsn = new->next_tsn;
asoc->ctsn_ack_point = new->ctsn_ack_point;
asoc->adv_peer_ack_point = new->adv_peer_ack_point;
/* Reinitialize SSN for both local streams
* and peer's streams.
*/
sctp_stream_clear(&asoc->stream);
/* Flush the ULP reassembly and ordered queue.
* Any data there will now be stale and will
* cause problems.
*/
sctp_ulpq_flush(&asoc->ulpq);
/* reset the overall association error count so
* that the restarted association doesn't get torn
* down on the next retransmission timer.
*/
asoc->overall_error_count = 0;
} else {
/* Add any peer addresses from the new association. */
list_for_each_entry(trans, &new->peer.transport_addr_list,
transports)
if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr) &&
!sctp_assoc_add_peer(asoc, &trans->ipaddr,
GFP_ATOMIC, trans->state))
return -ENOMEM;
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
if (sctp_state(asoc, COOKIE_WAIT))
sctp_stream_update(&asoc->stream, &new->stream);
/* get a new assoc id if we don't have one yet. */
if (sctp_assoc_set_id(asoc, GFP_ATOMIC))
return -ENOMEM;
}
/* SCTP-AUTH: Save the peer parameters from the new associations
* and also move the association shared keys over
*/
kfree(asoc->peer.peer_random);
asoc->peer.peer_random = new->peer.peer_random;
new->peer.peer_random = NULL;
kfree(asoc->peer.peer_chunks);
asoc->peer.peer_chunks = new->peer.peer_chunks;
new->peer.peer_chunks = NULL;
kfree(asoc->peer.peer_hmacs);
asoc->peer.peer_hmacs = new->peer.peer_hmacs;
new->peer.peer_hmacs = NULL;
return sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);
}
/* Update the retran path for sending a retransmitted packet.
* See also RFC4960, 6.4. Multi-Homed SCTP Endpoints:
*
* When there is outbound data to send and the primary path
* becomes inactive (e.g., due to failures), or where the
* SCTP user explicitly requests to send data to an
* inactive destination transport address, before reporting
* an error to its ULP, the SCTP endpoint should try to send
* the data to an alternate active destination transport
* address if one exists.
*
* When retransmitting data that timed out, if the endpoint
* is multihomed, it should consider each source-destination
* address pair in its retransmission selection policy.
* When retransmitting timed-out data, the endpoint should
* attempt to pick the most divergent source-destination
* pair from the original source-destination pair to which
* the packet was transmitted.
*
* Note: Rules for picking the most divergent source-destination
* pair are an implementation decision and are not specified
* within this document.
*
* Our basic strategy is to round-robin transports in priorities
* according to sctp_trans_score() e.g., if no such
* transport with state SCTP_ACTIVE exists, round-robin through
* SCTP_UNKNOWN, etc. You get the picture.
*/
static u8 sctp_trans_score(const struct sctp_transport *trans)
{
switch (trans->state) {
case SCTP_ACTIVE:
return 3; /* best case */
case SCTP_UNKNOWN:
return 2;
case SCTP_PF:
return 1;
default: /* case SCTP_INACTIVE */
return 0; /* worst case */
}
}
static struct sctp_transport *sctp_trans_elect_tie(struct sctp_transport *trans1,
struct sctp_transport *trans2)
{
if (trans1->error_count > trans2->error_count) {
return trans2;
} else if (trans1->error_count == trans2->error_count &&
ktime_after(trans2->last_time_heard,
trans1->last_time_heard)) {
return trans2;
} else {
return trans1;
}
}
static struct sctp_transport *sctp_trans_elect_best(struct sctp_transport *curr,
struct sctp_transport *best)
{
u8 score_curr, score_best;
if (best == NULL || curr == best)
return curr;
score_curr = sctp_trans_score(curr);
score_best = sctp_trans_score(best);
/* First, try a score-based selection if both transport states
* differ. If we're in a tie, lets try to make a more clever
* decision here based on error counts and last time heard.
*/
if (score_curr > score_best)
return curr;
else if (score_curr == score_best)
return sctp_trans_elect_tie(best, curr);
else
return best;
}
void sctp_assoc_update_retran_path(struct sctp_association *asoc)
{
struct sctp_transport *trans = asoc->peer.retran_path;
struct sctp_transport *trans_next = NULL;
/* We're done as we only have the one and only path. */
if (asoc->peer.transport_count == 1)
return;
/* If active_path and retran_path are the same and active,
* then this is the only active path. Use it.
*/
if (asoc->peer.active_path == asoc->peer.retran_path &&
asoc->peer.active_path->state == SCTP_ACTIVE)
return;
/* Iterate from retran_path's successor back to retran_path. */
for (trans = list_next_entry(trans, transports); 1;
trans = list_next_entry(trans, transports)) {
/* Manually skip the head element. */
if (&trans->transports == &asoc->peer.transport_addr_list)
continue;
if (trans->state == SCTP_UNCONFIRMED)
continue;
trans_next = sctp_trans_elect_best(trans, trans_next);
/* Active is good enough for immediate return. */
if (trans_next->state == SCTP_ACTIVE)
break;
/* We've reached the end, time to update path. */
if (trans == asoc->peer.retran_path)
break;
}
asoc->peer.retran_path = trans_next;
pr_debug("%s: association:%p updated new path to addr:%pISpc\n",
__func__, asoc, &asoc->peer.retran_path->ipaddr.sa);
}
static void sctp_select_active_and_retran_path(struct sctp_association *asoc)
{
struct sctp_transport *trans, *trans_pri = NULL, *trans_sec = NULL;
struct sctp_transport *trans_pf = NULL;
/* Look for the two most recently used active transports. */
list_for_each_entry(trans, &asoc->peer.transport_addr_list,
transports) {
/* Skip uninteresting transports. */
if (trans->state == SCTP_INACTIVE ||
trans->state == SCTP_UNCONFIRMED)
continue;
/* Keep track of the best PF transport from our
* list in case we don't find an active one.
*/
if (trans->state == SCTP_PF) {
trans_pf = sctp_trans_elect_best(trans, trans_pf);
continue;
}
/* For active transports, pick the most recent ones. */
if (trans_pri == NULL ||
ktime_after(trans->last_time_heard,
trans_pri->last_time_heard)) {
trans_sec = trans_pri;
trans_pri = trans;
} else if (trans_sec == NULL ||
ktime_after(trans->last_time_heard,
trans_sec->last_time_heard)) {
trans_sec = trans;
}
}
/* RFC 2960 6.4 Multi-Homed SCTP Endpoints
*
* By default, an endpoint should always transmit to the primary
* path, unless the SCTP user explicitly specifies the
* destination transport address (and possibly source transport
* address) to use. [If the primary is active but not most recent,
* bump the most recently used transport.]
*/
if ((asoc->peer.primary_path->state == SCTP_ACTIVE ||
asoc->peer.primary_path->state == SCTP_UNKNOWN) &&
asoc->peer.primary_path != trans_pri) {
trans_sec = trans_pri;
trans_pri = asoc->peer.primary_path;
}
/* We did not find anything useful for a possible retransmission
* path; either primary path that we found is the same as
* the current one, or we didn't generally find an active one.
*/
if (trans_sec == NULL)
trans_sec = trans_pri;
/* If we failed to find a usable transport, just camp on the
* active or pick a PF iff it's the better choice.
*/
if (trans_pri == NULL) {
trans_pri = sctp_trans_elect_best(asoc->peer.active_path, trans_pf);
trans_sec = trans_pri;
}
/* Set the active and retran transports. */
asoc->peer.active_path = trans_pri;
asoc->peer.retran_path = trans_sec;
}
struct sctp_transport *
sctp_assoc_choose_alter_transport(struct sctp_association *asoc,
struct sctp_transport *last_sent_to)
{
/* If this is the first time packet is sent, use the active path,
* else use the retran path. If the last packet was sent over the
* retran path, update the retran path and use it.
*/
if (last_sent_to == NULL) {
return asoc->peer.active_path;
} else {
if (last_sent_to == asoc->peer.retran_path)
sctp_assoc_update_retran_path(asoc);
return asoc->peer.retran_path;
}
}
void sctp_assoc_update_frag_point(struct sctp_association *asoc)
{
int frag = sctp_mtu_payload(sctp_sk(asoc->base.sk), asoc->pathmtu,
sctp_datachk_len(&asoc->stream));
if (asoc->user_frag)
frag = min_t(int, frag, asoc->user_frag);
frag = min_t(int, frag, SCTP_MAX_CHUNK_LEN -
sctp_datachk_len(&asoc->stream));
asoc->frag_point = SCTP_TRUNC4(frag);
}
void sctp_assoc_set_pmtu(struct sctp_association *asoc, __u32 pmtu)
{
if (asoc->pathmtu != pmtu) {
asoc->pathmtu = pmtu;
sctp_assoc_update_frag_point(asoc);
}
pr_debug("%s: asoc:%p, pmtu:%d, frag_point:%d\n", __func__, asoc,
asoc->pathmtu, asoc->frag_point);
}
/* Update the association's pmtu and frag_point by going through all the
* transports. This routine is called when a transport's PMTU has changed.
*/
void sctp_assoc_sync_pmtu(struct sctp_association *asoc)
{
struct sctp_transport *t;
__u32 pmtu = 0;
if (!asoc)
return;
/* Get the lowest pmtu of all the transports. */
list_for_each_entry(t, &asoc->peer.transport_addr_list, transports) {
if (t->pmtu_pending && t->dst) {
sctp_transport_update_pmtu(t,
atomic_read(&t->mtu_info));
t->pmtu_pending = 0;
}
if (!pmtu || (t->pathmtu < pmtu))
pmtu = t->pathmtu;
}
sctp_assoc_set_pmtu(asoc, pmtu);
}
/* Should we send a SACK to update our peer? */
static inline bool sctp_peer_needs_update(struct sctp_association *asoc)
{
struct net *net = asoc->base.net;
switch (asoc->state) {
case SCTP_STATE_ESTABLISHED:
case SCTP_STATE_SHUTDOWN_PENDING:
case SCTP_STATE_SHUTDOWN_RECEIVED:
case SCTP_STATE_SHUTDOWN_SENT:
if ((asoc->rwnd > asoc->a_rwnd) &&
((asoc->rwnd - asoc->a_rwnd) >= max_t(__u32,
(asoc->base.sk->sk_rcvbuf >> net->sctp.rwnd_upd_shift),
asoc->pathmtu)))
return true;
break;
default:
break;
}
return false;
}
/* Increase asoc's rwnd by len and send any window update SACK if needed. */
void sctp_assoc_rwnd_increase(struct sctp_association *asoc, unsigned int len)
{
struct sctp_chunk *sack;
struct timer_list *timer;
if (asoc->rwnd_over) {
if (asoc->rwnd_over >= len) {
asoc->rwnd_over -= len;
} else {
asoc->rwnd += (len - asoc->rwnd_over);
asoc->rwnd_over = 0;
}
} else {
asoc->rwnd += len;
}
/* If we had window pressure, start recovering it
* once our rwnd had reached the accumulated pressure
* threshold. The idea is to recover slowly, but up
* to the initial advertised window.
*/
if (asoc->rwnd_press) {
int change = min(asoc->pathmtu, asoc->rwnd_press);
asoc->rwnd += change;
asoc->rwnd_press -= change;
}
pr_debug("%s: asoc:%p rwnd increased by %d to (%u, %u) - %u\n",
__func__, asoc, len, asoc->rwnd, asoc->rwnd_over,
asoc->a_rwnd);
/* Send a window update SACK if the rwnd has increased by at least the
* minimum of the association's PMTU and half of the receive buffer.
* The algorithm used is similar to the one described in
* Section 4.2.3.3 of RFC 1122.
*/
if (sctp_peer_needs_update(asoc)) {
asoc->a_rwnd = asoc->rwnd;
pr_debug("%s: sending window update SACK- asoc:%p rwnd:%u "
"a_rwnd:%u\n", __func__, asoc, asoc->rwnd,
asoc->a_rwnd);
sack = sctp_make_sack(asoc);
if (!sack)
return;
asoc->peer.sack_needed = 0;
sctp_outq_tail(&asoc->outqueue, sack, GFP_ATOMIC);
/* Stop the SACK timer. */
timer = &asoc->timers[SCTP_EVENT_TIMEOUT_SACK];
if (del_timer(timer))
sctp_association_put(asoc);
}
}
/* Decrease asoc's rwnd by len. */
void sctp_assoc_rwnd_decrease(struct sctp_association *asoc, unsigned int len)
{
int rx_count;
int over = 0;
if (unlikely(!asoc->rwnd || asoc->rwnd_over))
pr_debug("%s: association:%p has asoc->rwnd:%u, "
"asoc->rwnd_over:%u!\n", __func__, asoc,
asoc->rwnd, asoc->rwnd_over);
if (asoc->ep->rcvbuf_policy)
rx_count = atomic_read(&asoc->rmem_alloc);
else
rx_count = atomic_read(&asoc->base.sk->sk_rmem_alloc);
/* If we've reached or overflowed our receive buffer, announce
* a 0 rwnd if rwnd would still be positive. Store the
* potential pressure overflow so that the window can be restored
* back to original value.
*/
if (rx_count >= asoc->base.sk->sk_rcvbuf)
over = 1;
if (asoc->rwnd >= len) {
asoc->rwnd -= len;
if (over) {
asoc->rwnd_press += asoc->rwnd;
asoc->rwnd = 0;
}
} else {
asoc->rwnd_over += len - asoc->rwnd;
asoc->rwnd = 0;
}
pr_debug("%s: asoc:%p rwnd decreased by %d to (%u, %u, %u)\n",
__func__, asoc, len, asoc->rwnd, asoc->rwnd_over,
asoc->rwnd_press);
}
/* Build the bind address list for the association based on info from the
* local endpoint and the remote peer.
*/
int sctp_assoc_set_bind_addr_from_ep(struct sctp_association *asoc,
enum sctp_scope scope, gfp_t gfp)
{
struct sock *sk = asoc->base.sk;
int flags;
/* Use scoping rules to determine the subset of addresses from
* the endpoint.
*/
flags = (PF_INET6 == sk->sk_family) ? SCTP_ADDR6_ALLOWED : 0;
if (!inet_v6_ipv6only(sk))
flags |= SCTP_ADDR4_ALLOWED;
if (asoc->peer.ipv4_address)
flags |= SCTP_ADDR4_PEERSUPP;
if (asoc->peer.ipv6_address)
flags |= SCTP_ADDR6_PEERSUPP;
return sctp_bind_addr_copy(asoc->base.net,
&asoc->base.bind_addr,
&asoc->ep->base.bind_addr,
scope, gfp, flags);
}
/* Build the association's bind address list from the cookie. */
int sctp_assoc_set_bind_addr_from_cookie(struct sctp_association *asoc,
struct sctp_cookie *cookie,
gfp_t gfp)
{
struct sctp_init_chunk *peer_init = (struct sctp_init_chunk *)(cookie + 1);
int var_size2 = ntohs(peer_init->chunk_hdr.length);
int var_size3 = cookie->raw_addr_list_len;
__u8 *raw = (__u8 *)peer_init + var_size2;
return sctp_raw_to_bind_addrs(&asoc->base.bind_addr, raw, var_size3,
asoc->ep->base.bind_addr.port, gfp);
}
/* Lookup laddr in the bind address list of an association. */
int sctp_assoc_lookup_laddr(struct sctp_association *asoc,
const union sctp_addr *laddr)
{
int found = 0;
if ((asoc->base.bind_addr.port == ntohs(laddr->v4.sin_port)) &&
sctp_bind_addr_match(&asoc->base.bind_addr, laddr,
sctp_sk(asoc->base.sk)))
found = 1;
return found;
}
/* Set an association id for a given association */
int sctp_assoc_set_id(struct sctp_association *asoc, gfp_t gfp)
{
bool preload = gfpflags_allow_blocking(gfp);
int ret;
/* If the id is already assigned, keep it. */
if (asoc->assoc_id)
return 0;
if (preload)
idr_preload(gfp);
spin_lock_bh(&sctp_assocs_id_lock);
/* 0, 1, 2 are used as SCTP_FUTURE_ASSOC, SCTP_CURRENT_ASSOC and
* SCTP_ALL_ASSOC, so an available id must be > SCTP_ALL_ASSOC.
*/
ret = idr_alloc_cyclic(&sctp_assocs_id, asoc, SCTP_ALL_ASSOC + 1, 0,
GFP_NOWAIT);
spin_unlock_bh(&sctp_assocs_id_lock);
if (preload)
idr_preload_end();
if (ret < 0)
return ret;
asoc->assoc_id = (sctp_assoc_t)ret;
return 0;
}
/* Free the ASCONF queue */
static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc)
{
struct sctp_chunk *asconf;
struct sctp_chunk *tmp;
list_for_each_entry_safe(asconf, tmp, &asoc->addip_chunk_list, list) {
list_del_init(&asconf->list);
sctp_chunk_free(asconf);
}
}
/* Free asconf_ack cache */
static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc)
{
struct sctp_chunk *ack;
struct sctp_chunk *tmp;
list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list,
transmitted_list) {
list_del_init(&ack->transmitted_list);
sctp_chunk_free(ack);
}
}
/* Clean up the ASCONF_ACK queue */
void sctp_assoc_clean_asconf_ack_cache(const struct sctp_association *asoc)
{
struct sctp_chunk *ack;
struct sctp_chunk *tmp;
/* We can remove all the entries from the queue up to
* the "Peer-Sequence-Number".
*/
list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list,
transmitted_list) {
if (ack->subh.addip_hdr->serial ==
htonl(asoc->peer.addip_serial))
break;
list_del_init(&ack->transmitted_list);
sctp_chunk_free(ack);
}
}
/* Find the ASCONF_ACK whose serial number matches ASCONF */
struct sctp_chunk *sctp_assoc_lookup_asconf_ack(
const struct sctp_association *asoc,
__be32 serial)
{
struct sctp_chunk *ack;
/* Walk through the list of cached ASCONF-ACKs and find the
* ack chunk whose serial number matches that of the request.
*/
list_for_each_entry(ack, &asoc->asconf_ack_list, transmitted_list) {
if (sctp_chunk_pending(ack))
continue;
if (ack->subh.addip_hdr->serial == serial) {
sctp_chunk_hold(ack);
return ack;
}
}
return NULL;
}
void sctp_asconf_queue_teardown(struct sctp_association *asoc)
{
/* Free any cached ASCONF_ACK chunk. */
sctp_assoc_free_asconf_acks(asoc);
/* Free the ASCONF queue. */
sctp_assoc_free_asconf_queue(asoc);
/* Free any cached ASCONF chunk. */
if (asoc->addip_last_asconf)
sctp_chunk_free(asoc->addip_last_asconf);
}
| linux-master | net/sctp/associola.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 Nokia, Inc.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* These functions manipulate an sctp event. The struct ulpevent is used
* to carry notifications and data to the ULP (sockets).
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Jon Grimm <[email protected]>
* La Monte H.P. Yarroll <[email protected]>
* Ardelle Fan <[email protected]>
* Sridhar Samudrala <[email protected]>
*/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <net/sctp/structs.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
static void sctp_ulpevent_receive_data(struct sctp_ulpevent *event,
struct sctp_association *asoc);
static void sctp_ulpevent_release_data(struct sctp_ulpevent *event);
static void sctp_ulpevent_release_frag_data(struct sctp_ulpevent *event);
/* Initialize an ULP event from an given skb. */
static void sctp_ulpevent_init(struct sctp_ulpevent *event,
__u16 msg_flags,
unsigned int len)
{
memset(event, 0, sizeof(struct sctp_ulpevent));
event->msg_flags = msg_flags;
event->rmem_len = len;
}
/* Create a new sctp_ulpevent. */
static struct sctp_ulpevent *sctp_ulpevent_new(int size, __u16 msg_flags,
gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sk_buff *skb;
skb = alloc_skb(size, gfp);
if (!skb)
goto fail;
event = sctp_skb2event(skb);
sctp_ulpevent_init(event, msg_flags, skb->truesize);
return event;
fail:
return NULL;
}
/* Is this a MSG_NOTIFICATION? */
int sctp_ulpevent_is_notification(const struct sctp_ulpevent *event)
{
return MSG_NOTIFICATION == (event->msg_flags & MSG_NOTIFICATION);
}
/* Hold the association in case the msg_name needs read out of
* the association.
*/
static inline void sctp_ulpevent_set_owner(struct sctp_ulpevent *event,
const struct sctp_association *asoc)
{
struct sctp_chunk *chunk = event->chunk;
struct sk_buff *skb;
/* Cast away the const, as we are just wanting to
* bump the reference count.
*/
sctp_association_hold((struct sctp_association *)asoc);
skb = sctp_event2skb(event);
event->asoc = (struct sctp_association *)asoc;
atomic_add(event->rmem_len, &event->asoc->rmem_alloc);
sctp_skb_set_owner_r(skb, asoc->base.sk);
if (chunk && chunk->head_skb && !chunk->head_skb->sk)
chunk->head_skb->sk = asoc->base.sk;
}
/* A simple destructor to give up the reference to the association. */
static inline void sctp_ulpevent_release_owner(struct sctp_ulpevent *event)
{
struct sctp_association *asoc = event->asoc;
atomic_sub(event->rmem_len, &asoc->rmem_alloc);
sctp_association_put(asoc);
}
/* Create and initialize an SCTP_ASSOC_CHANGE event.
*
* 5.3.1.1 SCTP_ASSOC_CHANGE
*
* Communication notifications inform the ULP that an SCTP association
* has either begun or ended. The identifier for a new association is
* provided by this notification.
*
* Note: There is no field checking here. If a field is unused it will be
* zero'd out.
*/
struct sctp_ulpevent *sctp_ulpevent_make_assoc_change(
const struct sctp_association *asoc,
__u16 flags, __u16 state, __u16 error, __u16 outbound,
__u16 inbound, struct sctp_chunk *chunk, gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sctp_assoc_change *sac;
struct sk_buff *skb;
/* If the lower layer passed in the chunk, it will be
* an ABORT, so we need to include it in the sac_info.
*/
if (chunk) {
/* Copy the chunk data to a new skb and reserve enough
* head room to use as notification.
*/
skb = skb_copy_expand(chunk->skb,
sizeof(struct sctp_assoc_change), 0, gfp);
if (!skb)
goto fail;
/* Embed the event fields inside the cloned skb. */
event = sctp_skb2event(skb);
sctp_ulpevent_init(event, MSG_NOTIFICATION, skb->truesize);
/* Include the notification structure */
sac = skb_push(skb, sizeof(struct sctp_assoc_change));
/* Trim the buffer to the right length. */
skb_trim(skb, sizeof(struct sctp_assoc_change) +
ntohs(chunk->chunk_hdr->length) -
sizeof(struct sctp_chunkhdr));
} else {
event = sctp_ulpevent_new(sizeof(struct sctp_assoc_change),
MSG_NOTIFICATION, gfp);
if (!event)
goto fail;
skb = sctp_event2skb(event);
sac = skb_put(skb, sizeof(struct sctp_assoc_change));
}
/* Socket Extensions for SCTP
* 5.3.1.1 SCTP_ASSOC_CHANGE
*
* sac_type:
* It should be SCTP_ASSOC_CHANGE.
*/
sac->sac_type = SCTP_ASSOC_CHANGE;
/* Socket Extensions for SCTP
* 5.3.1.1 SCTP_ASSOC_CHANGE
*
* sac_state: 32 bits (signed integer)
* This field holds one of a number of values that communicate the
* event that happened to the association.
*/
sac->sac_state = state;
/* Socket Extensions for SCTP
* 5.3.1.1 SCTP_ASSOC_CHANGE
*
* sac_flags: 16 bits (unsigned integer)
* Currently unused.
*/
sac->sac_flags = 0;
/* Socket Extensions for SCTP
* 5.3.1.1 SCTP_ASSOC_CHANGE
*
* sac_length: sizeof (__u32)
* This field is the total length of the notification data, including
* the notification header.
*/
sac->sac_length = skb->len;
/* Socket Extensions for SCTP
* 5.3.1.1 SCTP_ASSOC_CHANGE
*
* sac_error: 32 bits (signed integer)
*
* If the state was reached due to a error condition (e.g.
* COMMUNICATION_LOST) any relevant error information is available in
* this field. This corresponds to the protocol error codes defined in
* [SCTP].
*/
sac->sac_error = error;
/* Socket Extensions for SCTP
* 5.3.1.1 SCTP_ASSOC_CHANGE
*
* sac_outbound_streams: 16 bits (unsigned integer)
* sac_inbound_streams: 16 bits (unsigned integer)
*
* The maximum number of streams allowed in each direction are
* available in sac_outbound_streams and sac_inbound streams.
*/
sac->sac_outbound_streams = outbound;
sac->sac_inbound_streams = inbound;
/* Socket Extensions for SCTP
* 5.3.1.1 SCTP_ASSOC_CHANGE
*
* sac_assoc_id: sizeof (sctp_assoc_t)
*
* The association id field, holds the identifier for the association.
* All notifications for a given association have the same association
* identifier. For TCP style socket, this field is ignored.
*/
sctp_ulpevent_set_owner(event, asoc);
sac->sac_assoc_id = sctp_assoc2id(asoc);
return event;
fail:
return NULL;
}
/* Create and initialize an SCTP_PEER_ADDR_CHANGE event.
*
* Socket Extensions for SCTP - draft-01
* 5.3.1.2 SCTP_PEER_ADDR_CHANGE
*
* When a destination address on a multi-homed peer encounters a change
* an interface details event is sent.
*/
static struct sctp_ulpevent *sctp_ulpevent_make_peer_addr_change(
const struct sctp_association *asoc,
const struct sockaddr_storage *aaddr,
int flags, int state, int error, gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sctp_paddr_change *spc;
struct sk_buff *skb;
event = sctp_ulpevent_new(sizeof(struct sctp_paddr_change),
MSG_NOTIFICATION, gfp);
if (!event)
goto fail;
skb = sctp_event2skb(event);
spc = skb_put(skb, sizeof(struct sctp_paddr_change));
/* Sockets API Extensions for SCTP
* Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
*
* spc_type:
*
* It should be SCTP_PEER_ADDR_CHANGE.
*/
spc->spc_type = SCTP_PEER_ADDR_CHANGE;
/* Sockets API Extensions for SCTP
* Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
*
* spc_length: sizeof (__u32)
*
* This field is the total length of the notification data, including
* the notification header.
*/
spc->spc_length = sizeof(struct sctp_paddr_change);
/* Sockets API Extensions for SCTP
* Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
*
* spc_flags: 16 bits (unsigned integer)
* Currently unused.
*/
spc->spc_flags = 0;
/* Sockets API Extensions for SCTP
* Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
*
* spc_state: 32 bits (signed integer)
*
* This field holds one of a number of values that communicate the
* event that happened to the address.
*/
spc->spc_state = state;
/* Sockets API Extensions for SCTP
* Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
*
* spc_error: 32 bits (signed integer)
*
* If the state was reached due to any error condition (e.g.
* ADDRESS_UNREACHABLE) any relevant error information is available in
* this field.
*/
spc->spc_error = error;
/* Socket Extensions for SCTP
* 5.3.1.1 SCTP_ASSOC_CHANGE
*
* spc_assoc_id: sizeof (sctp_assoc_t)
*
* The association id field, holds the identifier for the association.
* All notifications for a given association have the same association
* identifier. For TCP style socket, this field is ignored.
*/
sctp_ulpevent_set_owner(event, asoc);
spc->spc_assoc_id = sctp_assoc2id(asoc);
/* Sockets API Extensions for SCTP
* Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE
*
* spc_aaddr: sizeof (struct sockaddr_storage)
*
* The affected address field, holds the remote peer's address that is
* encountering the change of state.
*/
memcpy(&spc->spc_aaddr, aaddr, sizeof(struct sockaddr_storage));
/* Map ipv4 address into v4-mapped-on-v6 address. */
sctp_get_pf_specific(asoc->base.sk->sk_family)->addr_to_user(
sctp_sk(asoc->base.sk),
(union sctp_addr *)&spc->spc_aaddr);
return event;
fail:
return NULL;
}
void sctp_ulpevent_notify_peer_addr_change(struct sctp_transport *transport,
int state, int error)
{
struct sctp_association *asoc = transport->asoc;
struct sockaddr_storage addr;
struct sctp_ulpevent *event;
if (asoc->state < SCTP_STATE_ESTABLISHED)
return;
memset(&addr, 0, sizeof(struct sockaddr_storage));
memcpy(&addr, &transport->ipaddr, transport->af_specific->sockaddr_len);
event = sctp_ulpevent_make_peer_addr_change(asoc, &addr, 0, state,
error, GFP_ATOMIC);
if (event)
asoc->stream.si->enqueue_event(&asoc->ulpq, event);
}
/* Create and initialize an SCTP_REMOTE_ERROR notification.
*
* Note: This assumes that the chunk->skb->data already points to the
* operation error payload.
*
* Socket Extensions for SCTP - draft-01
* 5.3.1.3 SCTP_REMOTE_ERROR
*
* A remote peer may send an Operational Error message to its peer.
* This message indicates a variety of error conditions on an
* association. The entire error TLV as it appears on the wire is
* included in a SCTP_REMOTE_ERROR event. Please refer to the SCTP
* specification [SCTP] and any extensions for a list of possible
* error formats.
*/
struct sctp_ulpevent *
sctp_ulpevent_make_remote_error(const struct sctp_association *asoc,
struct sctp_chunk *chunk, __u16 flags,
gfp_t gfp)
{
struct sctp_remote_error *sre;
struct sctp_ulpevent *event;
struct sctp_errhdr *ch;
struct sk_buff *skb;
__be16 cause;
int elen;
ch = (struct sctp_errhdr *)(chunk->skb->data);
cause = ch->cause;
elen = SCTP_PAD4(ntohs(ch->length)) - sizeof(*ch);
/* Pull off the ERROR header. */
skb_pull(chunk->skb, sizeof(*ch));
/* Copy the skb to a new skb with room for us to prepend
* notification with.
*/
skb = skb_copy_expand(chunk->skb, sizeof(*sre), 0, gfp);
/* Pull off the rest of the cause TLV from the chunk. */
skb_pull(chunk->skb, elen);
if (!skb)
goto fail;
/* Embed the event fields inside the cloned skb. */
event = sctp_skb2event(skb);
sctp_ulpevent_init(event, MSG_NOTIFICATION, skb->truesize);
sre = skb_push(skb, sizeof(*sre));
/* Trim the buffer to the right length. */
skb_trim(skb, sizeof(*sre) + elen);
/* RFC6458, Section 6.1.3. SCTP_REMOTE_ERROR */
memset(sre, 0, sizeof(*sre));
sre->sre_type = SCTP_REMOTE_ERROR;
sre->sre_flags = 0;
sre->sre_length = skb->len;
sre->sre_error = cause;
sctp_ulpevent_set_owner(event, asoc);
sre->sre_assoc_id = sctp_assoc2id(asoc);
return event;
fail:
return NULL;
}
/* Create and initialize a SCTP_SEND_FAILED notification.
*
* Socket Extensions for SCTP - draft-01
* 5.3.1.4 SCTP_SEND_FAILED
*/
struct sctp_ulpevent *sctp_ulpevent_make_send_failed(
const struct sctp_association *asoc, struct sctp_chunk *chunk,
__u16 flags, __u32 error, gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sctp_send_failed *ssf;
struct sk_buff *skb;
/* Pull off any padding. */
int len = ntohs(chunk->chunk_hdr->length);
/* Make skb with more room so we can prepend notification. */
skb = skb_copy_expand(chunk->skb,
sizeof(struct sctp_send_failed), /* headroom */
0, /* tailroom */
gfp);
if (!skb)
goto fail;
/* Pull off the common chunk header and DATA header. */
skb_pull(skb, sctp_datachk_len(&asoc->stream));
len -= sctp_datachk_len(&asoc->stream);
/* Embed the event fields inside the cloned skb. */
event = sctp_skb2event(skb);
sctp_ulpevent_init(event, MSG_NOTIFICATION, skb->truesize);
ssf = skb_push(skb, sizeof(struct sctp_send_failed));
/* Socket Extensions for SCTP
* 5.3.1.4 SCTP_SEND_FAILED
*
* ssf_type:
* It should be SCTP_SEND_FAILED.
*/
ssf->ssf_type = SCTP_SEND_FAILED;
/* Socket Extensions for SCTP
* 5.3.1.4 SCTP_SEND_FAILED
*
* ssf_flags: 16 bits (unsigned integer)
* The flag value will take one of the following values
*
* SCTP_DATA_UNSENT - Indicates that the data was never put on
* the wire.
*
* SCTP_DATA_SENT - Indicates that the data was put on the wire.
* Note that this does not necessarily mean that the
* data was (or was not) successfully delivered.
*/
ssf->ssf_flags = flags;
/* Socket Extensions for SCTP
* 5.3.1.4 SCTP_SEND_FAILED
*
* ssf_length: sizeof (__u32)
* This field is the total length of the notification data, including
* the notification header.
*/
ssf->ssf_length = sizeof(struct sctp_send_failed) + len;
skb_trim(skb, ssf->ssf_length);
/* Socket Extensions for SCTP
* 5.3.1.4 SCTP_SEND_FAILED
*
* ssf_error: 16 bits (unsigned integer)
* This value represents the reason why the send failed, and if set,
* will be a SCTP protocol error code as defined in [SCTP] section
* 3.3.10.
*/
ssf->ssf_error = error;
/* Socket Extensions for SCTP
* 5.3.1.4 SCTP_SEND_FAILED
*
* ssf_info: sizeof (struct sctp_sndrcvinfo)
* The original send information associated with the undelivered
* message.
*/
memcpy(&ssf->ssf_info, &chunk->sinfo, sizeof(struct sctp_sndrcvinfo));
/* Per TSVWG discussion with Randy. Allow the application to
* reassemble a fragmented message.
*/
ssf->ssf_info.sinfo_flags = chunk->chunk_hdr->flags;
/* Socket Extensions for SCTP
* 5.3.1.4 SCTP_SEND_FAILED
*
* ssf_assoc_id: sizeof (sctp_assoc_t)
* The association id field, sf_assoc_id, holds the identifier for the
* association. All notifications for a given association have the
* same association identifier. For TCP style socket, this field is
* ignored.
*/
sctp_ulpevent_set_owner(event, asoc);
ssf->ssf_assoc_id = sctp_assoc2id(asoc);
return event;
fail:
return NULL;
}
struct sctp_ulpevent *sctp_ulpevent_make_send_failed_event(
const struct sctp_association *asoc, struct sctp_chunk *chunk,
__u16 flags, __u32 error, gfp_t gfp)
{
struct sctp_send_failed_event *ssf;
struct sctp_ulpevent *event;
struct sk_buff *skb;
int len;
skb = skb_copy_expand(chunk->skb, sizeof(*ssf), 0, gfp);
if (!skb)
return NULL;
len = ntohs(chunk->chunk_hdr->length);
len -= sctp_datachk_len(&asoc->stream);
skb_pull(skb, sctp_datachk_len(&asoc->stream));
event = sctp_skb2event(skb);
sctp_ulpevent_init(event, MSG_NOTIFICATION, skb->truesize);
ssf = skb_push(skb, sizeof(*ssf));
ssf->ssf_type = SCTP_SEND_FAILED_EVENT;
ssf->ssf_flags = flags;
ssf->ssf_length = sizeof(*ssf) + len;
skb_trim(skb, ssf->ssf_length);
ssf->ssf_error = error;
ssf->ssfe_info.snd_sid = chunk->sinfo.sinfo_stream;
ssf->ssfe_info.snd_ppid = chunk->sinfo.sinfo_ppid;
ssf->ssfe_info.snd_context = chunk->sinfo.sinfo_context;
ssf->ssfe_info.snd_assoc_id = chunk->sinfo.sinfo_assoc_id;
ssf->ssfe_info.snd_flags = chunk->chunk_hdr->flags;
sctp_ulpevent_set_owner(event, asoc);
ssf->ssf_assoc_id = sctp_assoc2id(asoc);
return event;
}
/* Create and initialize a SCTP_SHUTDOWN_EVENT notification.
*
* Socket Extensions for SCTP - draft-01
* 5.3.1.5 SCTP_SHUTDOWN_EVENT
*/
struct sctp_ulpevent *sctp_ulpevent_make_shutdown_event(
const struct sctp_association *asoc,
__u16 flags, gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sctp_shutdown_event *sse;
struct sk_buff *skb;
event = sctp_ulpevent_new(sizeof(struct sctp_shutdown_event),
MSG_NOTIFICATION, gfp);
if (!event)
goto fail;
skb = sctp_event2skb(event);
sse = skb_put(skb, sizeof(struct sctp_shutdown_event));
/* Socket Extensions for SCTP
* 5.3.1.5 SCTP_SHUTDOWN_EVENT
*
* sse_type
* It should be SCTP_SHUTDOWN_EVENT
*/
sse->sse_type = SCTP_SHUTDOWN_EVENT;
/* Socket Extensions for SCTP
* 5.3.1.5 SCTP_SHUTDOWN_EVENT
*
* sse_flags: 16 bits (unsigned integer)
* Currently unused.
*/
sse->sse_flags = 0;
/* Socket Extensions for SCTP
* 5.3.1.5 SCTP_SHUTDOWN_EVENT
*
* sse_length: sizeof (__u32)
* This field is the total length of the notification data, including
* the notification header.
*/
sse->sse_length = sizeof(struct sctp_shutdown_event);
/* Socket Extensions for SCTP
* 5.3.1.5 SCTP_SHUTDOWN_EVENT
*
* sse_assoc_id: sizeof (sctp_assoc_t)
* The association id field, holds the identifier for the association.
* All notifications for a given association have the same association
* identifier. For TCP style socket, this field is ignored.
*/
sctp_ulpevent_set_owner(event, asoc);
sse->sse_assoc_id = sctp_assoc2id(asoc);
return event;
fail:
return NULL;
}
/* Create and initialize a SCTP_ADAPTATION_INDICATION notification.
*
* Socket Extensions for SCTP
* 5.3.1.6 SCTP_ADAPTATION_INDICATION
*/
struct sctp_ulpevent *sctp_ulpevent_make_adaptation_indication(
const struct sctp_association *asoc, gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sctp_adaptation_event *sai;
struct sk_buff *skb;
event = sctp_ulpevent_new(sizeof(struct sctp_adaptation_event),
MSG_NOTIFICATION, gfp);
if (!event)
goto fail;
skb = sctp_event2skb(event);
sai = skb_put(skb, sizeof(struct sctp_adaptation_event));
sai->sai_type = SCTP_ADAPTATION_INDICATION;
sai->sai_flags = 0;
sai->sai_length = sizeof(struct sctp_adaptation_event);
sai->sai_adaptation_ind = asoc->peer.adaptation_ind;
sctp_ulpevent_set_owner(event, asoc);
sai->sai_assoc_id = sctp_assoc2id(asoc);
return event;
fail:
return NULL;
}
/* A message has been received. Package this message as a notification
* to pass it to the upper layers. Go ahead and calculate the sndrcvinfo
* even if filtered out later.
*
* Socket Extensions for SCTP
* 5.2.2 SCTP Header Information Structure (SCTP_SNDRCV)
*/
struct sctp_ulpevent *sctp_ulpevent_make_rcvmsg(struct sctp_association *asoc,
struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sctp_ulpevent *event = NULL;
struct sk_buff *skb = chunk->skb;
struct sock *sk = asoc->base.sk;
size_t padding, datalen;
int rx_count;
/*
* check to see if we need to make space for this
* new skb, expand the rcvbuffer if needed, or drop
* the frame
*/
if (asoc->ep->rcvbuf_policy)
rx_count = atomic_read(&asoc->rmem_alloc);
else
rx_count = atomic_read(&sk->sk_rmem_alloc);
datalen = ntohs(chunk->chunk_hdr->length);
if (rx_count >= sk->sk_rcvbuf || !sk_rmem_schedule(sk, skb, datalen))
goto fail;
/* Clone the original skb, sharing the data. */
skb = skb_clone(chunk->skb, gfp);
if (!skb)
goto fail;
/* Now that all memory allocations for this chunk succeeded, we
* can mark it as received so the tsn_map is updated correctly.
*/
if (sctp_tsnmap_mark(&asoc->peer.tsn_map,
ntohl(chunk->subh.data_hdr->tsn),
chunk->transport))
goto fail_mark;
/* First calculate the padding, so we don't inadvertently
* pass up the wrong length to the user.
*
* RFC 2960 - Section 3.2 Chunk Field Descriptions
*
* The total length of a chunk(including Type, Length and Value fields)
* MUST be a multiple of 4 bytes. If the length of the chunk is not a
* multiple of 4 bytes, the sender MUST pad the chunk with all zero
* bytes and this padding is not included in the chunk length field.
* The sender should never pad with more than 3 bytes. The receiver
* MUST ignore the padding bytes.
*/
padding = SCTP_PAD4(datalen) - datalen;
/* Fixup cloned skb with just this chunks data. */
skb_trim(skb, chunk->chunk_end - padding - skb->data);
/* Embed the event fields inside the cloned skb. */
event = sctp_skb2event(skb);
/* Initialize event with flags 0 and correct length
* Since this is a clone of the original skb, only account for
* the data of this chunk as other chunks will be accounted separately.
*/
sctp_ulpevent_init(event, 0, skb->len + sizeof(struct sk_buff));
/* And hold the chunk as we need it for getting the IP headers
* later in recvmsg
*/
sctp_chunk_hold(chunk);
event->chunk = chunk;
sctp_ulpevent_receive_data(event, asoc);
event->stream = ntohs(chunk->subh.data_hdr->stream);
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
event->flags |= SCTP_UNORDERED;
event->cumtsn = sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map);
}
event->tsn = ntohl(chunk->subh.data_hdr->tsn);
event->msg_flags |= chunk->chunk_hdr->flags;
return event;
fail_mark:
kfree_skb(skb);
fail:
return NULL;
}
/* Create a partial delivery related event.
*
* 5.3.1.7 SCTP_PARTIAL_DELIVERY_EVENT
*
* When a receiver is engaged in a partial delivery of a
* message this notification will be used to indicate
* various events.
*/
struct sctp_ulpevent *sctp_ulpevent_make_pdapi(
const struct sctp_association *asoc,
__u32 indication, __u32 sid, __u32 seq,
__u32 flags, gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sctp_pdapi_event *pd;
struct sk_buff *skb;
event = sctp_ulpevent_new(sizeof(struct sctp_pdapi_event),
MSG_NOTIFICATION, gfp);
if (!event)
goto fail;
skb = sctp_event2skb(event);
pd = skb_put(skb, sizeof(struct sctp_pdapi_event));
/* pdapi_type
* It should be SCTP_PARTIAL_DELIVERY_EVENT
*
* pdapi_flags: 16 bits (unsigned integer)
* Currently unused.
*/
pd->pdapi_type = SCTP_PARTIAL_DELIVERY_EVENT;
pd->pdapi_flags = flags;
pd->pdapi_stream = sid;
pd->pdapi_seq = seq;
/* pdapi_length: 32 bits (unsigned integer)
*
* This field is the total length of the notification data, including
* the notification header. It will generally be sizeof (struct
* sctp_pdapi_event).
*/
pd->pdapi_length = sizeof(struct sctp_pdapi_event);
/* pdapi_indication: 32 bits (unsigned integer)
*
* This field holds the indication being sent to the application.
*/
pd->pdapi_indication = indication;
/* pdapi_assoc_id: sizeof (sctp_assoc_t)
*
* The association id field, holds the identifier for the association.
*/
sctp_ulpevent_set_owner(event, asoc);
pd->pdapi_assoc_id = sctp_assoc2id(asoc);
return event;
fail:
return NULL;
}
struct sctp_ulpevent *sctp_ulpevent_make_authkey(
const struct sctp_association *asoc, __u16 key_id,
__u32 indication, gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sctp_authkey_event *ak;
struct sk_buff *skb;
event = sctp_ulpevent_new(sizeof(struct sctp_authkey_event),
MSG_NOTIFICATION, gfp);
if (!event)
goto fail;
skb = sctp_event2skb(event);
ak = skb_put(skb, sizeof(struct sctp_authkey_event));
ak->auth_type = SCTP_AUTHENTICATION_EVENT;
ak->auth_flags = 0;
ak->auth_length = sizeof(struct sctp_authkey_event);
ak->auth_keynumber = key_id;
ak->auth_altkeynumber = 0;
ak->auth_indication = indication;
/*
* The association id field, holds the identifier for the association.
*/
sctp_ulpevent_set_owner(event, asoc);
ak->auth_assoc_id = sctp_assoc2id(asoc);
return event;
fail:
return NULL;
}
/*
* Socket Extensions for SCTP
* 6.3.10. SCTP_SENDER_DRY_EVENT
*/
struct sctp_ulpevent *sctp_ulpevent_make_sender_dry_event(
const struct sctp_association *asoc, gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sctp_sender_dry_event *sdry;
struct sk_buff *skb;
event = sctp_ulpevent_new(sizeof(struct sctp_sender_dry_event),
MSG_NOTIFICATION, gfp);
if (!event)
return NULL;
skb = sctp_event2skb(event);
sdry = skb_put(skb, sizeof(struct sctp_sender_dry_event));
sdry->sender_dry_type = SCTP_SENDER_DRY_EVENT;
sdry->sender_dry_flags = 0;
sdry->sender_dry_length = sizeof(struct sctp_sender_dry_event);
sctp_ulpevent_set_owner(event, asoc);
sdry->sender_dry_assoc_id = sctp_assoc2id(asoc);
return event;
}
struct sctp_ulpevent *sctp_ulpevent_make_stream_reset_event(
const struct sctp_association *asoc, __u16 flags, __u16 stream_num,
__be16 *stream_list, gfp_t gfp)
{
struct sctp_stream_reset_event *sreset;
struct sctp_ulpevent *event;
struct sk_buff *skb;
int length, i;
length = sizeof(struct sctp_stream_reset_event) + 2 * stream_num;
event = sctp_ulpevent_new(length, MSG_NOTIFICATION, gfp);
if (!event)
return NULL;
skb = sctp_event2skb(event);
sreset = skb_put(skb, length);
sreset->strreset_type = SCTP_STREAM_RESET_EVENT;
sreset->strreset_flags = flags;
sreset->strreset_length = length;
sctp_ulpevent_set_owner(event, asoc);
sreset->strreset_assoc_id = sctp_assoc2id(asoc);
for (i = 0; i < stream_num; i++)
sreset->strreset_stream_list[i] = ntohs(stream_list[i]);
return event;
}
struct sctp_ulpevent *sctp_ulpevent_make_assoc_reset_event(
const struct sctp_association *asoc, __u16 flags, __u32 local_tsn,
__u32 remote_tsn, gfp_t gfp)
{
struct sctp_assoc_reset_event *areset;
struct sctp_ulpevent *event;
struct sk_buff *skb;
event = sctp_ulpevent_new(sizeof(struct sctp_assoc_reset_event),
MSG_NOTIFICATION, gfp);
if (!event)
return NULL;
skb = sctp_event2skb(event);
areset = skb_put(skb, sizeof(struct sctp_assoc_reset_event));
areset->assocreset_type = SCTP_ASSOC_RESET_EVENT;
areset->assocreset_flags = flags;
areset->assocreset_length = sizeof(struct sctp_assoc_reset_event);
sctp_ulpevent_set_owner(event, asoc);
areset->assocreset_assoc_id = sctp_assoc2id(asoc);
areset->assocreset_local_tsn = local_tsn;
areset->assocreset_remote_tsn = remote_tsn;
return event;
}
struct sctp_ulpevent *sctp_ulpevent_make_stream_change_event(
const struct sctp_association *asoc, __u16 flags,
__u32 strchange_instrms, __u32 strchange_outstrms, gfp_t gfp)
{
struct sctp_stream_change_event *schange;
struct sctp_ulpevent *event;
struct sk_buff *skb;
event = sctp_ulpevent_new(sizeof(struct sctp_stream_change_event),
MSG_NOTIFICATION, gfp);
if (!event)
return NULL;
skb = sctp_event2skb(event);
schange = skb_put(skb, sizeof(struct sctp_stream_change_event));
schange->strchange_type = SCTP_STREAM_CHANGE_EVENT;
schange->strchange_flags = flags;
schange->strchange_length = sizeof(struct sctp_stream_change_event);
sctp_ulpevent_set_owner(event, asoc);
schange->strchange_assoc_id = sctp_assoc2id(asoc);
schange->strchange_instrms = strchange_instrms;
schange->strchange_outstrms = strchange_outstrms;
return event;
}
/* Return the notification type, assuming this is a notification
* event.
*/
__u16 sctp_ulpevent_get_notification_type(const struct sctp_ulpevent *event)
{
union sctp_notification *notification;
struct sk_buff *skb;
skb = sctp_event2skb(event);
notification = (union sctp_notification *) skb->data;
return notification->sn_header.sn_type;
}
/* RFC6458, Section 5.3.2. SCTP Header Information Structure
* (SCTP_SNDRCV, DEPRECATED)
*/
void sctp_ulpevent_read_sndrcvinfo(const struct sctp_ulpevent *event,
struct msghdr *msghdr)
{
struct sctp_sndrcvinfo sinfo;
if (sctp_ulpevent_is_notification(event))
return;
memset(&sinfo, 0, sizeof(sinfo));
sinfo.sinfo_stream = event->stream;
sinfo.sinfo_ssn = event->ssn;
sinfo.sinfo_ppid = event->ppid;
sinfo.sinfo_flags = event->flags;
sinfo.sinfo_tsn = event->tsn;
sinfo.sinfo_cumtsn = event->cumtsn;
sinfo.sinfo_assoc_id = sctp_assoc2id(event->asoc);
/* Context value that is set via SCTP_CONTEXT socket option. */
sinfo.sinfo_context = event->asoc->default_rcv_context;
/* These fields are not used while receiving. */
sinfo.sinfo_timetolive = 0;
put_cmsg(msghdr, IPPROTO_SCTP, SCTP_SNDRCV,
sizeof(sinfo), &sinfo);
}
/* RFC6458, Section 5.3.5 SCTP Receive Information Structure
* (SCTP_SNDRCV)
*/
void sctp_ulpevent_read_rcvinfo(const struct sctp_ulpevent *event,
struct msghdr *msghdr)
{
struct sctp_rcvinfo rinfo;
if (sctp_ulpevent_is_notification(event))
return;
memset(&rinfo, 0, sizeof(struct sctp_rcvinfo));
rinfo.rcv_sid = event->stream;
rinfo.rcv_ssn = event->ssn;
rinfo.rcv_ppid = event->ppid;
rinfo.rcv_flags = event->flags;
rinfo.rcv_tsn = event->tsn;
rinfo.rcv_cumtsn = event->cumtsn;
rinfo.rcv_assoc_id = sctp_assoc2id(event->asoc);
rinfo.rcv_context = event->asoc->default_rcv_context;
put_cmsg(msghdr, IPPROTO_SCTP, SCTP_RCVINFO,
sizeof(rinfo), &rinfo);
}
/* RFC6458, Section 5.3.6. SCTP Next Receive Information Structure
* (SCTP_NXTINFO)
*/
static void __sctp_ulpevent_read_nxtinfo(const struct sctp_ulpevent *event,
struct msghdr *msghdr,
const struct sk_buff *skb)
{
struct sctp_nxtinfo nxtinfo;
memset(&nxtinfo, 0, sizeof(nxtinfo));
nxtinfo.nxt_sid = event->stream;
nxtinfo.nxt_ppid = event->ppid;
nxtinfo.nxt_flags = event->flags;
if (sctp_ulpevent_is_notification(event))
nxtinfo.nxt_flags |= SCTP_NOTIFICATION;
nxtinfo.nxt_length = skb->len;
nxtinfo.nxt_assoc_id = sctp_assoc2id(event->asoc);
put_cmsg(msghdr, IPPROTO_SCTP, SCTP_NXTINFO,
sizeof(nxtinfo), &nxtinfo);
}
void sctp_ulpevent_read_nxtinfo(const struct sctp_ulpevent *event,
struct msghdr *msghdr,
struct sock *sk)
{
struct sk_buff *skb;
int err;
skb = sctp_skb_recv_datagram(sk, MSG_PEEK | MSG_DONTWAIT, &err);
if (skb != NULL) {
__sctp_ulpevent_read_nxtinfo(sctp_skb2event(skb),
msghdr, skb);
/* Just release refcount here. */
kfree_skb(skb);
}
}
/* Do accounting for bytes received and hold a reference to the association
* for each skb.
*/
static void sctp_ulpevent_receive_data(struct sctp_ulpevent *event,
struct sctp_association *asoc)
{
struct sk_buff *skb, *frag;
skb = sctp_event2skb(event);
/* Set the owner and charge rwnd for bytes received. */
sctp_ulpevent_set_owner(event, asoc);
sctp_assoc_rwnd_decrease(asoc, skb_headlen(skb));
if (!skb->data_len)
return;
/* Note: Not clearing the entire event struct as this is just a
* fragment of the real event. However, we still need to do rwnd
* accounting.
* In general, the skb passed from IP can have only 1 level of
* fragments. But we allow multiple levels of fragments.
*/
skb_walk_frags(skb, frag)
sctp_ulpevent_receive_data(sctp_skb2event(frag), asoc);
}
/* Do accounting for bytes just read by user and release the references to
* the association.
*/
static void sctp_ulpevent_release_data(struct sctp_ulpevent *event)
{
struct sk_buff *skb, *frag;
unsigned int len;
/* Current stack structures assume that the rcv buffer is
* per socket. For UDP style sockets this is not true as
* multiple associations may be on a single UDP-style socket.
* Use the local private area of the skb to track the owning
* association.
*/
skb = sctp_event2skb(event);
len = skb->len;
if (!skb->data_len)
goto done;
/* Don't forget the fragments. */
skb_walk_frags(skb, frag) {
/* NOTE: skb_shinfos are recursive. Although IP returns
* skb's with only 1 level of fragments, SCTP reassembly can
* increase the levels.
*/
sctp_ulpevent_release_frag_data(sctp_skb2event(frag));
}
done:
sctp_assoc_rwnd_increase(event->asoc, len);
sctp_chunk_put(event->chunk);
sctp_ulpevent_release_owner(event);
}
static void sctp_ulpevent_release_frag_data(struct sctp_ulpevent *event)
{
struct sk_buff *skb, *frag;
skb = sctp_event2skb(event);
if (!skb->data_len)
goto done;
/* Don't forget the fragments. */
skb_walk_frags(skb, frag) {
/* NOTE: skb_shinfos are recursive. Although IP returns
* skb's with only 1 level of fragments, SCTP reassembly can
* increase the levels.
*/
sctp_ulpevent_release_frag_data(sctp_skb2event(frag));
}
done:
sctp_chunk_put(event->chunk);
sctp_ulpevent_release_owner(event);
}
/* Free a ulpevent that has an owner. It includes releasing the reference
* to the owner, updating the rwnd in case of a DATA event and freeing the
* skb.
*/
void sctp_ulpevent_free(struct sctp_ulpevent *event)
{
if (sctp_ulpevent_is_notification(event))
sctp_ulpevent_release_owner(event);
else
sctp_ulpevent_release_data(event);
kfree_skb(sctp_event2skb(event));
}
/* Purge the skb lists holding ulpevents. */
unsigned int sctp_queue_purge_ulpevents(struct sk_buff_head *list)
{
struct sk_buff *skb;
unsigned int data_unread = 0;
while ((skb = skb_dequeue(list)) != NULL) {
struct sctp_ulpevent *event = sctp_skb2event(skb);
if (!sctp_ulpevent_is_notification(event))
data_unread += skb->len;
sctp_ulpevent_free(event);
}
return data_unread;
}
| linux-master | net/sctp/ulpevent.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright Red Hat Inc. 2017
*
* This file is part of the SCTP kernel implementation
*
* These functions manipulate sctp stream queue/scheduling.
*
* Please send any bug reports or fixes you make to the
* email addresched(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Marcelo Ricardo Leitner <[email protected]>
*/
#include <linux/list.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/stream_sched.h>
/* Priority handling
* RFC DRAFT ndata section 3.2
*/
static void sctp_sched_rr_unsched_all(struct sctp_stream *stream);
static void sctp_sched_rr_next_stream(struct sctp_stream *stream)
{
struct list_head *pos;
pos = stream->rr_next->rr_list.next;
if (pos == &stream->rr_list)
pos = pos->next;
stream->rr_next = list_entry(pos, struct sctp_stream_out_ext, rr_list);
}
static void sctp_sched_rr_unsched(struct sctp_stream *stream,
struct sctp_stream_out_ext *soute)
{
if (stream->rr_next == soute)
/* Try to move to the next stream */
sctp_sched_rr_next_stream(stream);
list_del_init(&soute->rr_list);
/* If we have no other stream queued, clear next */
if (list_empty(&stream->rr_list))
stream->rr_next = NULL;
}
static void sctp_sched_rr_sched(struct sctp_stream *stream,
struct sctp_stream_out_ext *soute)
{
if (!list_empty(&soute->rr_list))
/* Already scheduled. */
return;
/* Schedule the stream */
list_add_tail(&soute->rr_list, &stream->rr_list);
if (!stream->rr_next)
stream->rr_next = soute;
}
static int sctp_sched_rr_set(struct sctp_stream *stream, __u16 sid,
__u16 prio, gfp_t gfp)
{
return 0;
}
static int sctp_sched_rr_get(struct sctp_stream *stream, __u16 sid,
__u16 *value)
{
return 0;
}
static int sctp_sched_rr_init(struct sctp_stream *stream)
{
INIT_LIST_HEAD(&stream->rr_list);
stream->rr_next = NULL;
return 0;
}
static int sctp_sched_rr_init_sid(struct sctp_stream *stream, __u16 sid,
gfp_t gfp)
{
INIT_LIST_HEAD(&SCTP_SO(stream, sid)->ext->rr_list);
return 0;
}
static void sctp_sched_rr_free_sid(struct sctp_stream *stream, __u16 sid)
{
}
static void sctp_sched_rr_enqueue(struct sctp_outq *q,
struct sctp_datamsg *msg)
{
struct sctp_stream *stream;
struct sctp_chunk *ch;
__u16 sid;
ch = list_first_entry(&msg->chunks, struct sctp_chunk, frag_list);
sid = sctp_chunk_stream_no(ch);
stream = &q->asoc->stream;
sctp_sched_rr_sched(stream, SCTP_SO(stream, sid)->ext);
}
static struct sctp_chunk *sctp_sched_rr_dequeue(struct sctp_outq *q)
{
struct sctp_stream *stream = &q->asoc->stream;
struct sctp_stream_out_ext *soute;
struct sctp_chunk *ch = NULL;
/* Bail out quickly if queue is empty */
if (list_empty(&q->out_chunk_list))
goto out;
/* Find which chunk is next */
if (stream->out_curr)
soute = stream->out_curr->ext;
else
soute = stream->rr_next;
ch = list_entry(soute->outq.next, struct sctp_chunk, stream_list);
sctp_sched_dequeue_common(q, ch);
out:
return ch;
}
static void sctp_sched_rr_dequeue_done(struct sctp_outq *q,
struct sctp_chunk *ch)
{
struct sctp_stream_out_ext *soute;
__u16 sid;
/* Last chunk on that msg, move to the next stream */
sid = sctp_chunk_stream_no(ch);
soute = SCTP_SO(&q->asoc->stream, sid)->ext;
sctp_sched_rr_next_stream(&q->asoc->stream);
if (list_empty(&soute->outq))
sctp_sched_rr_unsched(&q->asoc->stream, soute);
}
static void sctp_sched_rr_sched_all(struct sctp_stream *stream)
{
struct sctp_association *asoc;
struct sctp_stream_out_ext *soute;
struct sctp_chunk *ch;
asoc = container_of(stream, struct sctp_association, stream);
list_for_each_entry(ch, &asoc->outqueue.out_chunk_list, list) {
__u16 sid;
sid = sctp_chunk_stream_no(ch);
soute = SCTP_SO(stream, sid)->ext;
if (soute)
sctp_sched_rr_sched(stream, soute);
}
}
static void sctp_sched_rr_unsched_all(struct sctp_stream *stream)
{
struct sctp_stream_out_ext *soute, *tmp;
list_for_each_entry_safe(soute, tmp, &stream->rr_list, rr_list)
sctp_sched_rr_unsched(stream, soute);
}
static struct sctp_sched_ops sctp_sched_rr = {
.set = sctp_sched_rr_set,
.get = sctp_sched_rr_get,
.init = sctp_sched_rr_init,
.init_sid = sctp_sched_rr_init_sid,
.free_sid = sctp_sched_rr_free_sid,
.enqueue = sctp_sched_rr_enqueue,
.dequeue = sctp_sched_rr_dequeue,
.dequeue_done = sctp_sched_rr_dequeue_done,
.sched_all = sctp_sched_rr_sched_all,
.unsched_all = sctp_sched_rr_unsched_all,
};
void sctp_sched_ops_rr_init(void)
{
sctp_sched_ops_register(SCTP_SS_RR, &sctp_sched_rr);
}
| linux-master | net/sctp/stream_sched_rr.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2003 International Business Machines Corp.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This file is part of the SCTP kernel implementation
*
* This module provides the abstraction for an SCTP transport representing
* a remote transport address. For local transport addresses, we just use
* union sctp_addr.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Jon Grimm <[email protected]>
* Xingang Guo <[email protected]>
* Hui Huang <[email protected]>
* Sridhar Samudrala <[email protected]>
* Ardelle Fan <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/random.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
/* 1st Level Abstractions. */
/* Initialize a new transport from provided memory. */
static struct sctp_transport *sctp_transport_init(struct net *net,
struct sctp_transport *peer,
const union sctp_addr *addr,
gfp_t gfp)
{
/* Copy in the address. */
peer->af_specific = sctp_get_af_specific(addr->sa.sa_family);
memcpy(&peer->ipaddr, addr, peer->af_specific->sockaddr_len);
memset(&peer->saddr, 0, sizeof(union sctp_addr));
peer->sack_generation = 0;
/* From 6.3.1 RTO Calculation:
*
* C1) Until an RTT measurement has been made for a packet sent to the
* given destination transport address, set RTO to the protocol
* parameter 'RTO.Initial'.
*/
peer->rto = msecs_to_jiffies(net->sctp.rto_initial);
peer->last_time_heard = 0;
peer->last_time_ecne_reduced = jiffies;
peer->param_flags = SPP_HB_DISABLE |
SPP_PMTUD_ENABLE |
SPP_SACKDELAY_ENABLE;
/* Initialize the default path max_retrans. */
peer->pathmaxrxt = net->sctp.max_retrans_path;
peer->pf_retrans = net->sctp.pf_retrans;
INIT_LIST_HEAD(&peer->transmitted);
INIT_LIST_HEAD(&peer->send_ready);
INIT_LIST_HEAD(&peer->transports);
timer_setup(&peer->T3_rtx_timer, sctp_generate_t3_rtx_event, 0);
timer_setup(&peer->hb_timer, sctp_generate_heartbeat_event, 0);
timer_setup(&peer->reconf_timer, sctp_generate_reconf_event, 0);
timer_setup(&peer->probe_timer, sctp_generate_probe_event, 0);
timer_setup(&peer->proto_unreach_timer,
sctp_generate_proto_unreach_event, 0);
/* Initialize the 64-bit random nonce sent with heartbeat. */
get_random_bytes(&peer->hb_nonce, sizeof(peer->hb_nonce));
refcount_set(&peer->refcnt, 1);
return peer;
}
/* Allocate and initialize a new transport. */
struct sctp_transport *sctp_transport_new(struct net *net,
const union sctp_addr *addr,
gfp_t gfp)
{
struct sctp_transport *transport;
transport = kzalloc(sizeof(*transport), gfp);
if (!transport)
goto fail;
if (!sctp_transport_init(net, transport, addr, gfp))
goto fail_init;
SCTP_DBG_OBJCNT_INC(transport);
return transport;
fail_init:
kfree(transport);
fail:
return NULL;
}
/* This transport is no longer needed. Free up if possible, or
* delay until it last reference count.
*/
void sctp_transport_free(struct sctp_transport *transport)
{
/* Try to delete the heartbeat timer. */
if (del_timer(&transport->hb_timer))
sctp_transport_put(transport);
/* Delete the T3_rtx timer if it's active.
* There is no point in not doing this now and letting
* structure hang around in memory since we know
* the transport is going away.
*/
if (del_timer(&transport->T3_rtx_timer))
sctp_transport_put(transport);
if (del_timer(&transport->reconf_timer))
sctp_transport_put(transport);
if (del_timer(&transport->probe_timer))
sctp_transport_put(transport);
/* Delete the ICMP proto unreachable timer if it's active. */
if (del_timer(&transport->proto_unreach_timer))
sctp_transport_put(transport);
sctp_transport_put(transport);
}
static void sctp_transport_destroy_rcu(struct rcu_head *head)
{
struct sctp_transport *transport;
transport = container_of(head, struct sctp_transport, rcu);
dst_release(transport->dst);
kfree(transport);
SCTP_DBG_OBJCNT_DEC(transport);
}
/* Destroy the transport data structure.
* Assumes there are no more users of this structure.
*/
static void sctp_transport_destroy(struct sctp_transport *transport)
{
if (unlikely(refcount_read(&transport->refcnt))) {
WARN(1, "Attempt to destroy undead transport %p!\n", transport);
return;
}
sctp_packet_free(&transport->packet);
if (transport->asoc)
sctp_association_put(transport->asoc);
call_rcu(&transport->rcu, sctp_transport_destroy_rcu);
}
/* Start T3_rtx timer if it is not already running and update the heartbeat
* timer. This routine is called every time a DATA chunk is sent.
*/
void sctp_transport_reset_t3_rtx(struct sctp_transport *transport)
{
/* RFC 2960 6.3.2 Retransmission Timer Rules
*
* R1) Every time a DATA chunk is sent to any address(including a
* retransmission), if the T3-rtx timer of that address is not running
* start it running so that it will expire after the RTO of that
* address.
*/
if (!timer_pending(&transport->T3_rtx_timer))
if (!mod_timer(&transport->T3_rtx_timer,
jiffies + transport->rto))
sctp_transport_hold(transport);
}
void sctp_transport_reset_hb_timer(struct sctp_transport *transport)
{
unsigned long expires;
/* When a data chunk is sent, reset the heartbeat interval. */
expires = jiffies + sctp_transport_timeout(transport);
if (!mod_timer(&transport->hb_timer,
expires + get_random_u32_below(transport->rto)))
sctp_transport_hold(transport);
}
void sctp_transport_reset_reconf_timer(struct sctp_transport *transport)
{
if (!timer_pending(&transport->reconf_timer))
if (!mod_timer(&transport->reconf_timer,
jiffies + transport->rto))
sctp_transport_hold(transport);
}
void sctp_transport_reset_probe_timer(struct sctp_transport *transport)
{
if (!mod_timer(&transport->probe_timer,
jiffies + transport->probe_interval))
sctp_transport_hold(transport);
}
void sctp_transport_reset_raise_timer(struct sctp_transport *transport)
{
if (!mod_timer(&transport->probe_timer,
jiffies + transport->probe_interval * 30))
sctp_transport_hold(transport);
}
/* This transport has been assigned to an association.
* Initialize fields from the association or from the sock itself.
* Register the reference count in the association.
*/
void sctp_transport_set_owner(struct sctp_transport *transport,
struct sctp_association *asoc)
{
transport->asoc = asoc;
sctp_association_hold(asoc);
}
/* Initialize the pmtu of a transport. */
void sctp_transport_pmtu(struct sctp_transport *transport, struct sock *sk)
{
/* If we don't have a fresh route, look one up */
if (!transport->dst || transport->dst->obsolete) {
sctp_transport_dst_release(transport);
transport->af_specific->get_dst(transport, &transport->saddr,
&transport->fl, sk);
}
if (transport->param_flags & SPP_PMTUD_DISABLE) {
struct sctp_association *asoc = transport->asoc;
if (!transport->pathmtu && asoc && asoc->pathmtu)
transport->pathmtu = asoc->pathmtu;
if (transport->pathmtu)
return;
}
if (transport->dst)
transport->pathmtu = sctp_dst_mtu(transport->dst);
else
transport->pathmtu = SCTP_DEFAULT_MAXSEGMENT;
sctp_transport_pl_update(transport);
}
void sctp_transport_pl_send(struct sctp_transport *t)
{
if (t->pl.probe_count < SCTP_MAX_PROBES)
goto out;
t->pl.probe_count = 0;
if (t->pl.state == SCTP_PL_BASE) {
if (t->pl.probe_size == SCTP_BASE_PLPMTU) { /* BASE_PLPMTU Confirmation Failed */
t->pl.state = SCTP_PL_ERROR; /* Base -> Error */
t->pl.pmtu = SCTP_BASE_PLPMTU;
t->pathmtu = t->pl.pmtu + sctp_transport_pl_hlen(t);
sctp_assoc_sync_pmtu(t->asoc);
}
} else if (t->pl.state == SCTP_PL_SEARCH) {
if (t->pl.pmtu == t->pl.probe_size) { /* Black Hole Detected */
t->pl.state = SCTP_PL_BASE; /* Search -> Base */
t->pl.probe_size = SCTP_BASE_PLPMTU;
t->pl.probe_high = 0;
t->pl.pmtu = SCTP_BASE_PLPMTU;
t->pathmtu = t->pl.pmtu + sctp_transport_pl_hlen(t);
sctp_assoc_sync_pmtu(t->asoc);
} else { /* Normal probe failure. */
t->pl.probe_high = t->pl.probe_size;
t->pl.probe_size = t->pl.pmtu;
}
} else if (t->pl.state == SCTP_PL_COMPLETE) {
if (t->pl.pmtu == t->pl.probe_size) { /* Black Hole Detected */
t->pl.state = SCTP_PL_BASE; /* Search Complete -> Base */
t->pl.probe_size = SCTP_BASE_PLPMTU;
t->pl.pmtu = SCTP_BASE_PLPMTU;
t->pathmtu = t->pl.pmtu + sctp_transport_pl_hlen(t);
sctp_assoc_sync_pmtu(t->asoc);
}
}
out:
pr_debug("%s: PLPMTUD: transport: %p, state: %d, pmtu: %d, size: %d, high: %d\n",
__func__, t, t->pl.state, t->pl.pmtu, t->pl.probe_size, t->pl.probe_high);
t->pl.probe_count++;
}
bool sctp_transport_pl_recv(struct sctp_transport *t)
{
pr_debug("%s: PLPMTUD: transport: %p, state: %d, pmtu: %d, size: %d, high: %d\n",
__func__, t, t->pl.state, t->pl.pmtu, t->pl.probe_size, t->pl.probe_high);
t->pl.pmtu = t->pl.probe_size;
t->pl.probe_count = 0;
if (t->pl.state == SCTP_PL_BASE) {
t->pl.state = SCTP_PL_SEARCH; /* Base -> Search */
t->pl.probe_size += SCTP_PL_BIG_STEP;
} else if (t->pl.state == SCTP_PL_ERROR) {
t->pl.state = SCTP_PL_SEARCH; /* Error -> Search */
t->pl.pmtu = t->pl.probe_size;
t->pathmtu = t->pl.pmtu + sctp_transport_pl_hlen(t);
sctp_assoc_sync_pmtu(t->asoc);
t->pl.probe_size += SCTP_PL_BIG_STEP;
} else if (t->pl.state == SCTP_PL_SEARCH) {
if (!t->pl.probe_high) {
if (t->pl.probe_size < SCTP_MAX_PLPMTU) {
t->pl.probe_size = min(t->pl.probe_size + SCTP_PL_BIG_STEP,
SCTP_MAX_PLPMTU);
return false;
}
t->pl.probe_high = SCTP_MAX_PLPMTU;
}
t->pl.probe_size += SCTP_PL_MIN_STEP;
if (t->pl.probe_size >= t->pl.probe_high) {
t->pl.probe_high = 0;
t->pl.state = SCTP_PL_COMPLETE; /* Search -> Search Complete */
t->pl.probe_size = t->pl.pmtu;
t->pathmtu = t->pl.pmtu + sctp_transport_pl_hlen(t);
sctp_assoc_sync_pmtu(t->asoc);
sctp_transport_reset_raise_timer(t);
}
} else if (t->pl.state == SCTP_PL_COMPLETE) {
/* Raise probe_size again after 30 * interval in Search Complete */
t->pl.state = SCTP_PL_SEARCH; /* Search Complete -> Search */
t->pl.probe_size = min(t->pl.probe_size + SCTP_PL_MIN_STEP, SCTP_MAX_PLPMTU);
}
return t->pl.state == SCTP_PL_COMPLETE;
}
static bool sctp_transport_pl_toobig(struct sctp_transport *t, u32 pmtu)
{
pr_debug("%s: PLPMTUD: transport: %p, state: %d, pmtu: %d, size: %d, ptb: %d\n",
__func__, t, t->pl.state, t->pl.pmtu, t->pl.probe_size, pmtu);
if (pmtu < SCTP_MIN_PLPMTU || pmtu >= t->pl.probe_size)
return false;
if (t->pl.state == SCTP_PL_BASE) {
if (pmtu >= SCTP_MIN_PLPMTU && pmtu < SCTP_BASE_PLPMTU) {
t->pl.state = SCTP_PL_ERROR; /* Base -> Error */
t->pl.pmtu = SCTP_BASE_PLPMTU;
t->pathmtu = t->pl.pmtu + sctp_transport_pl_hlen(t);
return true;
}
} else if (t->pl.state == SCTP_PL_SEARCH) {
if (pmtu >= SCTP_BASE_PLPMTU && pmtu < t->pl.pmtu) {
t->pl.state = SCTP_PL_BASE; /* Search -> Base */
t->pl.probe_size = SCTP_BASE_PLPMTU;
t->pl.probe_count = 0;
t->pl.probe_high = 0;
t->pl.pmtu = SCTP_BASE_PLPMTU;
t->pathmtu = t->pl.pmtu + sctp_transport_pl_hlen(t);
return true;
} else if (pmtu > t->pl.pmtu && pmtu < t->pl.probe_size) {
t->pl.probe_size = pmtu;
t->pl.probe_count = 0;
}
} else if (t->pl.state == SCTP_PL_COMPLETE) {
if (pmtu >= SCTP_BASE_PLPMTU && pmtu < t->pl.pmtu) {
t->pl.state = SCTP_PL_BASE; /* Complete -> Base */
t->pl.probe_size = SCTP_BASE_PLPMTU;
t->pl.probe_count = 0;
t->pl.probe_high = 0;
t->pl.pmtu = SCTP_BASE_PLPMTU;
t->pathmtu = t->pl.pmtu + sctp_transport_pl_hlen(t);
sctp_transport_reset_probe_timer(t);
return true;
}
}
return false;
}
bool sctp_transport_update_pmtu(struct sctp_transport *t, u32 pmtu)
{
struct sock *sk = t->asoc->base.sk;
struct dst_entry *dst;
bool change = true;
if (unlikely(pmtu < SCTP_DEFAULT_MINSEGMENT)) {
pr_warn_ratelimited("%s: Reported pmtu %d too low, using default minimum of %d\n",
__func__, pmtu, SCTP_DEFAULT_MINSEGMENT);
/* Use default minimum segment instead */
pmtu = SCTP_DEFAULT_MINSEGMENT;
}
pmtu = SCTP_TRUNC4(pmtu);
if (sctp_transport_pl_enabled(t))
return sctp_transport_pl_toobig(t, pmtu - sctp_transport_pl_hlen(t));
dst = sctp_transport_dst_check(t);
if (dst) {
struct sctp_pf *pf = sctp_get_pf_specific(dst->ops->family);
union sctp_addr addr;
pf->af->from_sk(&addr, sk);
pf->to_sk_daddr(&t->ipaddr, sk);
dst->ops->update_pmtu(dst, sk, NULL, pmtu, true);
pf->to_sk_daddr(&addr, sk);
dst = sctp_transport_dst_check(t);
}
if (!dst) {
t->af_specific->get_dst(t, &t->saddr, &t->fl, sk);
dst = t->dst;
}
if (dst) {
/* Re-fetch, as under layers may have a higher minimum size */
pmtu = sctp_dst_mtu(dst);
change = t->pathmtu != pmtu;
}
t->pathmtu = pmtu;
return change;
}
/* Caches the dst entry and source address for a transport's destination
* address.
*/
void sctp_transport_route(struct sctp_transport *transport,
union sctp_addr *saddr, struct sctp_sock *opt)
{
struct sctp_association *asoc = transport->asoc;
struct sctp_af *af = transport->af_specific;
sctp_transport_dst_release(transport);
af->get_dst(transport, saddr, &transport->fl, sctp_opt2sk(opt));
if (saddr)
memcpy(&transport->saddr, saddr, sizeof(union sctp_addr));
else
af->get_saddr(opt, transport, &transport->fl);
sctp_transport_pmtu(transport, sctp_opt2sk(opt));
/* Initialize sk->sk_rcv_saddr, if the transport is the
* association's active path for getsockname().
*/
if (transport->dst && asoc &&
(!asoc->peer.primary_path || transport == asoc->peer.active_path))
opt->pf->to_sk_saddr(&transport->saddr, asoc->base.sk);
}
/* Hold a reference to a transport. */
int sctp_transport_hold(struct sctp_transport *transport)
{
return refcount_inc_not_zero(&transport->refcnt);
}
/* Release a reference to a transport and clean up
* if there are no more references.
*/
void sctp_transport_put(struct sctp_transport *transport)
{
if (refcount_dec_and_test(&transport->refcnt))
sctp_transport_destroy(transport);
}
/* Update transport's RTO based on the newly calculated RTT. */
void sctp_transport_update_rto(struct sctp_transport *tp, __u32 rtt)
{
if (unlikely(!tp->rto_pending))
/* We should not be doing any RTO updates unless rto_pending is set. */
pr_debug("%s: rto_pending not set on transport %p!\n", __func__, tp);
if (tp->rttvar || tp->srtt) {
struct net *net = tp->asoc->base.net;
/* 6.3.1 C3) When a new RTT measurement R' is made, set
* RTTVAR <- (1 - RTO.Beta) * RTTVAR + RTO.Beta * |SRTT - R'|
* SRTT <- (1 - RTO.Alpha) * SRTT + RTO.Alpha * R'
*/
/* Note: The above algorithm has been rewritten to
* express rto_beta and rto_alpha as inverse powers
* of two.
* For example, assuming the default value of RTO.Alpha of
* 1/8, rto_alpha would be expressed as 3.
*/
tp->rttvar = tp->rttvar - (tp->rttvar >> net->sctp.rto_beta)
+ (((__u32)abs((__s64)tp->srtt - (__s64)rtt)) >> net->sctp.rto_beta);
tp->srtt = tp->srtt - (tp->srtt >> net->sctp.rto_alpha)
+ (rtt >> net->sctp.rto_alpha);
} else {
/* 6.3.1 C2) When the first RTT measurement R is made, set
* SRTT <- R, RTTVAR <- R/2.
*/
tp->srtt = rtt;
tp->rttvar = rtt >> 1;
}
/* 6.3.1 G1) Whenever RTTVAR is computed, if RTTVAR = 0, then
* adjust RTTVAR <- G, where G is the CLOCK GRANULARITY.
*/
if (tp->rttvar == 0)
tp->rttvar = SCTP_CLOCK_GRANULARITY;
/* 6.3.1 C3) After the computation, update RTO <- SRTT + 4 * RTTVAR. */
tp->rto = tp->srtt + (tp->rttvar << 2);
/* 6.3.1 C6) Whenever RTO is computed, if it is less than RTO.Min
* seconds then it is rounded up to RTO.Min seconds.
*/
if (tp->rto < tp->asoc->rto_min)
tp->rto = tp->asoc->rto_min;
/* 6.3.1 C7) A maximum value may be placed on RTO provided it is
* at least RTO.max seconds.
*/
if (tp->rto > tp->asoc->rto_max)
tp->rto = tp->asoc->rto_max;
sctp_max_rto(tp->asoc, tp);
tp->rtt = rtt;
/* Reset rto_pending so that a new RTT measurement is started when a
* new data chunk is sent.
*/
tp->rto_pending = 0;
pr_debug("%s: transport:%p, rtt:%d, srtt:%d rttvar:%d, rto:%ld\n",
__func__, tp, rtt, tp->srtt, tp->rttvar, tp->rto);
}
/* This routine updates the transport's cwnd and partial_bytes_acked
* parameters based on the bytes acked in the received SACK.
*/
void sctp_transport_raise_cwnd(struct sctp_transport *transport,
__u32 sack_ctsn, __u32 bytes_acked)
{
struct sctp_association *asoc = transport->asoc;
__u32 cwnd, ssthresh, flight_size, pba, pmtu;
cwnd = transport->cwnd;
flight_size = transport->flight_size;
/* See if we need to exit Fast Recovery first */
if (asoc->fast_recovery &&
TSN_lte(asoc->fast_recovery_exit, sack_ctsn))
asoc->fast_recovery = 0;
ssthresh = transport->ssthresh;
pba = transport->partial_bytes_acked;
pmtu = transport->asoc->pathmtu;
if (cwnd <= ssthresh) {
/* RFC 4960 7.2.1
* o When cwnd is less than or equal to ssthresh, an SCTP
* endpoint MUST use the slow-start algorithm to increase
* cwnd only if the current congestion window is being fully
* utilized, an incoming SACK advances the Cumulative TSN
* Ack Point, and the data sender is not in Fast Recovery.
* Only when these three conditions are met can the cwnd be
* increased; otherwise, the cwnd MUST not be increased.
* If these conditions are met, then cwnd MUST be increased
* by, at most, the lesser of 1) the total size of the
* previously outstanding DATA chunk(s) acknowledged, and
* 2) the destination's path MTU. This upper bound protects
* against the ACK-Splitting attack outlined in [SAVAGE99].
*/
if (asoc->fast_recovery)
return;
/* The appropriate cwnd increase algorithm is performed
* if, and only if the congestion window is being fully
* utilized. Note that RFC4960 Errata 3.22 removed the
* other condition on ctsn moving.
*/
if (flight_size < cwnd)
return;
if (bytes_acked > pmtu)
cwnd += pmtu;
else
cwnd += bytes_acked;
pr_debug("%s: slow start: transport:%p, bytes_acked:%d, "
"cwnd:%d, ssthresh:%d, flight_size:%d, pba:%d\n",
__func__, transport, bytes_acked, cwnd, ssthresh,
flight_size, pba);
} else {
/* RFC 2960 7.2.2 Whenever cwnd is greater than ssthresh,
* upon each SACK arrival, increase partial_bytes_acked
* by the total number of bytes of all new chunks
* acknowledged in that SACK including chunks
* acknowledged by the new Cumulative TSN Ack and by Gap
* Ack Blocks. (updated by RFC4960 Errata 3.22)
*
* When partial_bytes_acked is greater than cwnd and
* before the arrival of the SACK the sender had less
* bytes of data outstanding than cwnd (i.e., before
* arrival of the SACK, flightsize was less than cwnd),
* reset partial_bytes_acked to cwnd. (RFC 4960 Errata
* 3.26)
*
* When partial_bytes_acked is equal to or greater than
* cwnd and before the arrival of the SACK the sender
* had cwnd or more bytes of data outstanding (i.e.,
* before arrival of the SACK, flightsize was greater
* than or equal to cwnd), partial_bytes_acked is reset
* to (partial_bytes_acked - cwnd). Next, cwnd is
* increased by MTU. (RFC 4960 Errata 3.12)
*/
pba += bytes_acked;
if (pba > cwnd && flight_size < cwnd)
pba = cwnd;
if (pba >= cwnd && flight_size >= cwnd) {
pba = pba - cwnd;
cwnd += pmtu;
}
pr_debug("%s: congestion avoidance: transport:%p, "
"bytes_acked:%d, cwnd:%d, ssthresh:%d, "
"flight_size:%d, pba:%d\n", __func__,
transport, bytes_acked, cwnd, ssthresh,
flight_size, pba);
}
transport->cwnd = cwnd;
transport->partial_bytes_acked = pba;
}
/* This routine is used to lower the transport's cwnd when congestion is
* detected.
*/
void sctp_transport_lower_cwnd(struct sctp_transport *transport,
enum sctp_lower_cwnd reason)
{
struct sctp_association *asoc = transport->asoc;
switch (reason) {
case SCTP_LOWER_CWND_T3_RTX:
/* RFC 2960 Section 7.2.3, sctpimpguide
* When the T3-rtx timer expires on an address, SCTP should
* perform slow start by:
* ssthresh = max(cwnd/2, 4*MTU)
* cwnd = 1*MTU
* partial_bytes_acked = 0
*/
transport->ssthresh = max(transport->cwnd/2,
4*asoc->pathmtu);
transport->cwnd = asoc->pathmtu;
/* T3-rtx also clears fast recovery */
asoc->fast_recovery = 0;
break;
case SCTP_LOWER_CWND_FAST_RTX:
/* RFC 2960 7.2.4 Adjust the ssthresh and cwnd of the
* destination address(es) to which the missing DATA chunks
* were last sent, according to the formula described in
* Section 7.2.3.
*
* RFC 2960 7.2.3, sctpimpguide Upon detection of packet
* losses from SACK (see Section 7.2.4), An endpoint
* should do the following:
* ssthresh = max(cwnd/2, 4*MTU)
* cwnd = ssthresh
* partial_bytes_acked = 0
*/
if (asoc->fast_recovery)
return;
/* Mark Fast recovery */
asoc->fast_recovery = 1;
asoc->fast_recovery_exit = asoc->next_tsn - 1;
transport->ssthresh = max(transport->cwnd/2,
4*asoc->pathmtu);
transport->cwnd = transport->ssthresh;
break;
case SCTP_LOWER_CWND_ECNE:
/* RFC 2481 Section 6.1.2.
* If the sender receives an ECN-Echo ACK packet
* then the sender knows that congestion was encountered in the
* network on the path from the sender to the receiver. The
* indication of congestion should be treated just as a
* congestion loss in non-ECN Capable TCP. That is, the TCP
* source halves the congestion window "cwnd" and reduces the
* slow start threshold "ssthresh".
* A critical condition is that TCP does not react to
* congestion indications more than once every window of
* data (or more loosely more than once every round-trip time).
*/
if (time_after(jiffies, transport->last_time_ecne_reduced +
transport->rtt)) {
transport->ssthresh = max(transport->cwnd/2,
4*asoc->pathmtu);
transport->cwnd = transport->ssthresh;
transport->last_time_ecne_reduced = jiffies;
}
break;
case SCTP_LOWER_CWND_INACTIVE:
/* RFC 2960 Section 7.2.1, sctpimpguide
* When the endpoint does not transmit data on a given
* transport address, the cwnd of the transport address
* should be adjusted to max(cwnd/2, 4*MTU) per RTO.
* NOTE: Although the draft recommends that this check needs
* to be done every RTO interval, we do it every hearbeat
* interval.
*/
transport->cwnd = max(transport->cwnd/2,
4*asoc->pathmtu);
/* RFC 4960 Errata 3.27.2: also adjust sshthresh */
transport->ssthresh = transport->cwnd;
break;
}
transport->partial_bytes_acked = 0;
pr_debug("%s: transport:%p, reason:%d, cwnd:%d, ssthresh:%d\n",
__func__, transport, reason, transport->cwnd,
transport->ssthresh);
}
/* Apply Max.Burst limit to the congestion window:
* sctpimpguide-05 2.14.2
* D) When the time comes for the sender to
* transmit new DATA chunks, the protocol parameter Max.Burst MUST
* first be applied to limit how many new DATA chunks may be sent.
* The limit is applied by adjusting cwnd as follows:
* if ((flightsize+ Max.Burst * MTU) < cwnd)
* cwnd = flightsize + Max.Burst * MTU
*/
void sctp_transport_burst_limited(struct sctp_transport *t)
{
struct sctp_association *asoc = t->asoc;
u32 old_cwnd = t->cwnd;
u32 max_burst_bytes;
if (t->burst_limited || asoc->max_burst == 0)
return;
max_burst_bytes = t->flight_size + (asoc->max_burst * asoc->pathmtu);
if (max_burst_bytes < old_cwnd) {
t->cwnd = max_burst_bytes;
t->burst_limited = old_cwnd;
}
}
/* Restore the old cwnd congestion window, after the burst had it's
* desired effect.
*/
void sctp_transport_burst_reset(struct sctp_transport *t)
{
if (t->burst_limited) {
t->cwnd = t->burst_limited;
t->burst_limited = 0;
}
}
/* What is the next timeout value for this transport? */
unsigned long sctp_transport_timeout(struct sctp_transport *trans)
{
/* RTO + timer slack +/- 50% of RTO */
unsigned long timeout = trans->rto >> 1;
if (trans->state != SCTP_UNCONFIRMED &&
trans->state != SCTP_PF)
timeout += trans->hbinterval;
return max_t(unsigned long, timeout, HZ / 5);
}
/* Reset transport variables to their initial values */
void sctp_transport_reset(struct sctp_transport *t)
{
struct sctp_association *asoc = t->asoc;
/* RFC 2960 (bis), Section 5.2.4
* All the congestion control parameters (e.g., cwnd, ssthresh)
* related to this peer MUST be reset to their initial values
* (see Section 6.2.1)
*/
t->cwnd = min(4*asoc->pathmtu, max_t(__u32, 2*asoc->pathmtu, 4380));
t->burst_limited = 0;
t->ssthresh = asoc->peer.i.a_rwnd;
t->rto = asoc->rto_initial;
sctp_max_rto(asoc, t);
t->rtt = 0;
t->srtt = 0;
t->rttvar = 0;
/* Reset these additional variables so that we have a clean slate. */
t->partial_bytes_acked = 0;
t->flight_size = 0;
t->error_count = 0;
t->rto_pending = 0;
t->hb_sent = 0;
/* Initialize the state information for SFR-CACC */
t->cacc.changeover_active = 0;
t->cacc.cycling_changeover = 0;
t->cacc.next_tsn_at_change = 0;
t->cacc.cacc_saw_newack = 0;
}
/* Schedule retransmission on the given transport */
void sctp_transport_immediate_rtx(struct sctp_transport *t)
{
/* Stop pending T3_rtx_timer */
if (del_timer(&t->T3_rtx_timer))
sctp_transport_put(t);
sctp_retransmit(&t->asoc->outqueue, t, SCTP_RTXR_T3_RTX);
if (!timer_pending(&t->T3_rtx_timer)) {
if (!mod_timer(&t->T3_rtx_timer, jiffies + t->rto))
sctp_transport_hold(t);
}
}
/* Drop dst */
void sctp_transport_dst_release(struct sctp_transport *t)
{
dst_release(t->dst);
t->dst = NULL;
t->dst_pending_confirm = 0;
}
/* Schedule neighbour confirm */
void sctp_transport_dst_confirm(struct sctp_transport *t)
{
t->dst_pending_confirm = 1;
}
| linux-master | net/sctp/transport.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright 2007 Hewlett-Packard Development Company, L.P.
*
* This file is part of the SCTP kernel implementation
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Vlad Yasevich <[email protected]>
*/
#include <crypto/hash.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/scatterlist.h>
#include <net/sctp/sctp.h>
#include <net/sctp/auth.h>
static struct sctp_hmac sctp_hmac_list[SCTP_AUTH_NUM_HMACS] = {
{
/* id 0 is reserved. as all 0 */
.hmac_id = SCTP_AUTH_HMAC_ID_RESERVED_0,
},
{
.hmac_id = SCTP_AUTH_HMAC_ID_SHA1,
.hmac_name = "hmac(sha1)",
.hmac_len = SCTP_SHA1_SIG_SIZE,
},
{
/* id 2 is reserved as well */
.hmac_id = SCTP_AUTH_HMAC_ID_RESERVED_2,
},
#if IS_ENABLED(CONFIG_CRYPTO_SHA256)
{
.hmac_id = SCTP_AUTH_HMAC_ID_SHA256,
.hmac_name = "hmac(sha256)",
.hmac_len = SCTP_SHA256_SIG_SIZE,
}
#endif
};
void sctp_auth_key_put(struct sctp_auth_bytes *key)
{
if (!key)
return;
if (refcount_dec_and_test(&key->refcnt)) {
kfree_sensitive(key);
SCTP_DBG_OBJCNT_DEC(keys);
}
}
/* Create a new key structure of a given length */
static struct sctp_auth_bytes *sctp_auth_create_key(__u32 key_len, gfp_t gfp)
{
struct sctp_auth_bytes *key;
/* Verify that we are not going to overflow INT_MAX */
if (key_len > (INT_MAX - sizeof(struct sctp_auth_bytes)))
return NULL;
/* Allocate the shared key */
key = kmalloc(sizeof(struct sctp_auth_bytes) + key_len, gfp);
if (!key)
return NULL;
key->len = key_len;
refcount_set(&key->refcnt, 1);
SCTP_DBG_OBJCNT_INC(keys);
return key;
}
/* Create a new shared key container with a give key id */
struct sctp_shared_key *sctp_auth_shkey_create(__u16 key_id, gfp_t gfp)
{
struct sctp_shared_key *new;
/* Allocate the shared key container */
new = kzalloc(sizeof(struct sctp_shared_key), gfp);
if (!new)
return NULL;
INIT_LIST_HEAD(&new->key_list);
refcount_set(&new->refcnt, 1);
new->key_id = key_id;
return new;
}
/* Free the shared key structure */
static void sctp_auth_shkey_destroy(struct sctp_shared_key *sh_key)
{
BUG_ON(!list_empty(&sh_key->key_list));
sctp_auth_key_put(sh_key->key);
sh_key->key = NULL;
kfree(sh_key);
}
void sctp_auth_shkey_release(struct sctp_shared_key *sh_key)
{
if (refcount_dec_and_test(&sh_key->refcnt))
sctp_auth_shkey_destroy(sh_key);
}
void sctp_auth_shkey_hold(struct sctp_shared_key *sh_key)
{
refcount_inc(&sh_key->refcnt);
}
/* Destroy the entire key list. This is done during the
* associon and endpoint free process.
*/
void sctp_auth_destroy_keys(struct list_head *keys)
{
struct sctp_shared_key *ep_key;
struct sctp_shared_key *tmp;
if (list_empty(keys))
return;
key_for_each_safe(ep_key, tmp, keys) {
list_del_init(&ep_key->key_list);
sctp_auth_shkey_release(ep_key);
}
}
/* Compare two byte vectors as numbers. Return values
* are:
* 0 - vectors are equal
* < 0 - vector 1 is smaller than vector2
* > 0 - vector 1 is greater than vector2
*
* Algorithm is:
* This is performed by selecting the numerically smaller key vector...
* If the key vectors are equal as numbers but differ in length ...
* the shorter vector is considered smaller
*
* Examples (with small values):
* 000123456789 > 123456789 (first number is longer)
* 000123456789 < 234567891 (second number is larger numerically)
* 123456789 > 2345678 (first number is both larger & longer)
*/
static int sctp_auth_compare_vectors(struct sctp_auth_bytes *vector1,
struct sctp_auth_bytes *vector2)
{
int diff;
int i;
const __u8 *longer;
diff = vector1->len - vector2->len;
if (diff) {
longer = (diff > 0) ? vector1->data : vector2->data;
/* Check to see if the longer number is
* lead-zero padded. If it is not, it
* is automatically larger numerically.
*/
for (i = 0; i < abs(diff); i++) {
if (longer[i] != 0)
return diff;
}
}
/* lengths are the same, compare numbers */
return memcmp(vector1->data, vector2->data, vector1->len);
}
/*
* Create a key vector as described in SCTP-AUTH, Section 6.1
* The RANDOM parameter, the CHUNKS parameter and the HMAC-ALGO
* parameter sent by each endpoint are concatenated as byte vectors.
* These parameters include the parameter type, parameter length, and
* the parameter value, but padding is omitted; all padding MUST be
* removed from this concatenation before proceeding with further
* computation of keys. Parameters which were not sent are simply
* omitted from the concatenation process. The resulting two vectors
* are called the two key vectors.
*/
static struct sctp_auth_bytes *sctp_auth_make_key_vector(
struct sctp_random_param *random,
struct sctp_chunks_param *chunks,
struct sctp_hmac_algo_param *hmacs,
gfp_t gfp)
{
struct sctp_auth_bytes *new;
__u32 len;
__u32 offset = 0;
__u16 random_len, hmacs_len, chunks_len = 0;
random_len = ntohs(random->param_hdr.length);
hmacs_len = ntohs(hmacs->param_hdr.length);
if (chunks)
chunks_len = ntohs(chunks->param_hdr.length);
len = random_len + hmacs_len + chunks_len;
new = sctp_auth_create_key(len, gfp);
if (!new)
return NULL;
memcpy(new->data, random, random_len);
offset += random_len;
if (chunks) {
memcpy(new->data + offset, chunks, chunks_len);
offset += chunks_len;
}
memcpy(new->data + offset, hmacs, hmacs_len);
return new;
}
/* Make a key vector based on our local parameters */
static struct sctp_auth_bytes *sctp_auth_make_local_vector(
const struct sctp_association *asoc,
gfp_t gfp)
{
return sctp_auth_make_key_vector(
(struct sctp_random_param *)asoc->c.auth_random,
(struct sctp_chunks_param *)asoc->c.auth_chunks,
(struct sctp_hmac_algo_param *)asoc->c.auth_hmacs, gfp);
}
/* Make a key vector based on peer's parameters */
static struct sctp_auth_bytes *sctp_auth_make_peer_vector(
const struct sctp_association *asoc,
gfp_t gfp)
{
return sctp_auth_make_key_vector(asoc->peer.peer_random,
asoc->peer.peer_chunks,
asoc->peer.peer_hmacs,
gfp);
}
/* Set the value of the association shared key base on the parameters
* given. The algorithm is:
* From the endpoint pair shared keys and the key vectors the
* association shared keys are computed. This is performed by selecting
* the numerically smaller key vector and concatenating it to the
* endpoint pair shared key, and then concatenating the numerically
* larger key vector to that. The result of the concatenation is the
* association shared key.
*/
static struct sctp_auth_bytes *sctp_auth_asoc_set_secret(
struct sctp_shared_key *ep_key,
struct sctp_auth_bytes *first_vector,
struct sctp_auth_bytes *last_vector,
gfp_t gfp)
{
struct sctp_auth_bytes *secret;
__u32 offset = 0;
__u32 auth_len;
auth_len = first_vector->len + last_vector->len;
if (ep_key->key)
auth_len += ep_key->key->len;
secret = sctp_auth_create_key(auth_len, gfp);
if (!secret)
return NULL;
if (ep_key->key) {
memcpy(secret->data, ep_key->key->data, ep_key->key->len);
offset += ep_key->key->len;
}
memcpy(secret->data + offset, first_vector->data, first_vector->len);
offset += first_vector->len;
memcpy(secret->data + offset, last_vector->data, last_vector->len);
return secret;
}
/* Create an association shared key. Follow the algorithm
* described in SCTP-AUTH, Section 6.1
*/
static struct sctp_auth_bytes *sctp_auth_asoc_create_secret(
const struct sctp_association *asoc,
struct sctp_shared_key *ep_key,
gfp_t gfp)
{
struct sctp_auth_bytes *local_key_vector;
struct sctp_auth_bytes *peer_key_vector;
struct sctp_auth_bytes *first_vector,
*last_vector;
struct sctp_auth_bytes *secret = NULL;
int cmp;
/* Now we need to build the key vectors
* SCTP-AUTH , Section 6.1
* The RANDOM parameter, the CHUNKS parameter and the HMAC-ALGO
* parameter sent by each endpoint are concatenated as byte vectors.
* These parameters include the parameter type, parameter length, and
* the parameter value, but padding is omitted; all padding MUST be
* removed from this concatenation before proceeding with further
* computation of keys. Parameters which were not sent are simply
* omitted from the concatenation process. The resulting two vectors
* are called the two key vectors.
*/
local_key_vector = sctp_auth_make_local_vector(asoc, gfp);
peer_key_vector = sctp_auth_make_peer_vector(asoc, gfp);
if (!peer_key_vector || !local_key_vector)
goto out;
/* Figure out the order in which the key_vectors will be
* added to the endpoint shared key.
* SCTP-AUTH, Section 6.1:
* This is performed by selecting the numerically smaller key
* vector and concatenating it to the endpoint pair shared
* key, and then concatenating the numerically larger key
* vector to that. If the key vectors are equal as numbers
* but differ in length, then the concatenation order is the
* endpoint shared key, followed by the shorter key vector,
* followed by the longer key vector. Otherwise, the key
* vectors are identical, and may be concatenated to the
* endpoint pair key in any order.
*/
cmp = sctp_auth_compare_vectors(local_key_vector,
peer_key_vector);
if (cmp < 0) {
first_vector = local_key_vector;
last_vector = peer_key_vector;
} else {
first_vector = peer_key_vector;
last_vector = local_key_vector;
}
secret = sctp_auth_asoc_set_secret(ep_key, first_vector, last_vector,
gfp);
out:
sctp_auth_key_put(local_key_vector);
sctp_auth_key_put(peer_key_vector);
return secret;
}
/*
* Populate the association overlay list with the list
* from the endpoint.
*/
int sctp_auth_asoc_copy_shkeys(const struct sctp_endpoint *ep,
struct sctp_association *asoc,
gfp_t gfp)
{
struct sctp_shared_key *sh_key;
struct sctp_shared_key *new;
BUG_ON(!list_empty(&asoc->endpoint_shared_keys));
key_for_each(sh_key, &ep->endpoint_shared_keys) {
new = sctp_auth_shkey_create(sh_key->key_id, gfp);
if (!new)
goto nomem;
new->key = sh_key->key;
sctp_auth_key_hold(new->key);
list_add(&new->key_list, &asoc->endpoint_shared_keys);
}
return 0;
nomem:
sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
return -ENOMEM;
}
/* Public interface to create the association shared key.
* See code above for the algorithm.
*/
int sctp_auth_asoc_init_active_key(struct sctp_association *asoc, gfp_t gfp)
{
struct sctp_auth_bytes *secret;
struct sctp_shared_key *ep_key;
struct sctp_chunk *chunk;
/* If we don't support AUTH, or peer is not capable
* we don't need to do anything.
*/
if (!asoc->peer.auth_capable)
return 0;
/* If the key_id is non-zero and we couldn't find an
* endpoint pair shared key, we can't compute the
* secret.
* For key_id 0, endpoint pair shared key is a NULL key.
*/
ep_key = sctp_auth_get_shkey(asoc, asoc->active_key_id);
BUG_ON(!ep_key);
secret = sctp_auth_asoc_create_secret(asoc, ep_key, gfp);
if (!secret)
return -ENOMEM;
sctp_auth_key_put(asoc->asoc_shared_key);
asoc->asoc_shared_key = secret;
asoc->shkey = ep_key;
/* Update send queue in case any chunk already in there now
* needs authenticating
*/
list_for_each_entry(chunk, &asoc->outqueue.out_chunk_list, list) {
if (sctp_auth_send_cid(chunk->chunk_hdr->type, asoc)) {
chunk->auth = 1;
if (!chunk->shkey) {
chunk->shkey = asoc->shkey;
sctp_auth_shkey_hold(chunk->shkey);
}
}
}
return 0;
}
/* Find the endpoint pair shared key based on the key_id */
struct sctp_shared_key *sctp_auth_get_shkey(
const struct sctp_association *asoc,
__u16 key_id)
{
struct sctp_shared_key *key;
/* First search associations set of endpoint pair shared keys */
key_for_each(key, &asoc->endpoint_shared_keys) {
if (key->key_id == key_id) {
if (!key->deactivated)
return key;
break;
}
}
return NULL;
}
/*
* Initialize all the possible digest transforms that we can use. Right
* now, the supported digests are SHA1 and SHA256. We do this here once
* because of the restrictiong that transforms may only be allocated in
* user context. This forces us to pre-allocated all possible transforms
* at the endpoint init time.
*/
int sctp_auth_init_hmacs(struct sctp_endpoint *ep, gfp_t gfp)
{
struct crypto_shash *tfm = NULL;
__u16 id;
/* If the transforms are already allocated, we are done */
if (ep->auth_hmacs)
return 0;
/* Allocated the array of pointers to transorms */
ep->auth_hmacs = kcalloc(SCTP_AUTH_NUM_HMACS,
sizeof(struct crypto_shash *),
gfp);
if (!ep->auth_hmacs)
return -ENOMEM;
for (id = 0; id < SCTP_AUTH_NUM_HMACS; id++) {
/* See is we support the id. Supported IDs have name and
* length fields set, so that we can allocated and use
* them. We can safely just check for name, for without the
* name, we can't allocate the TFM.
*/
if (!sctp_hmac_list[id].hmac_name)
continue;
/* If this TFM has been allocated, we are all set */
if (ep->auth_hmacs[id])
continue;
/* Allocate the ID */
tfm = crypto_alloc_shash(sctp_hmac_list[id].hmac_name, 0, 0);
if (IS_ERR(tfm))
goto out_err;
ep->auth_hmacs[id] = tfm;
}
return 0;
out_err:
/* Clean up any successful allocations */
sctp_auth_destroy_hmacs(ep->auth_hmacs);
ep->auth_hmacs = NULL;
return -ENOMEM;
}
/* Destroy the hmac tfm array */
void sctp_auth_destroy_hmacs(struct crypto_shash *auth_hmacs[])
{
int i;
if (!auth_hmacs)
return;
for (i = 0; i < SCTP_AUTH_NUM_HMACS; i++) {
crypto_free_shash(auth_hmacs[i]);
}
kfree(auth_hmacs);
}
struct sctp_hmac *sctp_auth_get_hmac(__u16 hmac_id)
{
return &sctp_hmac_list[hmac_id];
}
/* Get an hmac description information that we can use to build
* the AUTH chunk
*/
struct sctp_hmac *sctp_auth_asoc_get_hmac(const struct sctp_association *asoc)
{
struct sctp_hmac_algo_param *hmacs;
__u16 n_elt;
__u16 id = 0;
int i;
/* If we have a default entry, use it */
if (asoc->default_hmac_id)
return &sctp_hmac_list[asoc->default_hmac_id];
/* Since we do not have a default entry, find the first entry
* we support and return that. Do not cache that id.
*/
hmacs = asoc->peer.peer_hmacs;
if (!hmacs)
return NULL;
n_elt = (ntohs(hmacs->param_hdr.length) -
sizeof(struct sctp_paramhdr)) >> 1;
for (i = 0; i < n_elt; i++) {
id = ntohs(hmacs->hmac_ids[i]);
/* Check the id is in the supported range. And
* see if we support the id. Supported IDs have name and
* length fields set, so that we can allocate and use
* them. We can safely just check for name, for without the
* name, we can't allocate the TFM.
*/
if (id > SCTP_AUTH_HMAC_ID_MAX ||
!sctp_hmac_list[id].hmac_name) {
id = 0;
continue;
}
break;
}
if (id == 0)
return NULL;
return &sctp_hmac_list[id];
}
static int __sctp_auth_find_hmacid(__be16 *hmacs, int n_elts, __be16 hmac_id)
{
int found = 0;
int i;
for (i = 0; i < n_elts; i++) {
if (hmac_id == hmacs[i]) {
found = 1;
break;
}
}
return found;
}
/* See if the HMAC_ID is one that we claim as supported */
int sctp_auth_asoc_verify_hmac_id(const struct sctp_association *asoc,
__be16 hmac_id)
{
struct sctp_hmac_algo_param *hmacs;
__u16 n_elt;
if (!asoc)
return 0;
hmacs = (struct sctp_hmac_algo_param *)asoc->c.auth_hmacs;
n_elt = (ntohs(hmacs->param_hdr.length) -
sizeof(struct sctp_paramhdr)) >> 1;
return __sctp_auth_find_hmacid(hmacs->hmac_ids, n_elt, hmac_id);
}
/* Cache the default HMAC id. This to follow this text from SCTP-AUTH:
* Section 6.1:
* The receiver of a HMAC-ALGO parameter SHOULD use the first listed
* algorithm it supports.
*/
void sctp_auth_asoc_set_default_hmac(struct sctp_association *asoc,
struct sctp_hmac_algo_param *hmacs)
{
struct sctp_endpoint *ep;
__u16 id;
int i;
int n_params;
/* if the default id is already set, use it */
if (asoc->default_hmac_id)
return;
n_params = (ntohs(hmacs->param_hdr.length) -
sizeof(struct sctp_paramhdr)) >> 1;
ep = asoc->ep;
for (i = 0; i < n_params; i++) {
id = ntohs(hmacs->hmac_ids[i]);
/* Check the id is in the supported range */
if (id > SCTP_AUTH_HMAC_ID_MAX)
continue;
/* If this TFM has been allocated, use this id */
if (ep->auth_hmacs[id]) {
asoc->default_hmac_id = id;
break;
}
}
}
/* Check to see if the given chunk is supposed to be authenticated */
static int __sctp_auth_cid(enum sctp_cid chunk, struct sctp_chunks_param *param)
{
unsigned short len;
int found = 0;
int i;
if (!param || param->param_hdr.length == 0)
return 0;
len = ntohs(param->param_hdr.length) - sizeof(struct sctp_paramhdr);
/* SCTP-AUTH, Section 3.2
* The chunk types for INIT, INIT-ACK, SHUTDOWN-COMPLETE and AUTH
* chunks MUST NOT be listed in the CHUNKS parameter. However, if
* a CHUNKS parameter is received then the types for INIT, INIT-ACK,
* SHUTDOWN-COMPLETE and AUTH chunks MUST be ignored.
*/
for (i = 0; !found && i < len; i++) {
switch (param->chunks[i]) {
case SCTP_CID_INIT:
case SCTP_CID_INIT_ACK:
case SCTP_CID_SHUTDOWN_COMPLETE:
case SCTP_CID_AUTH:
break;
default:
if (param->chunks[i] == chunk)
found = 1;
break;
}
}
return found;
}
/* Check if peer requested that this chunk is authenticated */
int sctp_auth_send_cid(enum sctp_cid chunk, const struct sctp_association *asoc)
{
if (!asoc)
return 0;
if (!asoc->peer.auth_capable)
return 0;
return __sctp_auth_cid(chunk, asoc->peer.peer_chunks);
}
/* Check if we requested that peer authenticate this chunk. */
int sctp_auth_recv_cid(enum sctp_cid chunk, const struct sctp_association *asoc)
{
if (!asoc)
return 0;
if (!asoc->peer.auth_capable)
return 0;
return __sctp_auth_cid(chunk,
(struct sctp_chunks_param *)asoc->c.auth_chunks);
}
/* SCTP-AUTH: Section 6.2:
* The sender MUST calculate the MAC as described in RFC2104 [2] using
* the hash function H as described by the MAC Identifier and the shared
* association key K based on the endpoint pair shared key described by
* the shared key identifier. The 'data' used for the computation of
* the AUTH-chunk is given by the AUTH chunk with its HMAC field set to
* zero (as shown in Figure 6) followed by all chunks that are placed
* after the AUTH chunk in the SCTP packet.
*/
void sctp_auth_calculate_hmac(const struct sctp_association *asoc,
struct sk_buff *skb, struct sctp_auth_chunk *auth,
struct sctp_shared_key *ep_key, gfp_t gfp)
{
struct sctp_auth_bytes *asoc_key;
struct crypto_shash *tfm;
__u16 key_id, hmac_id;
unsigned char *end;
int free_key = 0;
__u8 *digest;
/* Extract the info we need:
* - hmac id
* - key id
*/
key_id = ntohs(auth->auth_hdr.shkey_id);
hmac_id = ntohs(auth->auth_hdr.hmac_id);
if (key_id == asoc->active_key_id)
asoc_key = asoc->asoc_shared_key;
else {
/* ep_key can't be NULL here */
asoc_key = sctp_auth_asoc_create_secret(asoc, ep_key, gfp);
if (!asoc_key)
return;
free_key = 1;
}
/* set up scatter list */
end = skb_tail_pointer(skb);
tfm = asoc->ep->auth_hmacs[hmac_id];
digest = (u8 *)(&auth->auth_hdr + 1);
if (crypto_shash_setkey(tfm, &asoc_key->data[0], asoc_key->len))
goto free;
crypto_shash_tfm_digest(tfm, (u8 *)auth, end - (unsigned char *)auth,
digest);
free:
if (free_key)
sctp_auth_key_put(asoc_key);
}
/* API Helpers */
/* Add a chunk to the endpoint authenticated chunk list */
int sctp_auth_ep_add_chunkid(struct sctp_endpoint *ep, __u8 chunk_id)
{
struct sctp_chunks_param *p = ep->auth_chunk_list;
__u16 nchunks;
__u16 param_len;
/* If this chunk is already specified, we are done */
if (__sctp_auth_cid(chunk_id, p))
return 0;
/* Check if we can add this chunk to the array */
param_len = ntohs(p->param_hdr.length);
nchunks = param_len - sizeof(struct sctp_paramhdr);
if (nchunks == SCTP_NUM_CHUNK_TYPES)
return -EINVAL;
p->chunks[nchunks] = chunk_id;
p->param_hdr.length = htons(param_len + 1);
return 0;
}
/* Add hmac identifires to the endpoint list of supported hmac ids */
int sctp_auth_ep_set_hmacs(struct sctp_endpoint *ep,
struct sctp_hmacalgo *hmacs)
{
int has_sha1 = 0;
__u16 id;
int i;
/* Scan the list looking for unsupported id. Also make sure that
* SHA1 is specified.
*/
for (i = 0; i < hmacs->shmac_num_idents; i++) {
id = hmacs->shmac_idents[i];
if (id > SCTP_AUTH_HMAC_ID_MAX)
return -EOPNOTSUPP;
if (SCTP_AUTH_HMAC_ID_SHA1 == id)
has_sha1 = 1;
if (!sctp_hmac_list[id].hmac_name)
return -EOPNOTSUPP;
}
if (!has_sha1)
return -EINVAL;
for (i = 0; i < hmacs->shmac_num_idents; i++)
ep->auth_hmacs_list->hmac_ids[i] =
htons(hmacs->shmac_idents[i]);
ep->auth_hmacs_list->param_hdr.length =
htons(sizeof(struct sctp_paramhdr) +
hmacs->shmac_num_idents * sizeof(__u16));
return 0;
}
/* Set a new shared key on either endpoint or association. If the
* key with a same ID already exists, replace the key (remove the
* old key and add a new one).
*/
int sctp_auth_set_key(struct sctp_endpoint *ep,
struct sctp_association *asoc,
struct sctp_authkey *auth_key)
{
struct sctp_shared_key *cur_key, *shkey;
struct sctp_auth_bytes *key;
struct list_head *sh_keys;
int replace = 0;
/* Try to find the given key id to see if
* we are doing a replace, or adding a new key
*/
if (asoc) {
if (!asoc->peer.auth_capable)
return -EACCES;
sh_keys = &asoc->endpoint_shared_keys;
} else {
if (!ep->auth_enable)
return -EACCES;
sh_keys = &ep->endpoint_shared_keys;
}
key_for_each(shkey, sh_keys) {
if (shkey->key_id == auth_key->sca_keynumber) {
replace = 1;
break;
}
}
cur_key = sctp_auth_shkey_create(auth_key->sca_keynumber, GFP_KERNEL);
if (!cur_key)
return -ENOMEM;
/* Create a new key data based on the info passed in */
key = sctp_auth_create_key(auth_key->sca_keylength, GFP_KERNEL);
if (!key) {
kfree(cur_key);
return -ENOMEM;
}
memcpy(key->data, &auth_key->sca_key[0], auth_key->sca_keylength);
cur_key->key = key;
if (!replace) {
list_add(&cur_key->key_list, sh_keys);
return 0;
}
list_del_init(&shkey->key_list);
list_add(&cur_key->key_list, sh_keys);
if (asoc && asoc->active_key_id == auth_key->sca_keynumber &&
sctp_auth_asoc_init_active_key(asoc, GFP_KERNEL)) {
list_del_init(&cur_key->key_list);
sctp_auth_shkey_release(cur_key);
list_add(&shkey->key_list, sh_keys);
return -ENOMEM;
}
sctp_auth_shkey_release(shkey);
return 0;
}
int sctp_auth_set_active_key(struct sctp_endpoint *ep,
struct sctp_association *asoc,
__u16 key_id)
{
struct sctp_shared_key *key;
struct list_head *sh_keys;
int found = 0;
/* The key identifier MUST correst to an existing key */
if (asoc) {
if (!asoc->peer.auth_capable)
return -EACCES;
sh_keys = &asoc->endpoint_shared_keys;
} else {
if (!ep->auth_enable)
return -EACCES;
sh_keys = &ep->endpoint_shared_keys;
}
key_for_each(key, sh_keys) {
if (key->key_id == key_id) {
found = 1;
break;
}
}
if (!found || key->deactivated)
return -EINVAL;
if (asoc) {
__u16 active_key_id = asoc->active_key_id;
asoc->active_key_id = key_id;
if (sctp_auth_asoc_init_active_key(asoc, GFP_KERNEL)) {
asoc->active_key_id = active_key_id;
return -ENOMEM;
}
} else
ep->active_key_id = key_id;
return 0;
}
int sctp_auth_del_key_id(struct sctp_endpoint *ep,
struct sctp_association *asoc,
__u16 key_id)
{
struct sctp_shared_key *key;
struct list_head *sh_keys;
int found = 0;
/* The key identifier MUST NOT be the current active key
* The key identifier MUST correst to an existing key
*/
if (asoc) {
if (!asoc->peer.auth_capable)
return -EACCES;
if (asoc->active_key_id == key_id)
return -EINVAL;
sh_keys = &asoc->endpoint_shared_keys;
} else {
if (!ep->auth_enable)
return -EACCES;
if (ep->active_key_id == key_id)
return -EINVAL;
sh_keys = &ep->endpoint_shared_keys;
}
key_for_each(key, sh_keys) {
if (key->key_id == key_id) {
found = 1;
break;
}
}
if (!found)
return -EINVAL;
/* Delete the shared key */
list_del_init(&key->key_list);
sctp_auth_shkey_release(key);
return 0;
}
int sctp_auth_deact_key_id(struct sctp_endpoint *ep,
struct sctp_association *asoc, __u16 key_id)
{
struct sctp_shared_key *key;
struct list_head *sh_keys;
int found = 0;
/* The key identifier MUST NOT be the current active key
* The key identifier MUST correst to an existing key
*/
if (asoc) {
if (!asoc->peer.auth_capable)
return -EACCES;
if (asoc->active_key_id == key_id)
return -EINVAL;
sh_keys = &asoc->endpoint_shared_keys;
} else {
if (!ep->auth_enable)
return -EACCES;
if (ep->active_key_id == key_id)
return -EINVAL;
sh_keys = &ep->endpoint_shared_keys;
}
key_for_each(key, sh_keys) {
if (key->key_id == key_id) {
found = 1;
break;
}
}
if (!found)
return -EINVAL;
/* refcnt == 1 and !list_empty mean it's not being used anywhere
* and deactivated will be set, so it's time to notify userland
* that this shkey can be freed.
*/
if (asoc && !list_empty(&key->key_list) &&
refcount_read(&key->refcnt) == 1) {
struct sctp_ulpevent *ev;
ev = sctp_ulpevent_make_authkey(asoc, key->key_id,
SCTP_AUTH_FREE_KEY, GFP_KERNEL);
if (ev)
asoc->stream.si->enqueue_event(&asoc->ulpq, ev);
}
key->deactivated = 1;
return 0;
}
int sctp_auth_init(struct sctp_endpoint *ep, gfp_t gfp)
{
int err = -ENOMEM;
/* Allocate space for HMACS and CHUNKS authentication
* variables. There are arrays that we encode directly
* into parameters to make the rest of the operations easier.
*/
if (!ep->auth_hmacs_list) {
struct sctp_hmac_algo_param *auth_hmacs;
auth_hmacs = kzalloc(struct_size(auth_hmacs, hmac_ids,
SCTP_AUTH_NUM_HMACS), gfp);
if (!auth_hmacs)
goto nomem;
/* Initialize the HMACS parameter.
* SCTP-AUTH: Section 3.3
* Every endpoint supporting SCTP chunk authentication MUST
* support the HMAC based on the SHA-1 algorithm.
*/
auth_hmacs->param_hdr.type = SCTP_PARAM_HMAC_ALGO;
auth_hmacs->param_hdr.length =
htons(sizeof(struct sctp_paramhdr) + 2);
auth_hmacs->hmac_ids[0] = htons(SCTP_AUTH_HMAC_ID_SHA1);
ep->auth_hmacs_list = auth_hmacs;
}
if (!ep->auth_chunk_list) {
struct sctp_chunks_param *auth_chunks;
auth_chunks = kzalloc(sizeof(*auth_chunks) +
SCTP_NUM_CHUNK_TYPES, gfp);
if (!auth_chunks)
goto nomem;
/* Initialize the CHUNKS parameter */
auth_chunks->param_hdr.type = SCTP_PARAM_CHUNKS;
auth_chunks->param_hdr.length =
htons(sizeof(struct sctp_paramhdr));
ep->auth_chunk_list = auth_chunks;
}
/* Allocate and initialize transorms arrays for supported
* HMACs.
*/
err = sctp_auth_init_hmacs(ep, gfp);
if (err)
goto nomem;
return 0;
nomem:
/* Free all allocations */
kfree(ep->auth_hmacs_list);
kfree(ep->auth_chunk_list);
ep->auth_hmacs_list = NULL;
ep->auth_chunk_list = NULL;
return err;
}
void sctp_auth_free(struct sctp_endpoint *ep)
{
kfree(ep->auth_hmacs_list);
kfree(ep->auth_chunk_list);
ep->auth_hmacs_list = NULL;
ep->auth_chunk_list = NULL;
sctp_auth_destroy_hmacs(ep->auth_hmacs);
ep->auth_hmacs = NULL;
}
| linux-master | net/sctp/auth.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2002, 2004
* Copyright (c) 2002 Intel Corp.
*
* This file is part of the SCTP kernel implementation
*
* Sysctl related interfaces for SCTP.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Mingqin Liu <[email protected]>
* Jon Grimm <[email protected]>
* Ardelle Fan <[email protected]>
* Ryan Layer <[email protected]>
* Sridhar Samudrala <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <net/sctp/structs.h>
#include <net/sctp/sctp.h>
#include <linux/sysctl.h>
static int timer_max = 86400000; /* ms in one day */
static int sack_timer_min = 1;
static int sack_timer_max = 500;
static int addr_scope_max = SCTP_SCOPE_POLICY_MAX;
static int rwnd_scale_max = 16;
static int rto_alpha_min = 0;
static int rto_beta_min = 0;
static int rto_alpha_max = 1000;
static int rto_beta_max = 1000;
static int pf_expose_max = SCTP_PF_EXPOSE_MAX;
static int ps_retrans_max = SCTP_PS_RETRANS_MAX;
static int udp_port_max = 65535;
static unsigned long max_autoclose_min = 0;
static unsigned long max_autoclose_max =
(MAX_SCHEDULE_TIMEOUT / HZ > UINT_MAX)
? UINT_MAX : MAX_SCHEDULE_TIMEOUT / HZ;
static int proc_sctp_do_hmac_alg(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos);
static int proc_sctp_do_rto_min(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos);
static int proc_sctp_do_rto_max(struct ctl_table *ctl, int write, void *buffer,
size_t *lenp, loff_t *ppos);
static int proc_sctp_do_udp_port(struct ctl_table *ctl, int write, void *buffer,
size_t *lenp, loff_t *ppos);
static int proc_sctp_do_alpha_beta(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos);
static int proc_sctp_do_auth(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos);
static int proc_sctp_do_probe_interval(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos);
static struct ctl_table sctp_table[] = {
{
.procname = "sctp_mem",
.data = &sysctl_sctp_mem,
.maxlen = sizeof(sysctl_sctp_mem),
.mode = 0644,
.proc_handler = proc_doulongvec_minmax
},
{
.procname = "sctp_rmem",
.data = &sysctl_sctp_rmem,
.maxlen = sizeof(sysctl_sctp_rmem),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "sctp_wmem",
.data = &sysctl_sctp_wmem,
.maxlen = sizeof(sysctl_sctp_wmem),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{ /* sentinel */ }
};
/* The following index defines are used in sctp_sysctl_net_register().
* If you add new items to the sctp_net_table, please ensure that
* the index values of these defines hold the same meaning indicated by
* their macro names when they appear in sctp_net_table.
*/
#define SCTP_RTO_MIN_IDX 0
#define SCTP_RTO_MAX_IDX 1
#define SCTP_PF_RETRANS_IDX 2
#define SCTP_PS_RETRANS_IDX 3
static struct ctl_table sctp_net_table[] = {
[SCTP_RTO_MIN_IDX] = {
.procname = "rto_min",
.data = &init_net.sctp.rto_min,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_sctp_do_rto_min,
.extra1 = SYSCTL_ONE,
.extra2 = &init_net.sctp.rto_max
},
[SCTP_RTO_MAX_IDX] = {
.procname = "rto_max",
.data = &init_net.sctp.rto_max,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_sctp_do_rto_max,
.extra1 = &init_net.sctp.rto_min,
.extra2 = &timer_max
},
[SCTP_PF_RETRANS_IDX] = {
.procname = "pf_retrans",
.data = &init_net.sctp.pf_retrans,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ZERO,
.extra2 = &init_net.sctp.ps_retrans,
},
[SCTP_PS_RETRANS_IDX] = {
.procname = "ps_retrans",
.data = &init_net.sctp.ps_retrans,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &init_net.sctp.pf_retrans,
.extra2 = &ps_retrans_max,
},
{
.procname = "rto_initial",
.data = &init_net.sctp.rto_initial,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ONE,
.extra2 = &timer_max
},
{
.procname = "rto_alpha_exp_divisor",
.data = &init_net.sctp.rto_alpha,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_sctp_do_alpha_beta,
.extra1 = &rto_alpha_min,
.extra2 = &rto_alpha_max,
},
{
.procname = "rto_beta_exp_divisor",
.data = &init_net.sctp.rto_beta,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_sctp_do_alpha_beta,
.extra1 = &rto_beta_min,
.extra2 = &rto_beta_max,
},
{
.procname = "max_burst",
.data = &init_net.sctp.max_burst,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ZERO,
.extra2 = SYSCTL_INT_MAX,
},
{
.procname = "cookie_preserve_enable",
.data = &init_net.sctp.cookie_preserve_enable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "cookie_hmac_alg",
.data = &init_net.sctp.sctp_hmac_alg,
.maxlen = 8,
.mode = 0644,
.proc_handler = proc_sctp_do_hmac_alg,
},
{
.procname = "valid_cookie_life",
.data = &init_net.sctp.valid_cookie_life,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ONE,
.extra2 = &timer_max
},
{
.procname = "sack_timeout",
.data = &init_net.sctp.sack_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &sack_timer_min,
.extra2 = &sack_timer_max,
},
{
.procname = "hb_interval",
.data = &init_net.sctp.hb_interval,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ONE,
.extra2 = &timer_max
},
{
.procname = "association_max_retrans",
.data = &init_net.sctp.max_retrans_association,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ONE,
.extra2 = SYSCTL_INT_MAX,
},
{
.procname = "path_max_retrans",
.data = &init_net.sctp.max_retrans_path,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ONE,
.extra2 = SYSCTL_INT_MAX,
},
{
.procname = "max_init_retransmits",
.data = &init_net.sctp.max_retrans_init,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ONE,
.extra2 = SYSCTL_INT_MAX,
},
{
.procname = "sndbuf_policy",
.data = &init_net.sctp.sndbuf_policy,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "rcvbuf_policy",
.data = &init_net.sctp.rcvbuf_policy,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "default_auto_asconf",
.data = &init_net.sctp.default_auto_asconf,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "addip_enable",
.data = &init_net.sctp.addip_enable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "addip_noauth_enable",
.data = &init_net.sctp.addip_noauth,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "prsctp_enable",
.data = &init_net.sctp.prsctp_enable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "reconf_enable",
.data = &init_net.sctp.reconf_enable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "auth_enable",
.data = &init_net.sctp.auth_enable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_sctp_do_auth,
},
{
.procname = "intl_enable",
.data = &init_net.sctp.intl_enable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "ecn_enable",
.data = &init_net.sctp.ecn_enable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "plpmtud_probe_interval",
.data = &init_net.sctp.probe_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_sctp_do_probe_interval,
},
{
.procname = "udp_port",
.data = &init_net.sctp.udp_port,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_sctp_do_udp_port,
.extra1 = SYSCTL_ZERO,
.extra2 = &udp_port_max,
},
{
.procname = "encap_port",
.data = &init_net.sctp.encap_port,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ZERO,
.extra2 = &udp_port_max,
},
{
.procname = "addr_scope_policy",
.data = &init_net.sctp.scope_policy,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ZERO,
.extra2 = &addr_scope_max,
},
{
.procname = "rwnd_update_shift",
.data = &init_net.sctp.rwnd_upd_shift,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.extra1 = SYSCTL_ONE,
.extra2 = &rwnd_scale_max,
},
{
.procname = "max_autoclose",
.data = &init_net.sctp.max_autoclose,
.maxlen = sizeof(unsigned long),
.mode = 0644,
.proc_handler = &proc_doulongvec_minmax,
.extra1 = &max_autoclose_min,
.extra2 = &max_autoclose_max,
},
#ifdef CONFIG_NET_L3_MASTER_DEV
{
.procname = "l3mdev_accept",
.data = &init_net.sctp.l3mdev_accept,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ZERO,
.extra2 = SYSCTL_ONE,
},
#endif
{
.procname = "pf_enable",
.data = &init_net.sctp.pf_enable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "pf_expose",
.data = &init_net.sctp.pf_expose,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ZERO,
.extra2 = &pf_expose_max,
},
{ /* sentinel */ }
};
static int proc_sctp_do_hmac_alg(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct net *net = current->nsproxy->net_ns;
struct ctl_table tbl;
bool changed = false;
char *none = "none";
char tmp[8] = {0};
int ret;
memset(&tbl, 0, sizeof(struct ctl_table));
if (write) {
tbl.data = tmp;
tbl.maxlen = sizeof(tmp);
} else {
tbl.data = net->sctp.sctp_hmac_alg ? : none;
tbl.maxlen = strlen(tbl.data);
}
ret = proc_dostring(&tbl, write, buffer, lenp, ppos);
if (write && ret == 0) {
#ifdef CONFIG_CRYPTO_MD5
if (!strncmp(tmp, "md5", 3)) {
net->sctp.sctp_hmac_alg = "md5";
changed = true;
}
#endif
#ifdef CONFIG_CRYPTO_SHA1
if (!strncmp(tmp, "sha1", 4)) {
net->sctp.sctp_hmac_alg = "sha1";
changed = true;
}
#endif
if (!strncmp(tmp, "none", 4)) {
net->sctp.sctp_hmac_alg = NULL;
changed = true;
}
if (!changed)
ret = -EINVAL;
}
return ret;
}
static int proc_sctp_do_rto_min(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct net *net = current->nsproxy->net_ns;
unsigned int min = *(unsigned int *) ctl->extra1;
unsigned int max = *(unsigned int *) ctl->extra2;
struct ctl_table tbl;
int ret, new_value;
memset(&tbl, 0, sizeof(struct ctl_table));
tbl.maxlen = sizeof(unsigned int);
if (write)
tbl.data = &new_value;
else
tbl.data = &net->sctp.rto_min;
ret = proc_dointvec(&tbl, write, buffer, lenp, ppos);
if (write && ret == 0) {
if (new_value > max || new_value < min)
return -EINVAL;
net->sctp.rto_min = new_value;
}
return ret;
}
static int proc_sctp_do_rto_max(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct net *net = current->nsproxy->net_ns;
unsigned int min = *(unsigned int *) ctl->extra1;
unsigned int max = *(unsigned int *) ctl->extra2;
struct ctl_table tbl;
int ret, new_value;
memset(&tbl, 0, sizeof(struct ctl_table));
tbl.maxlen = sizeof(unsigned int);
if (write)
tbl.data = &new_value;
else
tbl.data = &net->sctp.rto_max;
ret = proc_dointvec(&tbl, write, buffer, lenp, ppos);
if (write && ret == 0) {
if (new_value > max || new_value < min)
return -EINVAL;
net->sctp.rto_max = new_value;
}
return ret;
}
static int proc_sctp_do_alpha_beta(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
if (write)
pr_warn_once("Changing rto_alpha or rto_beta may lead to "
"suboptimal rtt/srtt estimations!\n");
return proc_dointvec_minmax(ctl, write, buffer, lenp, ppos);
}
static int proc_sctp_do_auth(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct net *net = current->nsproxy->net_ns;
struct ctl_table tbl;
int new_value, ret;
memset(&tbl, 0, sizeof(struct ctl_table));
tbl.maxlen = sizeof(unsigned int);
if (write)
tbl.data = &new_value;
else
tbl.data = &net->sctp.auth_enable;
ret = proc_dointvec(&tbl, write, buffer, lenp, ppos);
if (write && ret == 0) {
struct sock *sk = net->sctp.ctl_sock;
net->sctp.auth_enable = new_value;
/* Update the value in the control socket */
lock_sock(sk);
sctp_sk(sk)->ep->auth_enable = new_value;
release_sock(sk);
}
return ret;
}
static int proc_sctp_do_udp_port(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct net *net = current->nsproxy->net_ns;
unsigned int min = *(unsigned int *)ctl->extra1;
unsigned int max = *(unsigned int *)ctl->extra2;
struct ctl_table tbl;
int ret, new_value;
memset(&tbl, 0, sizeof(struct ctl_table));
tbl.maxlen = sizeof(unsigned int);
if (write)
tbl.data = &new_value;
else
tbl.data = &net->sctp.udp_port;
ret = proc_dointvec(&tbl, write, buffer, lenp, ppos);
if (write && ret == 0) {
struct sock *sk = net->sctp.ctl_sock;
if (new_value > max || new_value < min)
return -EINVAL;
net->sctp.udp_port = new_value;
sctp_udp_sock_stop(net);
if (new_value) {
ret = sctp_udp_sock_start(net);
if (ret)
net->sctp.udp_port = 0;
}
/* Update the value in the control socket */
lock_sock(sk);
sctp_sk(sk)->udp_port = htons(net->sctp.udp_port);
release_sock(sk);
}
return ret;
}
static int proc_sctp_do_probe_interval(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct net *net = current->nsproxy->net_ns;
struct ctl_table tbl;
int ret, new_value;
memset(&tbl, 0, sizeof(struct ctl_table));
tbl.maxlen = sizeof(unsigned int);
if (write)
tbl.data = &new_value;
else
tbl.data = &net->sctp.probe_interval;
ret = proc_dointvec(&tbl, write, buffer, lenp, ppos);
if (write && ret == 0) {
if (new_value && new_value < SCTP_PROBE_TIMER_MIN)
return -EINVAL;
net->sctp.probe_interval = new_value;
}
return ret;
}
int sctp_sysctl_net_register(struct net *net)
{
struct ctl_table *table;
int i;
table = kmemdup(sctp_net_table, sizeof(sctp_net_table), GFP_KERNEL);
if (!table)
return -ENOMEM;
for (i = 0; table[i].data; i++)
table[i].data += (char *)(&net->sctp) - (char *)&init_net.sctp;
table[SCTP_RTO_MIN_IDX].extra2 = &net->sctp.rto_max;
table[SCTP_RTO_MAX_IDX].extra1 = &net->sctp.rto_min;
table[SCTP_PF_RETRANS_IDX].extra2 = &net->sctp.ps_retrans;
table[SCTP_PS_RETRANS_IDX].extra1 = &net->sctp.pf_retrans;
net->sctp.sysctl_header = register_net_sysctl_sz(net, "net/sctp",
table,
ARRAY_SIZE(sctp_net_table));
if (net->sctp.sysctl_header == NULL) {
kfree(table);
return -ENOMEM;
}
return 0;
}
void sctp_sysctl_net_unregister(struct net *net)
{
struct ctl_table *table;
table = net->sctp.sysctl_header->ctl_table_arg;
unregister_net_sysctl_table(net->sctp.sysctl_header);
kfree(table);
}
static struct ctl_table_header *sctp_sysctl_header;
/* Sysctl registration. */
void sctp_sysctl_register(void)
{
sctp_sysctl_header = register_net_sysctl(&init_net, "net/sctp", sctp_table);
}
/* Sysctl deregistration. */
void sctp_sysctl_unregister(void)
{
unregister_net_sysctl_table(sctp_sysctl_header);
}
| linux-master | net/sctp/sysctl.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2002 Intel Corp.
* Copyright (c) 2002 Nokia Corp.
*
* This is part of the SCTP Linux Kernel Implementation.
*
* These are the state functions for the state machine.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Mathew Kotowsky <[email protected]>
* Sridhar Samudrala <[email protected]>
* Jon Grimm <[email protected]>
* Hui Huang <[email protected]>
* Dajiang Zhang <[email protected]>
* Daisy Chang <[email protected]>
* Ardelle Fan <[email protected]>
* Ryan Layer <[email protected]>
* Kevin Gao <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/inet_ecn.h>
#include <linux/skbuff.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/structs.h>
#define CREATE_TRACE_POINTS
#include <trace/events/sctp.h>
static struct sctp_packet *sctp_abort_pkt_new(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
const void *payload, size_t paylen);
static int sctp_eat_data(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_cmd_seq *commands);
static struct sctp_packet *sctp_ootb_pkt_new(
struct net *net,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk);
static void sctp_send_stale_cookie_err(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
struct sctp_cmd_seq *commands,
struct sctp_chunk *err_chunk);
static enum sctp_disposition sctp_sf_do_5_2_6_stale(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands);
static enum sctp_disposition sctp_sf_shut_8_4_5(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands);
static enum sctp_disposition sctp_sf_tabort_8_4_8(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands);
static enum sctp_disposition sctp_sf_new_encap_port(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands);
static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk);
static enum sctp_disposition sctp_stop_t1_and_abort(
struct net *net,
struct sctp_cmd_seq *commands,
__be16 error, int sk_err,
const struct sctp_association *asoc,
struct sctp_transport *transport);
static enum sctp_disposition sctp_sf_abort_violation(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
void *arg,
struct sctp_cmd_seq *commands,
const __u8 *payload,
const size_t paylen);
static enum sctp_disposition sctp_sf_violation_chunklen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands);
static enum sctp_disposition sctp_sf_violation_paramlen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg, void *ext,
struct sctp_cmd_seq *commands);
static enum sctp_disposition sctp_sf_violation_ctsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands);
static enum sctp_disposition sctp_sf_violation_chunk(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands);
static enum sctp_ierror sctp_sf_authenticate(
const struct sctp_association *asoc,
struct sctp_chunk *chunk);
static enum sctp_disposition __sctp_sf_do_9_1_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands);
static enum sctp_disposition
__sctp_sf_do_9_2_reshutack(struct net *net, const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type, void *arg,
struct sctp_cmd_seq *commands);
/* Small helper function that checks if the chunk length
* is of the appropriate length. The 'required_length' argument
* is set to be the size of a specific chunk we are testing.
* Return Values: true = Valid length
* false = Invalid length
*
*/
static inline bool sctp_chunk_length_valid(struct sctp_chunk *chunk,
__u16 required_length)
{
__u16 chunk_length = ntohs(chunk->chunk_hdr->length);
/* Previously already marked? */
if (unlikely(chunk->pdiscard))
return false;
if (unlikely(chunk_length < required_length))
return false;
return true;
}
/* Check for format error in an ABORT chunk */
static inline bool sctp_err_chunk_valid(struct sctp_chunk *chunk)
{
struct sctp_errhdr *err;
sctp_walk_errors(err, chunk->chunk_hdr);
return (void *)err == (void *)chunk->chunk_end;
}
/**********************************************************
* These are the state functions for handling chunk events.
**********************************************************/
/*
* Process the final SHUTDOWN COMPLETE.
*
* Section: 4 (C) (diagram), 9.2
* Upon reception of the SHUTDOWN COMPLETE chunk the endpoint will verify
* that it is in SHUTDOWN-ACK-SENT state, if it is not the chunk should be
* discarded. If the endpoint is in the SHUTDOWN-ACK-SENT state the endpoint
* should stop the T2-shutdown timer and remove all knowledge of the
* association (and thus the association enters the CLOSED state).
*
* Verification Tag: 8.5.1(C), sctpimpguide 2.41.
* C) Rules for packet carrying SHUTDOWN COMPLETE:
* ...
* - The receiver of a SHUTDOWN COMPLETE shall accept the packet
* if the Verification Tag field of the packet matches its own tag and
* the T bit is not set
* OR
* it is set to its peer's tag and the T bit is set in the Chunk
* Flags.
* Otherwise, the receiver MUST silently discard the packet
* and take no further action. An endpoint MUST ignore the
* SHUTDOWN COMPLETE if it is not in the SHUTDOWN-ACK-SENT state.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_4_C(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg, struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 2960 6.10 Bundling
*
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*/
if (!chunk->singleton)
return sctp_sf_violation_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN_COMPLETE chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_chunkhdr)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* RFC 2960 10.2 SCTP-to-ULP
*
* H) SHUTDOWN COMPLETE notification
*
* When SCTP completes the shutdown procedures (section 9.2) this
* notification is passed to the upper layer.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_SHUTDOWN_COMP,
0, 0, 0, NULL, GFP_ATOMIC);
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
/* Upon reception of the SHUTDOWN COMPLETE chunk the endpoint
* will verify that it is in SHUTDOWN-ACK-SENT state, if it is
* not the chunk should be discarded. If the endpoint is in
* the SHUTDOWN-ACK-SENT state the endpoint should stop the
* T2-shutdown timer and remove all knowledge of the
* association (and thus the association enters the CLOSED
* state).
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
}
/*
* Respond to a normal INIT chunk.
* We are the side that is being asked for an association.
*
* Section: 5.1 Normal Establishment of an Association, B
* B) "Z" shall respond immediately with an INIT ACK chunk. The
* destination IP address of the INIT ACK MUST be set to the source
* IP address of the INIT to which this INIT ACK is responding. In
* the response, besides filling in other parameters, "Z" must set the
* Verification Tag field to Tag_A, and also provide its own
* Verification Tag (Tag_Z) in the Initiate Tag field.
*
* Verification Tag: Must be 0.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_5_1B_init(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg, *repl, *err_chunk;
struct sctp_unrecognized_param *unk_param;
struct sctp_association *new_asoc;
struct sctp_packet *packet;
int len;
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*
* IG Section 2.11.2
* Furthermore, we require that the receiver of an INIT chunk MUST
* enforce these rules by silently discarding an arriving packet
* with an INIT chunk that is bundled with other chunks.
*/
if (!chunk->singleton)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT chunk has a valid length.
* Normally, this would cause an ABORT with a Protocol Violation
* error, but since we don't have an association, we'll
* just discard the packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_init_chunk)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep) {
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
/* 3.1 A packet containing an INIT chunk MUST have a zero Verification
* Tag.
*/
if (chunk->sctp_hdr->vtag != 0)
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* If the INIT is coming toward a closing socket, we'll send back
* and ABORT. Essentially, this catches the race of INIT being
* backloged to the socket at the same time as the user issues close().
* Since the socket and all its associations are going away, we
* can treat this OOTB
*/
if (sctp_sstate(ep->base.sk, CLOSING))
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type,
(struct sctp_init_chunk *)chunk->chunk_hdr, chunk,
&err_chunk)) {
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes if there is any.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(struct sctp_chunkhdr),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(struct sctp_chunkhdr));
sctp_chunk_free(err_chunk);
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
return SCTP_DISPOSITION_CONSUME;
} else {
return SCTP_DISPOSITION_NOMEM;
}
} else {
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg,
commands);
}
}
/* Grab the INIT header. */
chunk->subh.init_hdr = (struct sctp_inithdr *)chunk->skb->data;
/* Tag the variable length parameters. */
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(struct sctp_inithdr));
new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC);
if (!new_asoc)
goto nomem;
/* Update socket peer label if first association. */
if (security_sctp_assoc_request(new_asoc, chunk->skb)) {
sctp_association_free(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (sctp_assoc_set_bind_addr_from_ep(new_asoc,
sctp_scope(sctp_source(chunk)),
GFP_ATOMIC) < 0)
goto nomem_init;
/* The call, sctp_process_init(), can fail on memory allocation. */
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk),
(struct sctp_init_chunk *)chunk->chunk_hdr,
GFP_ATOMIC))
goto nomem_init;
/* B) "Z" shall respond immediately with an INIT ACK chunk. */
/* If there are errors need to be reported for unknown parameters,
* make sure to reserve enough room in the INIT ACK for them.
*/
len = 0;
if (err_chunk)
len = ntohs(err_chunk->chunk_hdr->length) -
sizeof(struct sctp_chunkhdr);
repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len);
if (!repl)
goto nomem_init;
/* If there are errors need to be reported for unknown parameters,
* include them in the outgoing INIT ACK as "Unrecognized parameter"
* parameter.
*/
if (err_chunk) {
/* Get the "Unrecognized parameter" parameter(s) out of the
* ERROR chunk generated by sctp_verify_init(). Since the
* error cause code for "unknown parameter" and the
* "Unrecognized parameter" type is the same, we can
* construct the parameters in INIT ACK by copying the
* ERROR causes over.
*/
unk_param = (struct sctp_unrecognized_param *)
((__u8 *)(err_chunk->chunk_hdr) +
sizeof(struct sctp_chunkhdr));
/* Replace the cause code with the "Unrecognized parameter"
* parameter type.
*/
sctp_addto_chunk(repl, len, unk_param);
sctp_chunk_free(err_chunk);
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/*
* Note: After sending out INIT ACK with the State Cookie parameter,
* "Z" MUST NOT allocate any resources, nor keep any states for the
* new association. Otherwise, "Z" will be vulnerable to resource
* attacks.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
nomem_init:
sctp_association_free(new_asoc);
nomem:
if (err_chunk)
sctp_chunk_free(err_chunk);
return SCTP_DISPOSITION_NOMEM;
}
/*
* Respond to a normal INIT ACK chunk.
* We are the side that is initiating the association.
*
* Section: 5.1 Normal Establishment of an Association, C
* C) Upon reception of the INIT ACK from "Z", "A" shall stop the T1-init
* timer and leave COOKIE-WAIT state. "A" shall then send the State
* Cookie received in the INIT ACK chunk in a COOKIE ECHO chunk, start
* the T1-cookie timer, and enter the COOKIE-ECHOED state.
*
* Note: The COOKIE ECHO chunk can be bundled with any pending outbound
* DATA chunks, but it MUST be the first chunk in the packet and
* until the COOKIE ACK is returned the sender MUST NOT send any
* other packets to the peer.
*
* Verification Tag: 3.3.3
* If the value of the Initiate Tag in a received INIT ACK chunk is
* found to be 0, the receiver MUST treat it as an error and close the
* association by transmitting an ABORT.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_5_1C_ack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_init_chunk *initchunk;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*/
if (!chunk->singleton)
return sctp_sf_violation_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT-ACK chunk has a valid length */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_initack_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Grab the INIT header. */
chunk->subh.init_hdr = (struct sctp_inithdr *)chunk->skb->data;
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type,
(struct sctp_init_chunk *)chunk->chunk_hdr, chunk,
&err_chunk)) {
enum sctp_error error = SCTP_ERROR_NO_RESOURCE;
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes. If there are no causes,
* then there wasn't enough memory. Just terminate
* the association.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(struct sctp_chunkhdr),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(struct sctp_chunkhdr));
sctp_chunk_free(err_chunk);
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
error = SCTP_ERROR_INV_PARAM;
}
}
/* SCTP-AUTH, Section 6.3:
* It should be noted that if the receiver wants to tear
* down an association in an authenticated way only, the
* handling of malformed packets should not result in
* tearing down the association.
*
* This means that if we only want to abort associations
* in an authenticated way (i.e AUTH+ABORT), then we
* can't destroy this association just because the packet
* was malformed.
*/
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
return sctp_stop_t1_and_abort(net, commands, error, ECONNREFUSED,
asoc, chunk->transport);
}
/* Tag the variable length parameters. Note that we never
* convert the parameters in an INIT chunk.
*/
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(struct sctp_inithdr));
initchunk = (struct sctp_init_chunk *)chunk->chunk_hdr;
sctp_add_cmd_sf(commands, SCTP_CMD_PEER_INIT,
SCTP_PEER_INIT(initchunk));
/* Reset init error count upon receipt of INIT-ACK. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_RESET, SCTP_NULL());
/* 5.1 C) "A" shall stop the T1-init timer and leave
* COOKIE-WAIT state. "A" shall then ... start the T1-cookie
* timer, and enter the COOKIE-ECHOED state.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_ECHOED));
/* SCTP-AUTH: generate the association shared keys so that
* we can potentially sign the COOKIE-ECHO.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_SHKEY, SCTP_NULL());
/* 5.1 C) "A" shall then send the State Cookie received in the
* INIT ACK chunk in a COOKIE ECHO chunk, ...
*/
/* If there is any errors to report, send the ERROR chunk generated
* for unknown parameters as well.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_COOKIE_ECHO,
SCTP_CHUNK(err_chunk));
return SCTP_DISPOSITION_CONSUME;
}
static bool sctp_auth_chunk_verify(struct net *net, struct sctp_chunk *chunk,
const struct sctp_association *asoc)
{
struct sctp_chunk auth;
if (!chunk->auth_chunk)
return true;
/* SCTP-AUTH: auth_chunk pointer is only set when the cookie-echo
* is supposed to be authenticated and we have to do delayed
* authentication. We've just recreated the association using
* the information in the cookie and now it's much easier to
* do the authentication.
*/
/* Make sure that we and the peer are AUTH capable */
if (!net->sctp.auth_enable || !asoc->peer.auth_capable)
return false;
/* set-up our fake chunk so that we can process it */
auth.skb = chunk->auth_chunk;
auth.asoc = chunk->asoc;
auth.sctp_hdr = chunk->sctp_hdr;
auth.chunk_hdr = (struct sctp_chunkhdr *)
skb_push(chunk->auth_chunk,
sizeof(struct sctp_chunkhdr));
skb_pull(chunk->auth_chunk, sizeof(struct sctp_chunkhdr));
auth.transport = chunk->transport;
return sctp_sf_authenticate(asoc, &auth) == SCTP_IERROR_NO_ERROR;
}
/*
* Respond to a normal COOKIE ECHO chunk.
* We are the side that is being asked for an association.
*
* Section: 5.1 Normal Establishment of an Association, D
* D) Upon reception of the COOKIE ECHO chunk, Endpoint "Z" will reply
* with a COOKIE ACK chunk after building a TCB and moving to
* the ESTABLISHED state. A COOKIE ACK chunk may be bundled with
* any pending DATA chunks (and/or SACK chunks), but the COOKIE ACK
* chunk MUST be the first chunk in the packet.
*
* IMPLEMENTATION NOTE: An implementation may choose to send the
* Communication Up notification to the SCTP user upon reception
* of a valid COOKIE ECHO chunk.
*
* Verification Tag: 8.5.1 Exceptions in Verification Tag Rules
* D) Rules for packet carrying a COOKIE ECHO
*
* - When sending a COOKIE ECHO, the endpoint MUST use the value of the
* Initial Tag received in the INIT ACK.
*
* - The receiver of a COOKIE ECHO follows the procedures in Section 5.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_5_1D_ce(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_ulpevent *ev, *ai_ev = NULL, *auth_ev = NULL;
struct sctp_association *new_asoc;
struct sctp_init_chunk *peer_init;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *err_chk_p;
struct sctp_chunk *repl;
struct sock *sk;
int error = 0;
if (asoc && !sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep) {
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
/* Make sure that the COOKIE_ECHO chunk has a valid length.
* In this case, we check that we have enough for at least a
* chunk header. More detailed verification is done
* in sctp_unpack_cookie().
*/
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_chunkhdr)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* If the endpoint is not listening or if the number of associations
* on the TCP-style socket exceed the max backlog, respond with an
* ABORT.
*/
sk = ep->base.sk;
if (!sctp_sstate(sk, LISTENING) ||
(sctp_style(sk, TCP) && sk_acceptq_is_full(sk)))
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr =
(struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(struct sctp_chunkhdr)))
goto nomem;
/* 5.1 D) Upon reception of the COOKIE ECHO chunk, Endpoint
* "Z" will reply with a COOKIE ACK chunk after building a TCB
* and moving to the ESTABLISHED state.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -SCTP_IERROR_STALE_COOKIE:
sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
if (security_sctp_assoc_request(new_asoc, chunk->head_skb ?: chunk->skb)) {
sctp_association_free(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Delay state machine commands until later.
*
* Re-build the bind address for the association is done in
* the sctp_unpack_cookie() already.
*/
/* This is a brand-new association, so these are not yet side
* effects--it is safe to run them here.
*/
peer_init = (struct sctp_init_chunk *)(chunk->subh.cookie_hdr + 1);
if (!sctp_process_init(new_asoc, chunk,
&chunk->subh.cookie_hdr->c.peer_addr,
peer_init, GFP_ATOMIC))
goto nomem_init;
/* SCTP-AUTH: Now that we've populate required fields in
* sctp_process_init, set up the association shared keys as
* necessary so that we can potentially authenticate the ACK
*/
error = sctp_auth_asoc_init_active_key(new_asoc, GFP_ATOMIC);
if (error)
goto nomem_init;
if (!sctp_auth_chunk_verify(net, chunk, new_asoc)) {
sctp_association_free(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem_init;
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*/
ev = sctp_ulpevent_make_assoc_change(new_asoc, 0, SCTP_COMM_UP, 0,
new_asoc->c.sinit_num_ostreams,
new_asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (new_asoc->peer.adaptation_ind) {
ai_ev = sctp_ulpevent_make_adaptation_indication(new_asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem_aiev;
}
if (!new_asoc->peer.auth_capable) {
auth_ev = sctp_ulpevent_make_authkey(new_asoc, 0,
SCTP_AUTH_NO_AUTH,
GFP_ATOMIC);
if (!auth_ev)
goto nomem_authev;
}
/* Add all the state machine commands now since we've created
* everything. This way we don't introduce memory corruptions
* during side-effect processing and correctly count established
* associations.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_PASSIVEESTABS);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
if (new_asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* This will send the COOKIE ACK */
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* Queue the ASSOC_CHANGE event */
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Send up the Adaptation Layer Indication event */
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
if (auth_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(auth_ev));
return SCTP_DISPOSITION_CONSUME;
nomem_authev:
sctp_ulpevent_free(ai_ev);
nomem_aiev:
sctp_ulpevent_free(ev);
nomem_ev:
sctp_chunk_free(repl);
nomem_init:
sctp_association_free(new_asoc);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Respond to a normal COOKIE ACK chunk.
* We are the side that is asking for an association.
*
* RFC 2960 5.1 Normal Establishment of an Association
*
* E) Upon reception of the COOKIE ACK, endpoint "A" will move from the
* COOKIE-ECHOED state to the ESTABLISHED state, stopping the T1-cookie
* timer. It may also notify its ULP about the successful
* establishment of the association with a Communication Up
* notification (see Section 10).
*
* Verification Tag:
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_5_1E_ca(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Set peer label for connection. */
if (security_sctp_assoc_established((struct sctp_association *)asoc,
chunk->head_skb ?: chunk->skb))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Verify that the chunk length for the COOKIE-ACK is OK.
* If we don't do this, any bundled chunks may be junked.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_chunkhdr)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Reset init error count upon receipt of COOKIE-ACK,
* to avoid problems with the management of this
* counter in stale cookie situations when a transition back
* from the COOKIE-ECHOED state to the COOKIE-WAIT
* state is performed.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_RESET, SCTP_NULL());
/* RFC 2960 5.1 Normal Establishment of an Association
*
* E) Upon reception of the COOKIE ACK, endpoint "A" will move
* from the COOKIE-ECHOED state to the ESTABLISHED state,
* stopping the T1-cookie timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_ACTIVEESTABS);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* It may also notify its ULP about the successful
* establishment of the association with a Communication Up
* notification (see Section 10).
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_COMM_UP,
0, asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (asoc->peer.adaptation_ind) {
ev = sctp_ulpevent_make_adaptation_indication(asoc, GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
if (!asoc->peer.auth_capable) {
ev = sctp_ulpevent_make_authkey(asoc, 0, SCTP_AUTH_NO_AUTH,
GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Generate and sendout a heartbeat packet. */
static enum sctp_disposition sctp_sf_heartbeat(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_transport *transport = (struct sctp_transport *) arg;
struct sctp_chunk *reply;
/* Send a heartbeat to our peer. */
reply = sctp_make_heartbeat(asoc, transport, 0);
if (!reply)
return SCTP_DISPOSITION_NOMEM;
/* Set rto_pending indicating that an RTT measurement
* is started with this heartbeat chunk.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_RTO_PENDING,
SCTP_TRANSPORT(transport));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
}
/* Generate a HEARTBEAT packet on the given transport. */
enum sctp_disposition sctp_sf_sendbeat_8_3(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_transport *transport = (struct sctp_transport *) arg;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
/* Section 3.3.5.
* The Sender-specific Heartbeat Info field should normally include
* information about the sender's current time when this HEARTBEAT
* chunk is sent and the destination transport address to which this
* HEARTBEAT is sent (see Section 8.3).
*/
if (transport->param_flags & SPP_HB_ENABLE) {
if (SCTP_DISPOSITION_NOMEM ==
sctp_sf_heartbeat(ep, asoc, type, arg,
commands))
return SCTP_DISPOSITION_NOMEM;
/* Set transport error counter and association error counter
* when sending heartbeat.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT,
SCTP_TRANSPORT(transport));
}
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_IDLE,
SCTP_TRANSPORT(transport));
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMER_UPDATE,
SCTP_TRANSPORT(transport));
return SCTP_DISPOSITION_CONSUME;
}
/* resend asoc strreset_chunk. */
enum sctp_disposition sctp_sf_send_reconf(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_transport *transport = arg;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
sctp_chunk_hold(asoc->strreset_chunk);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(asoc->strreset_chunk));
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport));
return SCTP_DISPOSITION_CONSUME;
}
/* send hb chunk with padding for PLPMUTD. */
enum sctp_disposition sctp_sf_send_probe(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_transport *transport = (struct sctp_transport *)arg;
struct sctp_chunk *reply;
if (!sctp_transport_pl_enabled(transport))
return SCTP_DISPOSITION_CONSUME;
sctp_transport_pl_send(transport);
reply = sctp_make_heartbeat(asoc, transport, transport->pl.probe_size);
if (!reply)
return SCTP_DISPOSITION_NOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
sctp_add_cmd_sf(commands, SCTP_CMD_PROBE_TIMER_UPDATE,
SCTP_TRANSPORT(transport));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an heartbeat request.
*
* Section: 8.3 Path Heartbeat
* The receiver of the HEARTBEAT should immediately respond with a
* HEARTBEAT ACK that contains the Heartbeat Information field copied
* from the received HEARTBEAT chunk.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* When receiving an SCTP packet, the endpoint MUST ensure that the
* value in the Verification Tag field of the received SCTP packet
* matches its own Tag. If the received Verification Tag value does not
* match the receiver's own tag value, the receiver shall silently
* discard the packet and shall not process it any further except for
* those cases listed in Section 8.5.1 below.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_beat_8_3(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg, struct sctp_cmd_seq *commands)
{
struct sctp_paramhdr *param_hdr;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
size_t paylen = 0;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the HEARTBEAT chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk,
sizeof(struct sctp_heartbeat_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* 8.3 The receiver of the HEARTBEAT should immediately
* respond with a HEARTBEAT ACK that contains the Heartbeat
* Information field copied from the received HEARTBEAT chunk.
*/
chunk->subh.hb_hdr = (struct sctp_heartbeathdr *)chunk->skb->data;
param_hdr = (struct sctp_paramhdr *)chunk->subh.hb_hdr;
paylen = ntohs(chunk->chunk_hdr->length) - sizeof(struct sctp_chunkhdr);
if (ntohs(param_hdr->length) > paylen)
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
param_hdr, commands);
if (!pskb_pull(chunk->skb, paylen))
goto nomem;
reply = sctp_make_heartbeat_ack(asoc, chunk, param_hdr, paylen);
if (!reply)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process the returning HEARTBEAT ACK.
*
* Section: 8.3 Path Heartbeat
* Upon the receipt of the HEARTBEAT ACK, the sender of the HEARTBEAT
* should clear the error counter of the destination transport
* address to which the HEARTBEAT was sent, and mark the destination
* transport address as active if it is not so marked. The endpoint may
* optionally report to the upper layer when an inactive destination
* address is marked as active due to the reception of the latest
* HEARTBEAT ACK. The receiver of the HEARTBEAT ACK must also
* clear the association overall error count as well (as defined
* in section 8.1).
*
* The receiver of the HEARTBEAT ACK should also perform an RTT
* measurement for that destination transport address using the time
* value carried in the HEARTBEAT ACK chunk.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_backbeat_8_3(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_sender_hb_info *hbinfo;
struct sctp_chunk *chunk = arg;
struct sctp_transport *link;
unsigned long max_interval;
union sctp_addr from_addr;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the HEARTBEAT-ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_chunkhdr) +
sizeof(*hbinfo)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
hbinfo = (struct sctp_sender_hb_info *)chunk->skb->data;
/* Make sure that the length of the parameter is what we expect */
if (ntohs(hbinfo->param_hdr.length) != sizeof(*hbinfo))
return SCTP_DISPOSITION_DISCARD;
from_addr = hbinfo->daddr;
link = sctp_assoc_lookup_paddr(asoc, &from_addr);
/* This should never happen, but lets log it if so. */
if (unlikely(!link)) {
if (from_addr.sa.sa_family == AF_INET6) {
net_warn_ratelimited("%s association %p could not find address %pI6\n",
__func__,
asoc,
&from_addr.v6.sin6_addr);
} else {
net_warn_ratelimited("%s association %p could not find address %pI4\n",
__func__,
asoc,
&from_addr.v4.sin_addr.s_addr);
}
return SCTP_DISPOSITION_DISCARD;
}
/* Validate the 64-bit random nonce. */
if (hbinfo->hb_nonce != link->hb_nonce)
return SCTP_DISPOSITION_DISCARD;
if (hbinfo->probe_size) {
if (hbinfo->probe_size != link->pl.probe_size ||
!sctp_transport_pl_enabled(link))
return SCTP_DISPOSITION_DISCARD;
if (sctp_transport_pl_recv(link))
return SCTP_DISPOSITION_CONSUME;
return sctp_sf_send_probe(net, ep, asoc, type, link, commands);
}
max_interval = link->hbinterval + link->rto;
/* Check if the timestamp looks valid. */
if (time_after(hbinfo->sent_at, jiffies) ||
time_after(jiffies, hbinfo->sent_at + max_interval)) {
pr_debug("%s: HEARTBEAT ACK with invalid timestamp received "
"for transport:%p\n", __func__, link);
return SCTP_DISPOSITION_DISCARD;
}
/* 8.3 Upon the receipt of the HEARTBEAT ACK, the sender of
* the HEARTBEAT should clear the error counter of the
* destination transport address to which the HEARTBEAT was
* sent and mark the destination transport address as active if
* it is not so marked.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_ON, SCTP_TRANSPORT(link));
return SCTP_DISPOSITION_CONSUME;
}
/* Helper function to send out an abort for the restart
* condition.
*/
static int sctp_sf_send_restart_abort(struct net *net, union sctp_addr *ssa,
struct sctp_chunk *init,
struct sctp_cmd_seq *commands)
{
struct sctp_af *af = sctp_get_af_specific(ssa->v4.sin_family);
union sctp_addr_param *addrparm;
struct sctp_errhdr *errhdr;
char buffer[sizeof(*errhdr) + sizeof(*addrparm)];
struct sctp_endpoint *ep;
struct sctp_packet *pkt;
int len;
/* Build the error on the stack. We are way to malloc crazy
* throughout the code today.
*/
errhdr = (struct sctp_errhdr *)buffer;
addrparm = (union sctp_addr_param *)(errhdr + 1);
/* Copy into a parm format. */
len = af->to_addr_param(ssa, addrparm);
len += sizeof(*errhdr);
errhdr->cause = SCTP_ERROR_RESTART;
errhdr->length = htons(len);
/* Assign to the control socket. */
ep = sctp_sk(net->sctp.ctl_sock)->ep;
/* Association is NULL since this may be a restart attack and we
* want to send back the attacker's vtag.
*/
pkt = sctp_abort_pkt_new(net, ep, NULL, init, errhdr, len);
if (!pkt)
goto out;
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(pkt));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
/* Discard the rest of the inbound packet. */
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
out:
/* Even if there is no memory, treat as a failure so
* the packet will get dropped.
*/
return 0;
}
static bool list_has_sctp_addr(const struct list_head *list,
union sctp_addr *ipaddr)
{
struct sctp_transport *addr;
list_for_each_entry(addr, list, transports) {
if (sctp_cmp_addr_exact(ipaddr, &addr->ipaddr))
return true;
}
return false;
}
/* A restart is occurring, check to make sure no new addresses
* are being added as we may be under a takeover attack.
*/
static int sctp_sf_check_restart_addrs(const struct sctp_association *new_asoc,
const struct sctp_association *asoc,
struct sctp_chunk *init,
struct sctp_cmd_seq *commands)
{
struct net *net = new_asoc->base.net;
struct sctp_transport *new_addr;
int ret = 1;
/* Implementor's Guide - Section 5.2.2
* ...
* Before responding the endpoint MUST check to see if the
* unexpected INIT adds new addresses to the association. If new
* addresses are added to the association, the endpoint MUST respond
* with an ABORT..
*/
/* Search through all current addresses and make sure
* we aren't adding any new ones.
*/
list_for_each_entry(new_addr, &new_asoc->peer.transport_addr_list,
transports) {
if (!list_has_sctp_addr(&asoc->peer.transport_addr_list,
&new_addr->ipaddr)) {
sctp_sf_send_restart_abort(net, &new_addr->ipaddr, init,
commands);
ret = 0;
break;
}
}
/* Return success if all addresses were found. */
return ret;
}
/* Populate the verification/tie tags based on overlapping INIT
* scenario.
*
* Note: Do not use in CLOSED or SHUTDOWN-ACK-SENT state.
*/
static void sctp_tietags_populate(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
switch (asoc->state) {
/* 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State */
case SCTP_STATE_COOKIE_WAIT:
new_asoc->c.my_vtag = asoc->c.my_vtag;
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = 0;
break;
case SCTP_STATE_COOKIE_ECHOED:
new_asoc->c.my_vtag = asoc->c.my_vtag;
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = asoc->c.peer_vtag;
break;
/* 5.2.2 Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED,
* COOKIE-WAIT and SHUTDOWN-ACK-SENT
*/
default:
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = asoc->c.peer_vtag;
break;
}
/* Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of
* outbound streams) into the INIT ACK and cookie.
*/
new_asoc->rwnd = asoc->rwnd;
new_asoc->c.sinit_num_ostreams = asoc->c.sinit_num_ostreams;
new_asoc->c.sinit_max_instreams = asoc->c.sinit_max_instreams;
new_asoc->c.initial_tsn = asoc->c.initial_tsn;
}
/*
* Compare vtag/tietag values to determine unexpected COOKIE-ECHO
* handling action.
*
* RFC 2960 5.2.4 Handle a COOKIE ECHO when a TCB exists.
*
* Returns value representing action to be taken. These action values
* correspond to Action/Description values in RFC 2960, Table 2.
*/
static char sctp_tietags_compare(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
/* In this case, the peer may have restarted. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag != new_asoc->c.peer_vtag) &&
(asoc->c.my_vtag == new_asoc->c.my_ttag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_ttag))
return 'A';
/* Collision case B. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
((asoc->c.peer_vtag != new_asoc->c.peer_vtag) ||
(0 == asoc->c.peer_vtag))) {
return 'B';
}
/* Collision case D. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag))
return 'D';
/* Collision case C. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag) &&
(0 == new_asoc->c.my_ttag) &&
(0 == new_asoc->c.peer_ttag))
return 'C';
/* No match to any of the special cases; discard this packet. */
return 'E';
}
/* Common helper routine for both duplicate and simultaneous INIT
* chunk handling.
*/
static enum sctp_disposition sctp_sf_do_unexpected_init(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg, *repl, *err_chunk;
struct sctp_unrecognized_param *unk_param;
struct sctp_association *new_asoc;
enum sctp_disposition retval;
struct sctp_packet *packet;
int len;
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*
* IG Section 2.11.2
* Furthermore, we require that the receiver of an INIT chunk MUST
* enforce these rules by silently discarding an arriving packet
* with an INIT chunk that is bundled with other chunks.
*/
if (!chunk->singleton)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_init_chunk)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* 3.1 A packet containing an INIT chunk MUST have a zero Verification
* Tag.
*/
if (chunk->sctp_hdr->vtag != 0)
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
if (SCTP_INPUT_CB(chunk->skb)->encap_port != chunk->transport->encap_port)
return sctp_sf_new_encap_port(net, ep, asoc, type, arg, commands);
/* Grab the INIT header. */
chunk->subh.init_hdr = (struct sctp_inithdr *)chunk->skb->data;
/* Tag the variable length parameters. */
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(struct sctp_inithdr));
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type,
(struct sctp_init_chunk *)chunk->chunk_hdr, chunk,
&err_chunk)) {
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes if there is any.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(struct sctp_chunkhdr),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(struct sctp_chunkhdr));
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
retval = SCTP_DISPOSITION_CONSUME;
} else {
retval = SCTP_DISPOSITION_NOMEM;
}
goto cleanup;
} else {
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg,
commands);
}
}
/*
* Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of
* outbound streams) into the INIT ACK and cookie.
* FIXME: We are copying parameters from the endpoint not the
* association.
*/
new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC);
if (!new_asoc)
goto nomem;
/* Update socket peer label if first association. */
if (security_sctp_assoc_request(new_asoc, chunk->skb)) {
sctp_association_free(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (sctp_assoc_set_bind_addr_from_ep(new_asoc,
sctp_scope(sctp_source(chunk)), GFP_ATOMIC) < 0)
goto nomem;
/* In the outbound INIT ACK the endpoint MUST copy its current
* Verification Tag and Peers Verification tag into a reserved
* place (local tie-tag and per tie-tag) within the state cookie.
*/
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk),
(struct sctp_init_chunk *)chunk->chunk_hdr,
GFP_ATOMIC))
goto nomem;
/* Make sure no new addresses are being added during the
* restart. Do not do this check for COOKIE-WAIT state,
* since there are no peer addresses to check against.
* Upon return an ABORT will have been sent if needed.
*/
if (!sctp_state(asoc, COOKIE_WAIT)) {
if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk,
commands)) {
retval = SCTP_DISPOSITION_CONSUME;
goto nomem_retval;
}
}
sctp_tietags_populate(new_asoc, asoc);
/* B) "Z" shall respond immediately with an INIT ACK chunk. */
/* If there are errors need to be reported for unknown parameters,
* make sure to reserve enough room in the INIT ACK for them.
*/
len = 0;
if (err_chunk) {
len = ntohs(err_chunk->chunk_hdr->length) -
sizeof(struct sctp_chunkhdr);
}
repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len);
if (!repl)
goto nomem;
/* If there are errors need to be reported for unknown parameters,
* include them in the outgoing INIT ACK as "Unrecognized parameter"
* parameter.
*/
if (err_chunk) {
/* Get the "Unrecognized parameter" parameter(s) out of the
* ERROR chunk generated by sctp_verify_init(). Since the
* error cause code for "unknown parameter" and the
* "Unrecognized parameter" type is the same, we can
* construct the parameters in INIT ACK by copying the
* ERROR causes over.
*/
unk_param = (struct sctp_unrecognized_param *)
((__u8 *)(err_chunk->chunk_hdr) +
sizeof(struct sctp_chunkhdr));
/* Replace the cause code with the "Unrecognized parameter"
* parameter type.
*/
sctp_addto_chunk(repl, len, unk_param);
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/*
* Note: After sending out INIT ACK with the State Cookie parameter,
* "Z" MUST NOT allocate any resources for this new association.
* Otherwise, "Z" will be vulnerable to resource attacks.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
retval = SCTP_DISPOSITION_CONSUME;
return retval;
nomem:
retval = SCTP_DISPOSITION_NOMEM;
nomem_retval:
if (new_asoc)
sctp_association_free(new_asoc);
cleanup:
if (err_chunk)
sctp_chunk_free(err_chunk);
return retval;
}
/*
* Handle simultaneous INIT.
* This means we started an INIT and then we got an INIT request from
* our peer.
*
* Section: 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State (Item B)
* This usually indicates an initialization collision, i.e., each
* endpoint is attempting, at about the same time, to establish an
* association with the other endpoint.
*
* Upon receipt of an INIT in the COOKIE-WAIT or COOKIE-ECHOED state, an
* endpoint MUST respond with an INIT ACK using the same parameters it
* sent in its original INIT chunk (including its Verification Tag,
* unchanged). These original parameters are combined with those from the
* newly received INIT chunk. The endpoint shall also generate a State
* Cookie with the INIT ACK. The endpoint uses the parameters sent in its
* INIT to calculate the State Cookie.
*
* After that, the endpoint MUST NOT change its state, the T1-init
* timer shall be left running and the corresponding TCB MUST NOT be
* destroyed. The normal procedures for handling State Cookies when
* a TCB exists will resolve the duplicate INITs to a single association.
*
* For an endpoint that is in the COOKIE-ECHOED state it MUST populate
* its Tie-Tags with the Tag information of itself and its peer (see
* section 5.2.2 for a description of the Tie-Tags).
*
* Verification Tag: Not explicit, but an INIT can not have a valid
* verification tag, so we skip the check.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_5_2_1_siminit(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* Call helper to do the real work for both simultaneous and
* duplicate INIT chunk handling.
*/
return sctp_sf_do_unexpected_init(net, ep, asoc, type, arg, commands);
}
/*
* Handle duplicated INIT messages. These are usually delayed
* restransmissions.
*
* Section: 5.2.2 Unexpected INIT in States Other than CLOSED,
* COOKIE-ECHOED and COOKIE-WAIT
*
* Unless otherwise stated, upon reception of an unexpected INIT for
* this association, the endpoint shall generate an INIT ACK with a
* State Cookie. In the outbound INIT ACK the endpoint MUST copy its
* current Verification Tag and peer's Verification Tag into a reserved
* place within the state cookie. We shall refer to these locations as
* the Peer's-Tie-Tag and the Local-Tie-Tag. The outbound SCTP packet
* containing this INIT ACK MUST carry a Verification Tag value equal to
* the Initiation Tag found in the unexpected INIT. And the INIT ACK
* MUST contain a new Initiation Tag (randomly generated see Section
* 5.3.1). Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of outbound
* streams) into the INIT ACK and cookie.
*
* After sending out the INIT ACK, the endpoint shall take no further
* actions, i.e., the existing association, including its current state,
* and the corresponding TCB MUST NOT be changed.
*
* Note: Only when a TCB exists and the association is not in a COOKIE-
* WAIT state are the Tie-Tags populated. For a normal association INIT
* (i.e. the endpoint is in a COOKIE-WAIT state), the Tie-Tags MUST be
* set to 0 (indicating that no previous TCB existed). The INIT ACK and
* State Cookie are populated as specified in section 5.2.1.
*
* Verification Tag: Not specified, but an INIT has no way of knowing
* what the verification tag could be, so we ignore it.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_5_2_2_dupinit(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* Call helper to do the real work for both simultaneous and
* duplicate INIT chunk handling.
*/
return sctp_sf_do_unexpected_init(net, ep, asoc, type, arg, commands);
}
/*
* Unexpected INIT-ACK handler.
*
* Section 5.2.3
* If an INIT ACK received by an endpoint in any state other than the
* COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk.
* An unexpected INIT ACK usually indicates the processing of an old or
* duplicated INIT chunk.
*/
enum sctp_disposition sctp_sf_do_5_2_3_initack(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* Per the above section, we'll discard the chunk if we have an
* endpoint. If this is an OOTB INIT-ACK, treat it as such.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep)
return sctp_sf_ootb(net, ep, asoc, type, arg, commands);
else
return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);
}
static int sctp_sf_do_assoc_update(struct sctp_association *asoc,
struct sctp_association *new,
struct sctp_cmd_seq *cmds)
{
struct net *net = asoc->base.net;
struct sctp_chunk *abort;
if (!sctp_assoc_update(asoc, new))
return 0;
abort = sctp_make_abort(asoc, NULL, sizeof(struct sctp_errhdr));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0);
sctp_add_cmd_sf(cmds, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
}
sctp_add_cmd_sf(cmds, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(cmds, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_RSRC_LOW));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return -ENOMEM;
}
/* Unexpected COOKIE-ECHO handler for peer restart (Table 2, action 'A')
*
* Section 5.2.4
* A) In this case, the peer may have restarted.
*/
static enum sctp_disposition sctp_sf_do_dupcook_a(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_cmd_seq *commands,
struct sctp_association *new_asoc)
{
struct sctp_init_chunk *peer_init;
enum sctp_disposition disposition;
struct sctp_ulpevent *ev;
struct sctp_chunk *repl;
struct sctp_chunk *err;
/* new_asoc is a brand-new association, so these are not yet
* side effects--it is safe to run them here.
*/
peer_init = (struct sctp_init_chunk *)(chunk->subh.cookie_hdr + 1);
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init,
GFP_ATOMIC))
goto nomem;
if (sctp_auth_asoc_init_active_key(new_asoc, GFP_ATOMIC))
goto nomem;
if (!sctp_auth_chunk_verify(net, chunk, new_asoc))
return SCTP_DISPOSITION_DISCARD;
/* Make sure no new addresses are being added during the
* restart. Though this is a pretty complicated attack
* since you'd have to get inside the cookie.
*/
if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk, commands))
return SCTP_DISPOSITION_CONSUME;
/* If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes
* the peer has restarted (Action A), it MUST NOT setup a new
* association but instead resend the SHUTDOWN ACK and send an ERROR
* chunk with a "Cookie Received while Shutting Down" error cause to
* its peer.
*/
if (sctp_state(asoc, SHUTDOWN_ACK_SENT)) {
disposition = __sctp_sf_do_9_2_reshutack(net, ep, asoc,
SCTP_ST_CHUNK(chunk->chunk_hdr->type),
chunk, commands);
if (SCTP_DISPOSITION_NOMEM == disposition)
goto nomem;
err = sctp_make_op_error(asoc, chunk,
SCTP_ERROR_COOKIE_IN_SHUTDOWN,
NULL, 0, 0);
if (err)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
return SCTP_DISPOSITION_CONSUME;
}
/* For now, stop pending T3-rtx and SACK timers, fail any unsent/unacked
* data. Consider the optional choice of resending of this data.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_SACK));
sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_OUTQUEUE, SCTP_NULL());
/* Stop pending T4-rto timer, teardown ASCONF queue, ASCONF-ACK queue
* and ASCONF-ACK cache.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_ASCONF_QUEUE, SCTP_NULL());
/* Update the content of current association. */
if (sctp_sf_do_assoc_update((struct sctp_association *)asoc, new_asoc, commands))
goto nomem;
repl = sctp_make_cookie_ack(asoc, chunk);
if (!repl)
goto nomem;
/* Report association restart to upper layer. */
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_RESTART, 0,
asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
if ((sctp_state(asoc, SHUTDOWN_PENDING) ||
sctp_state(asoc, SHUTDOWN_SENT)) &&
(sctp_sstate(asoc->base.sk, CLOSING) ||
sock_flag(asoc->base.sk, SOCK_DEAD))) {
/* If the socket has been closed by user, don't
* transition to ESTABLISHED. Instead trigger SHUTDOWN
* bundled with COOKIE_ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
return sctp_sf_do_9_2_start_shutdown(net, ep, asoc,
SCTP_ST_CHUNK(0), repl,
commands);
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
}
return SCTP_DISPOSITION_CONSUME;
nomem_ev:
sctp_chunk_free(repl);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'B')
*
* Section 5.2.4
* B) In this case, both sides may be attempting to start an association
* at about the same time but the peer endpoint started its INIT
* after responding to the local endpoint's INIT
*/
/* This case represents an initialization collision. */
static enum sctp_disposition sctp_sf_do_dupcook_b(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_cmd_seq *commands,
struct sctp_association *new_asoc)
{
struct sctp_init_chunk *peer_init;
struct sctp_chunk *repl;
/* new_asoc is a brand-new association, so these are not yet
* side effects--it is safe to run them here.
*/
peer_init = (struct sctp_init_chunk *)(chunk->subh.cookie_hdr + 1);
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init,
GFP_ATOMIC))
goto nomem;
if (sctp_auth_asoc_init_active_key(new_asoc, GFP_ATOMIC))
goto nomem;
if (!sctp_auth_chunk_verify(net, chunk, new_asoc))
return SCTP_DISPOSITION_DISCARD;
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
if (asoc->state < SCTP_STATE_ESTABLISHED)
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
/* Update the content of current association. */
if (sctp_sf_do_assoc_update((struct sctp_association *)asoc, new_asoc, commands))
goto nomem;
repl = sctp_make_cookie_ack(asoc, chunk);
if (!repl)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*
* Sadly, this needs to be implemented as a side-effect, because
* we are not guaranteed to have set the association id of the real
* association and so these notifications need to be delayed until
* the association id is allocated.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_CHANGE, SCTP_U8(SCTP_COMM_UP));
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*
* This also needs to be done as a side effect for the same reason as
* above.
*/
if (asoc->peer.adaptation_ind)
sctp_add_cmd_sf(commands, SCTP_CMD_ADAPTATION_IND, SCTP_NULL());
if (!asoc->peer.auth_capable)
sctp_add_cmd_sf(commands, SCTP_CMD_PEER_NO_AUTH, SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'C')
*
* Section 5.2.4
* C) In this case, the local endpoint's cookie has arrived late.
* Before it arrived, the local endpoint sent an INIT and received an
* INIT-ACK and finally sent a COOKIE ECHO with the peer's same tag
* but a new tag of its own.
*/
/* This case represents an initialization collision. */
static enum sctp_disposition sctp_sf_do_dupcook_c(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_cmd_seq *commands,
struct sctp_association *new_asoc)
{
/* The cookie should be silently discarded.
* The endpoint SHOULD NOT change states and should leave
* any timers running.
*/
return SCTP_DISPOSITION_DISCARD;
}
/* Unexpected COOKIE-ECHO handler lost chunk (Table 2, action 'D')
*
* Section 5.2.4
*
* D) When both local and remote tags match the endpoint should always
* enter the ESTABLISHED state, if it has not already done so.
*/
/* This case represents an initialization collision. */
static enum sctp_disposition sctp_sf_do_dupcook_d(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_cmd_seq *commands,
struct sctp_association *new_asoc)
{
struct sctp_ulpevent *ev = NULL, *ai_ev = NULL, *auth_ev = NULL;
struct sctp_chunk *repl;
/* Clarification from Implementor's Guide:
* D) When both local and remote tags match the endpoint should
* enter the ESTABLISHED state, if it is in the COOKIE-ECHOED state.
* It should stop any cookie timer that may be running and send
* a COOKIE ACK.
*/
if (!sctp_auth_chunk_verify(net, chunk, asoc))
return SCTP_DISPOSITION_DISCARD;
/* Don't accidentally move back into established state. */
if (asoc->state < SCTP_STATE_ESTABLISHED) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START,
SCTP_NULL());
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose
* to send the Communication Up notification to the
* SCTP user upon reception of a valid COOKIE
* ECHO chunk.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0,
SCTP_COMM_UP, 0,
asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter,
* SCTP delivers this notification to inform the application
* that of the peers requested adaptation layer.
*/
if (asoc->peer.adaptation_ind) {
ai_ev = sctp_ulpevent_make_adaptation_indication(asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem;
}
if (!asoc->peer.auth_capable) {
auth_ev = sctp_ulpevent_make_authkey(asoc, 0,
SCTP_AUTH_NO_AUTH,
GFP_ATOMIC);
if (!auth_ev)
goto nomem;
}
}
repl = sctp_make_cookie_ack(asoc, chunk);
if (!repl)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
if (auth_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(auth_ev));
return SCTP_DISPOSITION_CONSUME;
nomem:
if (auth_ev)
sctp_ulpevent_free(auth_ev);
if (ai_ev)
sctp_ulpevent_free(ai_ev);
if (ev)
sctp_ulpevent_free(ev);
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle a duplicate COOKIE-ECHO. This usually means a cookie-carrying
* chunk was retransmitted and then delayed in the network.
*
* Section: 5.2.4 Handle a COOKIE ECHO when a TCB exists
*
* Verification Tag: None. Do cookie validation.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_5_2_4_dupcook(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_association *new_asoc;
struct sctp_chunk *chunk = arg;
enum sctp_disposition retval;
struct sctp_chunk *err_chk_p;
int error = 0;
char action;
/* Make sure that the chunk has a valid length from the protocol
* perspective. In this case check to make sure we have at least
* enough for the chunk header. Cookie length verification is
* done later.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_chunkhdr))) {
if (!sctp_vtag_verify(chunk, asoc))
asoc = NULL;
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands);
}
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(struct sctp_chunkhdr)))
goto nomem;
/* In RFC 2960 5.2.4 3, if both Verification Tags in the State Cookie
* of a duplicate COOKIE ECHO match the Verification Tags of the
* current association, consider the State Cookie valid even if
* the lifespan is exceeded.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -SCTP_IERROR_STALE_COOKIE:
sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
/* Update socket peer label if first association. */
if (security_sctp_assoc_request(new_asoc, chunk->head_skb ?: chunk->skb)) {
sctp_association_free(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Set temp so that it won't be added into hashtable */
new_asoc->temp = 1;
/* Compare the tie_tag in cookie with the verification tag of
* current association.
*/
action = sctp_tietags_compare(new_asoc, asoc);
switch (action) {
case 'A': /* Association restart. */
retval = sctp_sf_do_dupcook_a(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'B': /* Collision case B. */
retval = sctp_sf_do_dupcook_b(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'C': /* Collision case C. */
retval = sctp_sf_do_dupcook_c(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'D': /* Collision case D. */
retval = sctp_sf_do_dupcook_d(net, ep, asoc, chunk, commands,
new_asoc);
break;
default: /* Discard packet for all others. */
retval = sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
break;
}
/* Delete the temporary new association. */
sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
/* Restore association pointer to provide SCTP command interpreter
* with a valid context in case it needs to manipulate
* the queues */
sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC,
SCTP_ASOC((struct sctp_association *)asoc));
return retval;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process an ABORT. (SHUTDOWN-PENDING state)
*
* See sctp_sf_do_9_1_abort().
*/
enum sctp_disposition sctp_sf_shutdown_pending_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_abort_chunk)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!sctp_err_chunk_valid(chunk))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands);
}
/*
* Process an ABORT. (SHUTDOWN-SENT state)
*
* See sctp_sf_do_9_1_abort().
*/
enum sctp_disposition sctp_sf_shutdown_sent_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_abort_chunk)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!sctp_err_chunk_valid(chunk))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Stop the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands);
}
/*
* Process an ABORT. (SHUTDOWN-ACK-SENT state)
*
* See sctp_sf_do_9_1_abort().
*/
enum sctp_disposition sctp_sf_shutdown_ack_sent_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* The same T2 timer, so we should be able to use
* common function with the SHUTDOWN-SENT state.
*/
return sctp_sf_shutdown_sent_abort(net, ep, asoc, type, arg, commands);
}
/*
* Handle an Error received in COOKIE_ECHOED state.
*
* Only handle the error type of stale COOKIE Error, the other errors will
* be ignored.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_cookie_echoed_err(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_errhdr *err;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ERROR chunk has a valid length.
* The parameter walking depends on this as well.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_operr_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Process the error here */
/* FUTURE FIXME: When PR-SCTP related and other optional
* parms are emitted, this will have to change to handle multiple
* errors.
*/
sctp_walk_errors(err, chunk->chunk_hdr) {
if (SCTP_ERROR_STALE_COOKIE == err->cause)
return sctp_sf_do_5_2_6_stale(net, ep, asoc, type,
arg, commands);
}
/* It is possible to have malformed error causes, and that
* will cause us to end the walk early. However, since
* we are discarding the packet, there should be no adverse
* affects.
*/
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/*
* Handle a Stale COOKIE Error
*
* Section: 5.2.6 Handle Stale COOKIE Error
* If the association is in the COOKIE-ECHOED state, the endpoint may elect
* one of the following three alternatives.
* ...
* 3) Send a new INIT chunk to the endpoint, adding a Cookie
* Preservative parameter requesting an extension to the lifetime of
* the State Cookie. When calculating the time extension, an
* implementation SHOULD use the RTT information measured based on the
* previous COOKIE ECHO / ERROR exchange, and should add no more
* than 1 second beyond the measured RTT, due to long State Cookie
* lifetimes making the endpoint more subject to a replay attack.
*
* Verification Tag: Not explicit, but safe to ignore.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
static enum sctp_disposition sctp_sf_do_5_2_6_stale(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
int attempts = asoc->init_err_counter + 1;
struct sctp_chunk *chunk = arg, *reply;
struct sctp_cookie_preserve_param bht;
struct sctp_bind_addr *bp;
struct sctp_errhdr *err;
u32 stale;
if (attempts > asoc->max_init_attempts) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_STALE_COOKIE));
return SCTP_DISPOSITION_DELETE_TCB;
}
err = (struct sctp_errhdr *)(chunk->skb->data);
/* When calculating the time extension, an implementation
* SHOULD use the RTT information measured based on the
* previous COOKIE ECHO / ERROR exchange, and should add no
* more than 1 second beyond the measured RTT, due to long
* State Cookie lifetimes making the endpoint more subject to
* a replay attack.
* Measure of Staleness's unit is usec. (1/1000000 sec)
* Suggested Cookie Life-span Increment's unit is msec.
* (1/1000 sec)
* In general, if you use the suggested cookie life, the value
* found in the field of measure of staleness should be doubled
* to give ample time to retransmit the new cookie and thus
* yield a higher probability of success on the reattempt.
*/
stale = ntohl(*(__be32 *)((u8 *)err + sizeof(*err)));
stale = (stale * 2) / 1000;
bht.param_hdr.type = SCTP_PARAM_COOKIE_PRESERVATIVE;
bht.param_hdr.length = htons(sizeof(bht));
bht.lifespan_increment = htonl(stale);
/* Build that new INIT chunk. */
bp = (struct sctp_bind_addr *) &asoc->base.bind_addr;
reply = sctp_make_init(asoc, bp, GFP_ATOMIC, sizeof(bht));
if (!reply)
goto nomem;
sctp_addto_chunk(reply, sizeof(bht), &bht);
/* Clear peer's init_tag cached in assoc as we are sending a new INIT */
sctp_add_cmd_sf(commands, SCTP_CMD_CLEAR_INIT_TAG, SCTP_NULL());
/* Stop pending T3-rtx and heartbeat timers */
sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
/* Delete non-primary peer ip addresses since we are transitioning
* back to the COOKIE-WAIT state
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DEL_NON_PRIMARY, SCTP_NULL());
/* If we've sent any data bundled with COOKIE-ECHO we will need to
* resend
*/
sctp_add_cmd_sf(commands, SCTP_CMD_T1_RETRAN,
SCTP_TRANSPORT(asoc->peer.primary_path));
/* Cast away the const modifier, as we want to just
* rerun it through as a sideffect.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_INC, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_WAIT));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process an ABORT.
*
* Section: 9.1
* After checking the Verification Tag, the receiving endpoint shall
* remove the association from its record, and shall report the
* termination to its upper layer.
*
* Verification Tag: 8.5.1 Exceptions in Verification Tag Rules
* B) Rules for packet carrying ABORT:
*
* - The endpoint shall always fill in the Verification Tag field of the
* outbound packet with the destination endpoint's tag value if it
* is known.
*
* - If the ABORT is sent in response to an OOTB packet, the endpoint
* MUST follow the procedure described in Section 8.4.
*
* - The receiver MUST accept the packet if the Verification Tag
* matches either its own tag, OR the tag of its peer. Otherwise, the
* receiver MUST silently discard the packet and take no further
* action.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_9_1_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_abort_chunk)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!sctp_err_chunk_valid(chunk))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands);
}
static enum sctp_disposition __sctp_sf_do_9_1_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
__be16 error = SCTP_ERROR_NO_ERROR;
struct sctp_chunk *chunk = arg;
unsigned int len;
/* See if we have an error cause code in the chunk. */
len = ntohs(chunk->chunk_hdr->length);
if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr))
error = ((struct sctp_errhdr *)chunk->skb->data)->cause;
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNRESET));
/* ASSOC_FAILED will DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(error));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
/*
* Process an ABORT. (COOKIE-WAIT state)
*
* See sctp_sf_do_9_1_abort() above.
*/
enum sctp_disposition sctp_sf_cookie_wait_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
__be16 error = SCTP_ERROR_NO_ERROR;
struct sctp_chunk *chunk = arg;
unsigned int len;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_abort_chunk)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* See if we have an error cause code in the chunk. */
len = ntohs(chunk->chunk_hdr->length);
if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr))
error = ((struct sctp_errhdr *)chunk->skb->data)->cause;
return sctp_stop_t1_and_abort(net, commands, error, ECONNREFUSED, asoc,
chunk->transport);
}
/*
* Process an incoming ICMP as an ABORT. (COOKIE-WAIT state)
*/
enum sctp_disposition sctp_sf_cookie_wait_icmp_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
return sctp_stop_t1_and_abort(net, commands, SCTP_ERROR_NO_ERROR,
ENOPROTOOPT, asoc,
(struct sctp_transport *)arg);
}
/*
* Process an ABORT. (COOKIE-ECHOED state)
*/
enum sctp_disposition sctp_sf_cookie_echoed_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_abort(net, ep, asoc, type, arg, commands);
}
/*
* Stop T1 timer and abort association with "INIT failed".
*
* This is common code called by several sctp_sf_*_abort() functions above.
*/
static enum sctp_disposition sctp_stop_t1_and_abort(
struct net *net,
struct sctp_cmd_seq *commands,
__be16 error, int sk_err,
const struct sctp_association *asoc,
struct sctp_transport *transport)
{
pr_debug("%s: ABORT received (INIT)\n", __func__);
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(sk_err));
/* CMD_INIT_FAILED will DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(error));
return SCTP_DISPOSITION_ABORT;
}
/*
* sctp_sf_do_9_2_shut
*
* Section: 9.2
* Upon the reception of the SHUTDOWN, the peer endpoint shall
* - enter the SHUTDOWN-RECEIVED state,
*
* - stop accepting new data from its SCTP user
*
* - verify, by checking the Cumulative TSN Ack field of the chunk,
* that all its outstanding DATA chunks have been received by the
* SHUTDOWN sender.
*
* Once an endpoint as reached the SHUTDOWN-RECEIVED state it MUST NOT
* send a SHUTDOWN in response to a ULP request. And should discard
* subsequent SHUTDOWN chunks.
*
* If there are still outstanding DATA chunks left, the SHUTDOWN
* receiver shall continue to follow normal data transmission
* procedures defined in Section 6 until all outstanding DATA chunks
* are acknowledged; however, the SHUTDOWN receiver MUST NOT accept
* new data from its SCTP user.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_9_2_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
enum sctp_disposition disposition;
struct sctp_chunk *chunk = arg;
struct sctp_shutdownhdr *sdh;
struct sctp_ulpevent *ev;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_shutdown_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Convert the elaborate header. */
sdh = (struct sctp_shutdownhdr *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(*sdh));
chunk->subh.shutdown_hdr = sdh;
ctsn = ntohl(sdh->cum_tsn_ack);
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands);
/* API 5.3.1.5 SCTP_SHUTDOWN_EVENT
* When a peer sends a SHUTDOWN, SCTP delivers this notification to
* inform the application that it should cease sending data.
*/
ev = sctp_ulpevent_make_shutdown_event(asoc, 0, GFP_ATOMIC);
if (!ev) {
disposition = SCTP_DISPOSITION_NOMEM;
goto out;
}
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Upon the reception of the SHUTDOWN, the peer endpoint shall
* - enter the SHUTDOWN-RECEIVED state,
* - stop accepting new data from its SCTP user
*
* [This is implicit in the new state.]
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_RECEIVED));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_shutdown_ack(net, ep, asoc, type,
arg, commands);
}
if (SCTP_DISPOSITION_NOMEM == disposition)
goto out;
/* - verify, by checking the Cumulative TSN Ack field of the
* chunk, that all its outstanding DATA chunks have been
* received by the SHUTDOWN sender.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_CTSN,
SCTP_BE32(chunk->subh.shutdown_hdr->cum_tsn_ack));
out:
return disposition;
}
/*
* sctp_sf_do_9_2_shut_ctsn
*
* Once an endpoint has reached the SHUTDOWN-RECEIVED state,
* it MUST NOT send a SHUTDOWN in response to a ULP request.
* The Cumulative TSN Ack of the received SHUTDOWN chunk
* MUST be processed.
*/
enum sctp_disposition sctp_sf_do_9_2_shut_ctsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_shutdownhdr *sdh;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_shutdown_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
sdh = (struct sctp_shutdownhdr *)chunk->skb->data;
ctsn = ntohl(sdh->cum_tsn_ack);
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands);
/* verify, by checking the Cumulative TSN Ack field of the
* chunk, that all its outstanding DATA chunks have been
* received by the SHUTDOWN sender.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_CTSN,
SCTP_BE32(sdh->cum_tsn_ack));
return SCTP_DISPOSITION_CONSUME;
}
/* RFC 2960 9.2
* If an endpoint is in SHUTDOWN-ACK-SENT state and receives an INIT chunk
* (e.g., if the SHUTDOWN COMPLETE was lost) with source and destination
* transport addresses (either in the IP addresses or in the INIT chunk)
* that belong to this association, it should discard the INIT chunk and
* retransmit the SHUTDOWN ACK chunk.
*/
static enum sctp_disposition
__sctp_sf_do_9_2_reshutack(struct net *net, const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type, void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
/* Make sure that the chunk has a valid length */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_chunkhdr)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Since we are not going to really process this INIT, there
* is no point in verifying chunk boundaries. Just generate
* the SHUTDOWN ACK.
*/
reply = sctp_make_shutdown_ack(asoc, chunk);
if (NULL == reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-SHUTDOWN timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and restart the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
enum sctp_disposition
sctp_sf_do_9_2_reshutack(struct net *net, const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type, void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
if (!chunk->singleton)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_init_chunk)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (chunk->sctp_hdr->vtag != 0)
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
return __sctp_sf_do_9_2_reshutack(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_do_ecn_cwr
*
* Section: Appendix A: Explicit Congestion Notification
*
* CWR:
*
* RFC 2481 details a specific bit for a sender to send in the header of
* its next outbound TCP segment to indicate to its peer that it has
* reduced its congestion window. This is termed the CWR bit. For
* SCTP the same indication is made by including the CWR chunk.
* This chunk contains one data element, i.e. the TSN number that
* was sent in the ECNE chunk. This element represents the lowest
* TSN number in the datagram that was originally marked with the
* CE bit.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_ecn_cwr(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_cwrhdr *cwr;
u32 lowest_tsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_ecne_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
cwr = (struct sctp_cwrhdr *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(*cwr));
lowest_tsn = ntohl(cwr->lowest_tsn);
/* Does this CWR ack the last sent congestion notification? */
if (TSN_lte(asoc->last_ecne_tsn, lowest_tsn)) {
/* Stop sending ECNE. */
sctp_add_cmd_sf(commands,
SCTP_CMD_ECN_CWR,
SCTP_U32(lowest_tsn));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_do_ecne
*
* Section: Appendix A: Explicit Congestion Notification
*
* ECN-Echo
*
* RFC 2481 details a specific bit for a receiver to send back in its
* TCP acknowledgements to notify the sender of the Congestion
* Experienced (CE) bit having arrived from the network. For SCTP this
* same indication is made by including the ECNE chunk. This chunk
* contains one data element, i.e. the lowest TSN associated with the IP
* datagram marked with the CE bit.....
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_ecne(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg, struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ecnehdr *ecne;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_ecne_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
ecne = (struct sctp_ecnehdr *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(*ecne));
/* If this is a newer ECNE than the last CWR packet we sent out */
sctp_add_cmd_sf(commands, SCTP_CMD_ECN_ECNE,
SCTP_U32(ntohl(ecne->lowest_tsn)));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Section: 6.2 Acknowledgement on Reception of DATA Chunks
*
* The SCTP endpoint MUST always acknowledge the reception of each valid
* DATA chunk.
*
* The guidelines on delayed acknowledgement algorithm specified in
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
* acknowledgement SHOULD be generated for at least every second packet
* (not every second DATA chunk) received, and SHOULD be generated within
* 200 ms of the arrival of any unacknowledged DATA chunk. In some
* situations it may be beneficial for an SCTP transmitter to be more
* conservative than the algorithms detailed in this document allow.
* However, an SCTP transmitter MUST NOT be more aggressive than the
* following algorithms allow.
*
* A SCTP receiver MUST NOT generate more than one SACK for every
* incoming packet, other than to update the offered window as the
* receiving application consumes new data.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_eat_data_6_2(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
union sctp_arg force = SCTP_NOFORCE();
struct sctp_chunk *chunk = arg;
int error;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (!sctp_chunk_length_valid(chunk, sctp_datachk_len(&asoc->stream)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
error = sctp_eat_data(asoc, chunk, commands);
switch (error) {
case SCTP_IERROR_NO_ERROR:
break;
case SCTP_IERROR_HIGH_TSN:
case SCTP_IERROR_BAD_STREAM:
SCTP_INC_STATS(net, SCTP_MIB_IN_DATA_CHUNK_DISCARDS);
goto discard_noforce;
case SCTP_IERROR_DUP_TSN:
case SCTP_IERROR_IGNORE_TSN:
SCTP_INC_STATS(net, SCTP_MIB_IN_DATA_CHUNK_DISCARDS);
goto discard_force;
case SCTP_IERROR_NO_DATA:
return SCTP_DISPOSITION_ABORT;
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_abort_violation(net, ep, asoc, chunk, commands,
(u8 *)chunk->subh.data_hdr,
sctp_datahdr_len(&asoc->stream));
default:
BUG();
}
if (chunk->chunk_hdr->flags & SCTP_DATA_SACK_IMM)
force = SCTP_FORCE();
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
}
/* If this is the last chunk in a packet, we need to count it
* toward sack generation. Note that we need to SACK every
* OTHER packet containing data chunks, EVEN IF WE DISCARD
* THEM. We elect to NOT generate SACK's if the chunk fails
* the verification tag test.
*
* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks
*
* The SCTP endpoint MUST always acknowledge the reception of
* each valid DATA chunk.
*
* The guidelines on delayed acknowledgement algorithm
* specified in Section 4.2 of [RFC2581] SHOULD be followed.
* Specifically, an acknowledgement SHOULD be generated for at
* least every second packet (not every second DATA chunk)
* received, and SHOULD be generated within 200 ms of the
* arrival of any unacknowledged DATA chunk. In some
* situations it may be beneficial for an SCTP transmitter to
* be more conservative than the algorithms detailed in this
* document allow. However, an SCTP transmitter MUST NOT be
* more aggressive than the following algorithms allow.
*/
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force);
return SCTP_DISPOSITION_CONSUME;
discard_force:
/* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks
*
* When a packet arrives with duplicate DATA chunk(s) and with
* no new DATA chunk(s), the endpoint MUST immediately send a
* SACK with no delay. If a packet arrives with duplicate
* DATA chunk(s) bundled with new DATA chunks, the endpoint
* MAY immediately send a SACK. Normally receipt of duplicate
* DATA chunks will occur when the original SACK chunk was lost
* and the peer's RTO has expired. The duplicate TSN number(s)
* SHOULD be reported in the SACK as duplicate.
*/
/* In our case, we split the MAY SACK advice up whether or not
* the last chunk is a duplicate.'
*/
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
return SCTP_DISPOSITION_DISCARD;
discard_noforce:
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force);
return SCTP_DISPOSITION_DISCARD;
}
/*
* sctp_sf_eat_data_fast_4_4
*
* Section: 4 (4)
* (4) In SHUTDOWN-SENT state the endpoint MUST acknowledge any received
* DATA chunks without delay.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_eat_data_fast_4_4(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
int error;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (!sctp_chunk_length_valid(chunk, sctp_datachk_len(&asoc->stream)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
error = sctp_eat_data(asoc, chunk, commands);
switch (error) {
case SCTP_IERROR_NO_ERROR:
case SCTP_IERROR_HIGH_TSN:
case SCTP_IERROR_DUP_TSN:
case SCTP_IERROR_IGNORE_TSN:
case SCTP_IERROR_BAD_STREAM:
break;
case SCTP_IERROR_NO_DATA:
return SCTP_DISPOSITION_ABORT;
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_abort_violation(net, ep, asoc, chunk, commands,
(u8 *)chunk->subh.data_hdr,
sctp_datahdr_len(&asoc->stream));
default:
BUG();
}
/* Go a head and force a SACK, since we are shutting down. */
/* Implementor's Guide.
*
* While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
* respond to each received packet containing one or more DATA chunk(s)
* with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer
*/
if (chunk->end_of_packet) {
/* We must delay the chunk creation since the cumulative
* TSN has not been updated yet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SHUTDOWN, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* Section: 6.2 Processing a Received SACK
* D) Any time a SACK arrives, the endpoint performs the following:
*
* i) If Cumulative TSN Ack is less than the Cumulative TSN Ack Point,
* then drop the SACK. Since Cumulative TSN Ack is monotonically
* increasing, a SACK whose Cumulative TSN Ack is less than the
* Cumulative TSN Ack Point indicates an out-of-order SACK.
*
* ii) Set rwnd equal to the newly received a_rwnd minus the number
* of bytes still outstanding after processing the Cumulative TSN Ack
* and the Gap Ack Blocks.
*
* iii) If the SACK is missing a TSN that was previously
* acknowledged via a Gap Ack Block (e.g., the data receiver
* reneged on the data), then mark the corresponding DATA chunk
* as available for retransmit: Mark it as missing for fast
* retransmit as described in Section 7.2.4 and if no retransmit
* timer is running for the destination address to which the DATA
* chunk was originally transmitted, then T3-rtx is started for
* that destination address.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_eat_sack_6_2(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_sackhdr *sackh;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_sack_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Pull the SACK chunk from the data buffer */
sackh = sctp_sm_pull_sack(chunk);
/* Was this a bogus SACK? */
if (!sackh)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
chunk->subh.sack_hdr = sackh;
ctsn = ntohl(sackh->cum_tsn_ack);
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (TSN_lte(asoc->next_tsn, ctsn))
return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands);
trace_sctp_probe(ep, asoc, chunk);
/* i) If Cumulative TSN Ack is less than the Cumulative TSN
* Ack Point, then drop the SACK. Since Cumulative TSN
* Ack is monotonically increasing, a SACK whose
* Cumulative TSN Ack is less than the Cumulative TSN Ack
* Point indicates an out-of-order SACK.
*/
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* Return this SACK for further processing. */
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_SACK, SCTP_CHUNK(chunk));
/* Note: We do the rest of the work on the PROCESS_SACK
* sideeffect.
*/
return SCTP_DISPOSITION_CONSUME;
}
/*
* Generate an ABORT in response to a packet.
*
* Section: 8.4 Handle "Out of the blue" Packets, sctpimpguide 2.41
*
* 8) The receiver should respond to the sender of the OOTB packet with
* an ABORT. When sending the ABORT, the receiver of the OOTB packet
* MUST fill in the Verification Tag field of the outbound packet
* with the value found in the Verification Tag field of the OOTB
* packet and set the T-bit in the Chunk Flags to indicate that the
* Verification Tag is reflected. After sending this ABORT, the
* receiver of the OOTB packet shall discard the OOTB packet and take
* no further action.
*
* Verification Tag:
*
* The return value is the disposition of the chunk.
*/
static enum sctp_disposition sctp_sf_tabort_8_4_8(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (!packet)
return SCTP_DISPOSITION_NOMEM;
/* Make an ABORT. The T bit will be set if the asoc
* is NULL.
*/
abort = sctp_make_abort(asoc, chunk, 0);
if (!abort) {
sctp_ootb_pkt_free(packet);
return SCTP_DISPOSITION_NOMEM;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Set the skb to the belonging sock for accounting. */
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return SCTP_DISPOSITION_CONSUME;
}
/* Handling of SCTP Packets Containing an INIT Chunk Matching an
* Existing Associations when the UDP encap port is incorrect.
*
* From Section 4 at draft-tuexen-tsvwg-sctp-udp-encaps-cons-03.
*/
static enum sctp_disposition sctp_sf_new_encap_port(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (!packet)
return SCTP_DISPOSITION_NOMEM;
abort = sctp_make_new_encap_port(asoc, chunk);
if (!abort) {
sctp_ootb_pkt_free(packet);
return SCTP_DISPOSITION_NOMEM;
}
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return SCTP_DISPOSITION_CONSUME;
}
/*
* Received an ERROR chunk from peer. Generate SCTP_REMOTE_ERROR
* event as ULP notification for each cause included in the chunk.
*
* API 5.3.1.3 - SCTP_REMOTE_ERROR
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_operr_notify(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_errhdr *err;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ERROR chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_operr_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
sctp_walk_errors(err, chunk->chunk_hdr);
if ((void *)err != (void *)chunk->chunk_end)
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)err, commands);
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_OPERR,
SCTP_CHUNK(chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an inbound SHUTDOWN ACK.
*
* From Section 9.2:
* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall
* stop the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its
* peer, and remove all record of the association.
*
* The return value is the disposition.
*/
enum sctp_disposition sctp_sf_do_9_2_final(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN_ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_chunkhdr)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* 10.2 H) SHUTDOWN COMPLETE notification
*
* When SCTP completes the shutdown procedures (section 9.2) this
* notification is passed to the upper layer.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_SHUTDOWN_COMP,
0, 0, 0, NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
/* ...send a SHUTDOWN COMPLETE chunk to its peer, */
reply = sctp_make_shutdown_complete(asoc, chunk);
if (!reply)
goto nomem_chunk;
/* Do all the commands now (after allocation), so that we
* have consistent state if memory allocation fails
*/
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall
* stop the T2-shutdown timer,
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
/* ...and remove all record of the association. */
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
nomem_chunk:
sctp_ulpevent_free(ev);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets, sctpimpguide 2.41.
*
* 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should
* respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE.
* When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
* packet must fill in the Verification Tag field of the outbound
* packet with the Verification Tag received in the SHUTDOWN ACK and
* set the T-bit in the Chunk Flags to indicate that the Verification
* Tag is reflected.
*
* 8) The receiver should respond to the sender of the OOTB packet with
* an ABORT. When sending the ABORT, the receiver of the OOTB packet
* MUST fill in the Verification Tag field of the outbound packet
* with the value found in the Verification Tag field of the OOTB
* packet and set the T-bit in the Chunk Flags to indicate that the
* Verification Tag is reflected. After sending this ABORT, the
* receiver of the OOTB packet shall discard the OOTB packet and take
* no further action.
*/
enum sctp_disposition sctp_sf_ootb(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg, struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sk_buff *skb = chunk->skb;
struct sctp_chunkhdr *ch;
struct sctp_errhdr *err;
int ootb_cookie_ack = 0;
int ootb_shut_ack = 0;
__u8 *ch_end;
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
if (asoc && !sctp_vtag_verify(chunk, asoc))
asoc = NULL;
ch = (struct sctp_chunkhdr *)chunk->chunk_hdr;
do {
/* Report violation if the chunk is less then minimal */
if (ntohs(ch->length) < sizeof(*ch))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Report violation if chunk len overflows */
ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Now that we know we at least have a chunk header,
* do things that are type appropriate.
*/
if (SCTP_CID_SHUTDOWN_ACK == ch->type)
ootb_shut_ack = 1;
/* RFC 2960, Section 3.3.7
* Moreover, under any circumstances, an endpoint that
* receives an ABORT MUST NOT respond to that ABORT by
* sending an ABORT of its own.
*/
if (SCTP_CID_ABORT == ch->type)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR
* or a COOKIE ACK the SCTP Packet should be silently
* discarded.
*/
if (SCTP_CID_COOKIE_ACK == ch->type)
ootb_cookie_ack = 1;
if (SCTP_CID_ERROR == ch->type) {
sctp_walk_errors(err, ch) {
if (SCTP_ERROR_STALE_COOKIE == err->cause) {
ootb_cookie_ack = 1;
break;
}
}
}
ch = (struct sctp_chunkhdr *)ch_end;
} while (ch_end < skb_tail_pointer(skb));
if (ootb_shut_ack)
return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands);
else if (ootb_cookie_ack)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
else
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
/*
* Handle an "Out of the blue" SHUTDOWN ACK.
*
* Section: 8.4 5, sctpimpguide 2.41.
*
* 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should
* respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE.
* When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
* packet must fill in the Verification Tag field of the outbound
* packet with the Verification Tag received in the SHUTDOWN ACK and
* set the T-bit in the Chunk Flags to indicate that the Verification
* Tag is reflected.
*
* Inputs
* (endpoint, asoc, type, arg, commands)
*
* Outputs
* (enum sctp_disposition)
*
* The return value is the disposition of the chunk.
*/
static enum sctp_disposition sctp_sf_shut_8_4_5(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *shut;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (!packet)
return SCTP_DISPOSITION_NOMEM;
/* Make an SHUTDOWN_COMPLETE.
* The T bit will be set if the asoc is NULL.
*/
shut = sctp_make_shutdown_complete(asoc, chunk);
if (!shut) {
sctp_ootb_pkt_free(packet);
return SCTP_DISPOSITION_NOMEM;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(shut))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Set the skb to the belonging sock for accounting. */
shut->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, shut);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
/* We need to discard the rest of the packet to prevent
* potential boomming attacks from additional bundled chunks.
* This is documented in SCTP Threats ID.
*/
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/*
* Handle SHUTDOWN ACK in COOKIE_ECHOED or COOKIE_WAIT state.
*
* Verification Tag: 8.5.1 E) Rules for packet carrying a SHUTDOWN ACK
* If the receiver is in COOKIE-ECHOED or COOKIE-WAIT state the
* procedures in section 8.4 SHOULD be followed, in other words it
* should be treated as an Out Of The Blue packet.
* [This means that we do NOT check the Verification Tag on these
* chunks. --piggy ]
*
*/
enum sctp_disposition sctp_sf_do_8_5_1_E_sa(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify(chunk, asoc))
asoc = NULL;
/* Make sure that the SHUTDOWN_ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_chunkhdr)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Although we do have an association in this case, it corresponds
* to a restarted association. So the packet is treated as an OOTB
* packet and the state function that handles OOTB SHUTDOWN_ACK is
* called with a NULL association.
*/
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_shut_8_4_5(net, ep, NULL, type, arg, commands);
}
/* ADDIP Section 4.2 Upon reception of an ASCONF Chunk. */
enum sctp_disposition sctp_sf_do_asconf(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_paramhdr *err_param = NULL;
struct sctp_chunk *asconf_ack = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_addiphdr *hdr;
__u32 serial;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the ASCONF ADDIP chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_addip_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* ADD-IP: Section 4.1.1
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.ietf-tsvwg-sctp-auth].
*/
if (!asoc->peer.asconf_capable ||
(!net->sctp.addip_noauth && !chunk->auth))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
hdr = (struct sctp_addiphdr *)chunk->skb->data;
serial = ntohl(hdr->serial);
/* Verify the ASCONF chunk before processing it. */
if (!sctp_verify_asconf(asoc, chunk, true, &err_param))
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)err_param, commands);
/* ADDIP 5.2 E1) Compare the value of the serial number to the value
* the endpoint stored in a new association variable
* 'Peer-Serial-Number'.
*/
if (serial == asoc->peer.addip_serial + 1) {
/* If this is the first instance of ASCONF in the packet,
* we can clean our old ASCONF-ACKs.
*/
if (!chunk->has_asconf)
sctp_assoc_clean_asconf_ack_cache(asoc);
/* ADDIP 5.2 E4) When the Sequence Number matches the next one
* expected, process the ASCONF as described below and after
* processing the ASCONF Chunk, append an ASCONF-ACK Chunk to
* the response packet and cache a copy of it (in the event it
* later needs to be retransmitted).
*
* Essentially, do V1-V5.
*/
asconf_ack = sctp_process_asconf((struct sctp_association *)
asoc, chunk);
if (!asconf_ack)
return SCTP_DISPOSITION_NOMEM;
} else if (serial < asoc->peer.addip_serial + 1) {
/* ADDIP 5.2 E2)
* If the value found in the Sequence Number is less than the
* ('Peer- Sequence-Number' + 1), simply skip to the next
* ASCONF, and include in the outbound response packet
* any previously cached ASCONF-ACK response that was
* sent and saved that matches the Sequence Number of the
* ASCONF. Note: It is possible that no cached ASCONF-ACK
* Chunk exists. This will occur when an older ASCONF
* arrives out of order. In such a case, the receiver
* should skip the ASCONF Chunk and not include ASCONF-ACK
* Chunk for that chunk.
*/
asconf_ack = sctp_assoc_lookup_asconf_ack(asoc, hdr->serial);
if (!asconf_ack)
return SCTP_DISPOSITION_DISCARD;
/* Reset the transport so that we select the correct one
* this time around. This is to make sure that we don't
* accidentally use a stale transport that's been removed.
*/
asconf_ack->transport = NULL;
} else {
/* ADDIP 5.2 E5) Otherwise, the ASCONF Chunk is discarded since
* it must be either a stale packet or from an attacker.
*/
return SCTP_DISPOSITION_DISCARD;
}
/* ADDIP 5.2 E6) The destination address of the SCTP packet
* containing the ASCONF-ACK Chunks MUST be the source address of
* the SCTP packet that held the ASCONF Chunks.
*
* To do this properly, we'll set the destination address of the chunk
* and at the transmit time, will try look up the transport to use.
* Since ASCONFs may be bundled, the correct transport may not be
* created until we process the entire packet, thus this workaround.
*/
asconf_ack->dest = chunk->source;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(asconf_ack));
if (asoc->new_transport) {
sctp_sf_heartbeat(ep, asoc, type, asoc->new_transport, commands);
((struct sctp_association *)asoc)->new_transport = NULL;
}
return SCTP_DISPOSITION_CONSUME;
}
static enum sctp_disposition sctp_send_next_asconf(
struct net *net,
const struct sctp_endpoint *ep,
struct sctp_association *asoc,
const union sctp_subtype type,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *asconf;
struct list_head *entry;
if (list_empty(&asoc->addip_chunk_list))
return SCTP_DISPOSITION_CONSUME;
entry = asoc->addip_chunk_list.next;
asconf = list_entry(entry, struct sctp_chunk, list);
list_del_init(entry);
sctp_chunk_hold(asconf);
asoc->addip_last_asconf = asconf;
return sctp_sf_do_prm_asconf(net, ep, asoc, type, asconf, commands);
}
/*
* ADDIP Section 4.3 General rules for address manipulation
* When building TLV parameters for the ASCONF Chunk that will add or
* delete IP addresses the D0 to D13 rules should be applied:
*/
enum sctp_disposition sctp_sf_do_asconf_ack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *last_asconf = asoc->addip_last_asconf;
struct sctp_paramhdr *err_param = NULL;
struct sctp_chunk *asconf_ack = arg;
struct sctp_addiphdr *addip_hdr;
__u32 sent_serial, rcvd_serial;
struct sctp_chunk *abort;
if (!sctp_vtag_verify(asconf_ack, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the ADDIP chunk has a valid length. */
if (!sctp_chunk_length_valid(asconf_ack,
sizeof(struct sctp_addip_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* ADD-IP, Section 4.1.2:
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.ietf-tsvwg-sctp-auth].
*/
if (!asoc->peer.asconf_capable ||
(!net->sctp.addip_noauth && !asconf_ack->auth))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
addip_hdr = (struct sctp_addiphdr *)asconf_ack->skb->data;
rcvd_serial = ntohl(addip_hdr->serial);
/* Verify the ASCONF-ACK chunk before processing it. */
if (!sctp_verify_asconf(asoc, asconf_ack, false, &err_param))
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)err_param, commands);
if (last_asconf) {
addip_hdr = last_asconf->subh.addip_hdr;
sent_serial = ntohl(addip_hdr->serial);
} else {
sent_serial = asoc->addip_serial - 1;
}
/* D0) If an endpoint receives an ASCONF-ACK that is greater than or
* equal to the next serial number to be used but no ASCONF chunk is
* outstanding the endpoint MUST ABORT the association. Note that a
* sequence number is greater than if it is no more than 2^^31-1
* larger than the current sequence number (using serial arithmetic).
*/
if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) &&
!(asoc->addip_last_asconf)) {
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(struct sctp_errhdr));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_ASCONF_ACK));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
if (!sctp_process_asconf_ack((struct sctp_association *)asoc,
asconf_ack))
return sctp_send_next_asconf(net, ep,
(struct sctp_association *)asoc,
type, commands);
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(struct sctp_errhdr));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_ASCONF_ACK));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
return SCTP_DISPOSITION_DISCARD;
}
/* RE-CONFIG Section 5.2 Upon reception of an RECONF Chunk. */
enum sctp_disposition sctp_sf_do_reconf(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_paramhdr *err_param = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_reconf_chunk *hdr;
union sctp_params param;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the RECONF chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(*hdr)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
if (!sctp_verify_reconf(asoc, chunk, &err_param))
return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
(void *)err_param, commands);
hdr = (struct sctp_reconf_chunk *)chunk->chunk_hdr;
sctp_walk_params(param, hdr) {
struct sctp_chunk *reply = NULL;
struct sctp_ulpevent *ev = NULL;
if (param.p->type == SCTP_PARAM_RESET_OUT_REQUEST)
reply = sctp_process_strreset_outreq(
(struct sctp_association *)asoc, param, &ev);
else if (param.p->type == SCTP_PARAM_RESET_IN_REQUEST)
reply = sctp_process_strreset_inreq(
(struct sctp_association *)asoc, param, &ev);
else if (param.p->type == SCTP_PARAM_RESET_TSN_REQUEST)
reply = sctp_process_strreset_tsnreq(
(struct sctp_association *)asoc, param, &ev);
else if (param.p->type == SCTP_PARAM_RESET_ADD_OUT_STREAMS)
reply = sctp_process_strreset_addstrm_out(
(struct sctp_association *)asoc, param, &ev);
else if (param.p->type == SCTP_PARAM_RESET_ADD_IN_STREAMS)
reply = sctp_process_strreset_addstrm_in(
(struct sctp_association *)asoc, param, &ev);
else if (param.p->type == SCTP_PARAM_RESET_RESPONSE)
reply = sctp_process_strreset_resp(
(struct sctp_association *)asoc, param, &ev);
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
if (reply)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(reply));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* PR-SCTP Section 3.6 Receiver Side Implementation of PR-SCTP
*
* When a FORWARD TSN chunk arrives, the data receiver MUST first update
* its cumulative TSN point to the value carried in the FORWARD TSN
* chunk, and then MUST further advance its cumulative TSN point locally
* if possible.
* After the above processing, the data receiver MUST stop reporting any
* missing TSNs earlier than or equal to the new cumulative TSN point.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_eat_fwd_tsn(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_chunk *chunk = arg;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (!asoc->peer.prsctp_capable)
return sctp_sf_unk_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the FORWARD_TSN chunk has valid length. */
if (!sctp_chunk_length_valid(chunk, sctp_ftsnchk_len(&asoc->stream)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto discard_noforce;
if (!asoc->stream.si->validate_ftsn(chunk))
goto discard_noforce;
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn));
if (len > sctp_ftsnhdr_len(&asoc->stream))
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN,
SCTP_CHUNK(chunk));
/* Count this as receiving DATA. */
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
}
/* FIXME: For now send a SACK, but DATA processing may
* send another.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_NOFORCE());
return SCTP_DISPOSITION_CONSUME;
discard_noforce:
return SCTP_DISPOSITION_DISCARD;
}
enum sctp_disposition sctp_sf_eat_fwd_tsn_fast(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_chunk *chunk = arg;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (!asoc->peer.prsctp_capable)
return sctp_sf_unk_chunk(net, ep, asoc, type, arg, commands);
/* Make sure that the FORWARD_TSN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sctp_ftsnchk_len(&asoc->stream)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto gen_shutdown;
if (!asoc->stream.si->validate_ftsn(chunk))
goto gen_shutdown;
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn));
if (len > sctp_ftsnhdr_len(&asoc->stream))
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN,
SCTP_CHUNK(chunk));
/* Go a head and force a SACK, since we are shutting down. */
gen_shutdown:
/* Implementor's Guide.
*
* While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
* respond to each received packet containing one or more DATA chunk(s)
* with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SHUTDOWN, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
return SCTP_DISPOSITION_CONSUME;
}
/*
* SCTP-AUTH Section 6.3 Receiving authenticated chunks
*
* The receiver MUST use the HMAC algorithm indicated in the HMAC
* Identifier field. If this algorithm was not specified by the
* receiver in the HMAC-ALGO parameter in the INIT or INIT-ACK chunk
* during association setup, the AUTH chunk and all chunks after it MUST
* be discarded and an ERROR chunk SHOULD be sent with the error cause
* defined in Section 4.1.
*
* If an endpoint with no shared key receives a Shared Key Identifier
* other than 0, it MUST silently discard all authenticated chunks. If
* the endpoint has at least one endpoint pair shared key for the peer,
* it MUST use the key specified by the Shared Key Identifier if a
* key has been configured for that Shared Key Identifier. If no
* endpoint pair shared key has been configured for that Shared Key
* Identifier, all authenticated chunks MUST be silently discarded.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* The return value is the disposition of the chunk.
*/
static enum sctp_ierror sctp_sf_authenticate(
const struct sctp_association *asoc,
struct sctp_chunk *chunk)
{
struct sctp_shared_key *sh_key = NULL;
struct sctp_authhdr *auth_hdr;
__u8 *save_digest, *digest;
struct sctp_hmac *hmac;
unsigned int sig_len;
__u16 key_id;
/* Pull in the auth header, so we can do some more verification */
auth_hdr = (struct sctp_authhdr *)chunk->skb->data;
chunk->subh.auth_hdr = auth_hdr;
skb_pull(chunk->skb, sizeof(*auth_hdr));
/* Make sure that we support the HMAC algorithm from the auth
* chunk.
*/
if (!sctp_auth_asoc_verify_hmac_id(asoc, auth_hdr->hmac_id))
return SCTP_IERROR_AUTH_BAD_HMAC;
/* Make sure that the provided shared key identifier has been
* configured
*/
key_id = ntohs(auth_hdr->shkey_id);
if (key_id != asoc->active_key_id) {
sh_key = sctp_auth_get_shkey(asoc, key_id);
if (!sh_key)
return SCTP_IERROR_AUTH_BAD_KEYID;
}
/* Make sure that the length of the signature matches what
* we expect.
*/
sig_len = ntohs(chunk->chunk_hdr->length) -
sizeof(struct sctp_auth_chunk);
hmac = sctp_auth_get_hmac(ntohs(auth_hdr->hmac_id));
if (sig_len != hmac->hmac_len)
return SCTP_IERROR_PROTO_VIOLATION;
/* Now that we've done validation checks, we can compute and
* verify the hmac. The steps involved are:
* 1. Save the digest from the chunk.
* 2. Zero out the digest in the chunk.
* 3. Compute the new digest
* 4. Compare saved and new digests.
*/
digest = (u8 *)(auth_hdr + 1);
skb_pull(chunk->skb, sig_len);
save_digest = kmemdup(digest, sig_len, GFP_ATOMIC);
if (!save_digest)
goto nomem;
memset(digest, 0, sig_len);
sctp_auth_calculate_hmac(asoc, chunk->skb,
(struct sctp_auth_chunk *)chunk->chunk_hdr,
sh_key, GFP_ATOMIC);
/* Discard the packet if the digests do not match */
if (memcmp(save_digest, digest, sig_len)) {
kfree(save_digest);
return SCTP_IERROR_BAD_SIG;
}
kfree(save_digest);
chunk->auth = 1;
return SCTP_IERROR_NO_ERROR;
nomem:
return SCTP_IERROR_NOMEM;
}
enum sctp_disposition sctp_sf_eat_auth(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg, struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_authhdr *auth_hdr;
struct sctp_chunk *err_chunk;
enum sctp_ierror error;
/* Make sure that the peer has AUTH capable */
if (!asoc->peer.auth_capable)
return sctp_sf_unk_chunk(net, ep, asoc, type, arg, commands);
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the AUTH chunk has valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_auth_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
auth_hdr = (struct sctp_authhdr *)chunk->skb->data;
error = sctp_sf_authenticate(asoc, chunk);
switch (error) {
case SCTP_IERROR_AUTH_BAD_HMAC:
/* Generate the ERROR chunk and discard the rest
* of the packet
*/
err_chunk = sctp_make_op_error(asoc, chunk,
SCTP_ERROR_UNSUP_HMAC,
&auth_hdr->hmac_id,
sizeof(__u16), 0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
fallthrough;
case SCTP_IERROR_AUTH_BAD_KEYID:
case SCTP_IERROR_BAD_SIG:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
case SCTP_IERROR_NOMEM:
return SCTP_DISPOSITION_NOMEM;
default: /* Prevent gcc warnings */
break;
}
if (asoc->active_key_id != ntohs(auth_hdr->shkey_id)) {
struct sctp_ulpevent *ev;
ev = sctp_ulpevent_make_authkey(asoc, ntohs(auth_hdr->shkey_id),
SCTP_AUTH_NEW_KEY, GFP_ATOMIC);
if (!ev)
return SCTP_DISPOSITION_NOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an unknown chunk.
*
* Section: 3.2. Also, 2.1 in the implementor's guide.
*
* Chunk Types are encoded such that the highest-order two bits specify
* the action that must be taken if the processing endpoint does not
* recognize the Chunk Type.
*
* 00 - Stop processing this SCTP packet and discard it, do not process
* any further chunks within it.
*
* 01 - Stop processing this SCTP packet and discard it, do not process
* any further chunks within it, and report the unrecognized
* chunk in an 'Unrecognized Chunk Type'.
*
* 10 - Skip this chunk and continue processing.
*
* 11 - Skip this chunk and continue processing, but report in an ERROR
* Chunk using the 'Unrecognized Chunk Type' cause of error.
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_unk_chunk(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *unk_chunk = arg;
struct sctp_chunk *err_chunk;
struct sctp_chunkhdr *hdr;
pr_debug("%s: processing unknown chunk id:%d\n", __func__, type.chunk);
if (!sctp_vtag_verify(unk_chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the chunk has a valid length.
* Since we don't know the chunk type, we use a general
* chunkhdr structure to make a comparison.
*/
if (!sctp_chunk_length_valid(unk_chunk, sizeof(*hdr)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
switch (type.chunk & SCTP_CID_ACTION_MASK) {
case SCTP_CID_ACTION_DISCARD:
/* Discard the packet. */
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case SCTP_CID_ACTION_DISCARD_ERR:
/* Generate an ERROR chunk as response. */
hdr = unk_chunk->chunk_hdr;
err_chunk = sctp_make_op_error(asoc, unk_chunk,
SCTP_ERROR_UNKNOWN_CHUNK, hdr,
SCTP_PAD4(ntohs(hdr->length)),
0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Discard the packet. */
sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return SCTP_DISPOSITION_CONSUME;
case SCTP_CID_ACTION_SKIP:
/* Skip the chunk. */
return SCTP_DISPOSITION_DISCARD;
case SCTP_CID_ACTION_SKIP_ERR:
/* Generate an ERROR chunk as response. */
hdr = unk_chunk->chunk_hdr;
err_chunk = sctp_make_op_error(asoc, unk_chunk,
SCTP_ERROR_UNKNOWN_CHUNK, hdr,
SCTP_PAD4(ntohs(hdr->length)),
0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Skip the chunk. */
return SCTP_DISPOSITION_CONSUME;
default:
break;
}
return SCTP_DISPOSITION_DISCARD;
}
/*
* Discard the chunk.
*
* Section: 0.2, 5.2.3, 5.2.5, 5.2.6, 6.0, 8.4.6, 8.5.1c, 9.2
* [Too numerous to mention...]
* Verification Tag: No verification needed.
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_discard_chunk(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
if (asoc && !sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the chunk has a valid length.
* Since we don't know the chunk type, we use a general
* chunkhdr structure to make a comparison.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_chunkhdr)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
pr_debug("%s: chunk:%d is discarded\n", __func__, type.chunk);
return SCTP_DISPOSITION_DISCARD;
}
/*
* Discard the whole packet.
*
* Section: 8.4 2)
*
* 2) If the OOTB packet contains an ABORT chunk, the receiver MUST
* silently discard the OOTB packet and take no further action.
*
* Verification Tag: No verification necessary
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_pdiscard(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg, struct sctp_cmd_seq *commands)
{
SCTP_INC_STATS(net, SCTP_MIB_IN_PKT_DISCARDS);
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
}
/*
* The other end is violating protocol.
*
* Section: Not specified
* Verification Tag: Not specified
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* We simply tag the chunk as a violation. The state machine will log
* the violation and continue.
*/
enum sctp_disposition sctp_sf_violation(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_chunkhdr)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
return SCTP_DISPOSITION_VIOLATION;
}
/*
* Common function to handle a protocol violation.
*/
static enum sctp_disposition sctp_sf_abort_violation(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
void *arg,
struct sctp_cmd_seq *commands,
const __u8 *payload,
const size_t paylen)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort = NULL;
/* SCTP-AUTH, Section 6.3:
* It should be noted that if the receiver wants to tear
* down an association in an authenticated way only, the
* handling of malformed packets should not result in
* tearing down the association.
*
* This means that if we only want to abort associations
* in an authenticated way (i.e AUTH+ABORT), then we
* can't destroy this association just because the packet
* was malformed.
*/
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
goto discard;
/* Make the abort chunk. */
abort = sctp_make_abort_violation(asoc, chunk, payload, paylen);
if (!abort)
goto nomem;
if (asoc) {
/* Treat INIT-ACK as a special case during COOKIE-WAIT. */
if (chunk->chunk_hdr->type == SCTP_CID_INIT_ACK &&
!asoc->peer.i.init_tag) {
struct sctp_initack_chunk *initack;
initack = (struct sctp_initack_chunk *)chunk->chunk_hdr;
if (!sctp_chunk_length_valid(chunk, sizeof(*initack)))
abort->chunk_hdr->flags |= SCTP_CHUNK_FLAG_T;
else {
unsigned int inittag;
inittag = ntohl(initack->init_hdr.init_tag);
sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_INITTAG,
SCTP_U32(inittag));
}
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
if (asoc->state <= SCTP_STATE_COOKIE_ECHOED) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNREFUSED));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
}
} else {
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (!packet)
goto nomem_pkt;
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
}
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
discard:
sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands);
return SCTP_DISPOSITION_ABORT;
nomem_pkt:
sctp_chunk_free(abort);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle a protocol violation when the chunk length is invalid.
* "Invalid" length is identified as smaller than the minimal length a
* given chunk can be. For example, a SACK chunk has invalid length
* if its length is set to be smaller than the size of struct sctp_sack_chunk.
*
* We inform the other end by sending an ABORT with a Protocol Violation
* error code.
*
* Section: Not specified
* Verification Tag: Nothing to do
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (reply_msg, msg_up, counters)
*
* Generate an ABORT chunk and terminate the association.
*/
static enum sctp_disposition sctp_sf_violation_chunklen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
static const char err_str[] = "The following chunk had invalid length:";
return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/*
* Handle a protocol violation when the parameter length is invalid.
* If the length is smaller than the minimum length of a given parameter,
* or accumulated length in multi parameters exceeds the end of the chunk,
* the length is considered as invalid.
*/
static enum sctp_disposition sctp_sf_violation_paramlen(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg, void *ext,
struct sctp_cmd_seq *commands)
{
struct sctp_paramhdr *param = ext;
struct sctp_chunk *abort = NULL;
struct sctp_chunk *chunk = arg;
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
goto discard;
/* Make the abort chunk. */
abort = sctp_make_violation_paramlen(asoc, chunk, param);
if (!abort)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
discard:
sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands);
return SCTP_DISPOSITION_ABORT;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Handle a protocol violation when the peer trying to advance the
* cumulative tsn ack to a point beyond the max tsn currently sent.
*
* We inform the other end by sending an ABORT with a Protocol Violation
* error code.
*/
static enum sctp_disposition sctp_sf_violation_ctsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
static const char err_str[] = "The cumulative tsn ack beyond the max tsn currently sent:";
return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/* Handle protocol violation of an invalid chunk bundling. For example,
* when we have an association and we receive bundled INIT-ACK, or
* SHUTDOWN-COMPLETE, our peer is clearly violating the "MUST NOT bundle"
* statement from the specs. Additionally, there might be an attacker
* on the path and we may not want to continue this communication.
*/
static enum sctp_disposition sctp_sf_violation_chunk(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
static const char err_str[] = "The following chunk violates protocol:";
return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/***************************************************************************
* These are the state functions for handling primitive (Section 10) events.
***************************************************************************/
/*
* sctp_sf_do_prm_asoc
*
* Section: 10.1 ULP-to-SCTP
* B) Associate
*
* Format: ASSOCIATE(local SCTP instance name, destination transport addr,
* outbound stream count)
* -> association id [,destination transport addr list] [,outbound stream
* count]
*
* This primitive allows the upper layer to initiate an association to a
* specific peer endpoint.
*
* The peer endpoint shall be specified by one of the transport addresses
* which defines the endpoint (see Section 1.4). If the local SCTP
* instance has not been initialized, the ASSOCIATE is considered an
* error.
* [This is not relevant for the kernel implementation since we do all
* initialization at boot time. It we hadn't initialized we wouldn't
* get anywhere near this code.]
*
* An association id, which is a local handle to the SCTP association,
* will be returned on successful establishment of the association. If
* SCTP is not able to open an SCTP association with the peer endpoint,
* an error is returned.
* [In the kernel implementation, the struct sctp_association needs to
* be created BEFORE causing this primitive to run.]
*
* Other association parameters may be returned, including the
* complete destination transport addresses of the peer as well as the
* outbound stream count of the local endpoint. One of the transport
* address from the returned destination addresses will be selected by
* the local endpoint as default primary path for sending SCTP packets
* to this peer. The returned "destination transport addr list" can
* be used by the ULP to change the default primary path or to force
* sending a packet to a specific transport address. [All of this
* stuff happens when the INIT ACK arrives. This is a NON-BLOCKING
* function.]
*
* Mandatory attributes:
*
* o local SCTP instance name - obtained from the INITIALIZE operation.
* [This is the argument asoc.]
* o destination transport addr - specified as one of the transport
* addresses of the peer endpoint with which the association is to be
* established.
* [This is asoc->peer.active_path.]
* o outbound stream count - the number of outbound streams the ULP
* would like to open towards this peer endpoint.
* [BUG: This is not currently implemented.]
* Optional attributes:
*
* None.
*
* The return value is a disposition.
*/
enum sctp_disposition sctp_sf_do_prm_asoc(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_association *my_asoc;
struct sctp_chunk *repl;
/* The comment below says that we enter COOKIE-WAIT AFTER
* sending the INIT, but that doesn't actually work in our
* implementation...
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_WAIT));
/* RFC 2960 5.1 Normal Establishment of an Association
*
* A) "A" first sends an INIT chunk to "Z". In the INIT, "A"
* must provide its Verification Tag (Tag_A) in the Initiate
* Tag field. Tag_A SHOULD be a random number in the range of
* 1 to 4294967295 (see 5.3.1 for Tag value selection). ...
*/
repl = sctp_make_init(asoc, &asoc->base.bind_addr, GFP_ATOMIC, 0);
if (!repl)
goto nomem;
/* Choose transport for INIT. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Cast away the const modifier, as we want to just
* rerun it through as a sideffect.
*/
my_asoc = (struct sctp_association *)asoc;
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(my_asoc));
/* After sending the INIT, "A" starts the T1-init timer and
* enters the COOKIE-WAIT state.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process the SEND primitive.
*
* Section: 10.1 ULP-to-SCTP
* E) Send
*
* Format: SEND(association id, buffer address, byte count [,context]
* [,stream id] [,life time] [,destination transport address]
* [,unorder flag] [,no-bundle flag] [,payload protocol-id] )
* -> result
*
* This is the main method to send user data via SCTP.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o buffer address - the location where the user message to be
* transmitted is stored;
*
* o byte count - The size of the user data in number of bytes;
*
* Optional attributes:
*
* o context - an optional 32 bit integer that will be carried in the
* sending failure notification to the ULP if the transportation of
* this User Message fails.
*
* o stream id - to indicate which stream to send the data on. If not
* specified, stream 0 will be used.
*
* o life time - specifies the life time of the user data. The user data
* will not be sent by SCTP after the life time expires. This
* parameter can be used to avoid efforts to transmit stale
* user messages. SCTP notifies the ULP if the data cannot be
* initiated to transport (i.e. sent to the destination via SCTP's
* send primitive) within the life time variable. However, the
* user data will be transmitted if SCTP has attempted to transmit a
* chunk before the life time expired.
*
* o destination transport address - specified as one of the destination
* transport addresses of the peer endpoint to which this packet
* should be sent. Whenever possible, SCTP should use this destination
* transport address for sending the packets, instead of the current
* primary path.
*
* o unorder flag - this flag, if present, indicates that the user
* would like the data delivered in an unordered fashion to the peer
* (i.e., the U flag is set to 1 on all DATA chunks carrying this
* message).
*
* o no-bundle flag - instructs SCTP not to bundle this user data with
* other outbound DATA chunks. SCTP MAY still bundle even when
* this flag is present, when faced with network congestion.
*
* o payload protocol-id - A 32 bit unsigned integer that is to be
* passed to the peer indicating the type of payload protocol data
* being transmitted. This value is passed as opaque data by SCTP.
*
* The return value is the disposition.
*/
enum sctp_disposition sctp_sf_do_prm_send(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_datamsg *msg = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_MSG, SCTP_DATAMSG(msg));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process the SHUTDOWN primitive.
*
* Section: 10.1:
* C) Shutdown
*
* Format: SHUTDOWN(association id)
* -> result
*
* Gracefully closes an association. Any locally queued user data
* will be delivered to the peer. The association will be terminated only
* after the peer acknowledges all the SCTP packets sent. A success code
* will be returned on successful termination of the association. If
* attempting to terminate the association results in a failure, an error
* code shall be returned.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* Optional attributes:
*
* None.
*
* The return value is the disposition.
*/
enum sctp_disposition sctp_sf_do_9_2_prm_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
enum sctp_disposition disposition;
/* From 9.2 Shutdown of an Association
* Upon receipt of the SHUTDOWN primitive from its upper
* layer, the endpoint enters SHUTDOWN-PENDING state and
* remains there until all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_PENDING));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_start_shutdown(net, ep, asoc, type,
arg, commands);
}
return disposition;
}
/*
* Process the ABORT primitive.
*
* Section: 10.1:
* C) Abort
*
* Format: Abort(association id [, cause code])
* -> result
*
* Ungracefully closes an association. Any locally queued user data
* will be discarded and an ABORT chunk is sent to the peer. A success code
* will be returned on successful abortion of the association. If
* attempting to abort the association results in a failure, an error
* code shall be returned.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* Optional attributes:
*
* o cause code - reason of the abort to be passed to the peer
*
* None.
*
* The return value is the disposition.
*/
enum sctp_disposition sctp_sf_do_9_1_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* From 9.1 Abort of an Association
* Upon receipt of the ABORT primitive from its upper
* layer, the endpoint enters CLOSED state and
* discard all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
struct sctp_chunk *abort = arg;
if (abort)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
/* Even if we can't send the ABORT due to low memory delete the
* TCB. This is a departure from our typical NOMEM handling.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
/* Delete the established association. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_USER_ABORT));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
/* We tried an illegal operation on an association which is closed. */
enum sctp_disposition sctp_sf_error_closed(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_ERROR, SCTP_ERROR(-EINVAL));
return SCTP_DISPOSITION_CONSUME;
}
/* We tried an illegal operation on an association which is shutting
* down.
*/
enum sctp_disposition sctp_sf_error_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_ERROR,
SCTP_ERROR(-ESHUTDOWN));
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_cookie_wait_prm_shutdown
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues a shutdown while in COOKIE_WAIT state.
*
* Outputs
* (timers)
*/
enum sctp_disposition sctp_sf_cookie_wait_prm_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
}
/*
* sctp_cookie_echoed_prm_shutdown
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues a shutdown while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
enum sctp_disposition sctp_sf_cookie_echoed_prm_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_prm_shutdown(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_cookie_wait_prm_abort
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_WAIT state.
*
* Outputs
* (timers)
*/
enum sctp_disposition sctp_sf_cookie_wait_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *abort = arg;
/* Stop T1-init timer */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
if (abort)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
/* Even if we can't send the ABORT due to low memory delete the
* TCB. This is a departure from our typical NOMEM handling.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNREFUSED));
/* Delete the established association. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_USER_ABORT));
return SCTP_DISPOSITION_ABORT;
}
/*
* sctp_sf_cookie_echoed_prm_abort
*
* Section: 4 Note: 3
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
enum sctp_disposition sctp_sf_cookie_echoed_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_shutdown_pending_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in SHUTDOWN-PENDING state.
*
* Outputs
* (timers)
*/
enum sctp_disposition sctp_sf_shutdown_pending_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return sctp_sf_do_9_1_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_shutdown_sent_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in SHUTDOWN-SENT state.
*
* Outputs
* (timers)
*/
enum sctp_disposition sctp_sf_shutdown_sent_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* Stop the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return sctp_sf_do_9_1_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* sctp_sf_cookie_echoed_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
enum sctp_disposition sctp_sf_shutdown_ack_sent_prm_abort(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
/* The same T2 timer, so we should be able to use
* common function with the SHUTDOWN-SENT state.
*/
return sctp_sf_shutdown_sent_prm_abort(net, ep, asoc, type, arg, commands);
}
/*
* Process the REQUESTHEARTBEAT primitive
*
* 10.1 ULP-to-SCTP
* J) Request Heartbeat
*
* Format: REQUESTHEARTBEAT(association id, destination transport address)
*
* -> result
*
* Instructs the local endpoint to perform a HeartBeat on the specified
* destination transport address of the given association. The returned
* result should indicate whether the transmission of the HEARTBEAT
* chunk to the destination address is successful.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o destination transport address - the transport address of the
* association on which a heartbeat should be issued.
*/
enum sctp_disposition sctp_sf_do_prm_requestheartbeat(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
if (SCTP_DISPOSITION_NOMEM == sctp_sf_heartbeat(ep, asoc, type,
(struct sctp_transport *)arg, commands))
return SCTP_DISPOSITION_NOMEM;
/*
* RFC 2960 (bis), section 8.3
*
* D) Request an on-demand HEARTBEAT on a specific destination
* transport address of a given association.
*
* The endpoint should increment the respective error counter of
* the destination transport address each time a HEARTBEAT is sent
* to that address and not acknowledged within one RTO.
*
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT,
SCTP_TRANSPORT(arg));
return SCTP_DISPOSITION_CONSUME;
}
/*
* ADDIP Section 4.1 ASCONF Chunk Procedures
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do A1 to A9
*/
enum sctp_disposition sctp_sf_do_prm_asconf(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(chunk));
return SCTP_DISPOSITION_CONSUME;
}
/* RE-CONFIG Section 5.1 RECONF Chunk Procedures */
enum sctp_disposition sctp_sf_do_prm_reconf(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Ignore the primitive event
*
* The return value is the disposition of the primitive.
*/
enum sctp_disposition sctp_sf_ignore_primitive(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
pr_debug("%s: primitive type:%d is ignored\n", __func__,
type.primitive);
return SCTP_DISPOSITION_DISCARD;
}
/***************************************************************************
* These are the state functions for the OTHER events.
***************************************************************************/
/*
* When the SCTP stack has no more user data to send or retransmit, this
* notification is given to the user. Also, at the time when a user app
* subscribes to this event, if there is no data to be sent or
* retransmit, the stack will immediately send up this notification.
*/
enum sctp_disposition sctp_sf_do_no_pending_tsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_ulpevent *event;
event = sctp_ulpevent_make_sender_dry_event(asoc, GFP_ATOMIC);
if (!event)
return SCTP_DISPOSITION_NOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(event));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Start the shutdown negotiation.
*
* From Section 9.2:
* Once all its outstanding data has been acknowledged, the endpoint
* shall send a SHUTDOWN chunk to its peer including in the Cumulative
* TSN Ack field the last sequential TSN it has received from the peer.
* It shall then start the T2-shutdown timer and enter the SHUTDOWN-SENT
* state. If the timer expires, the endpoint must re-send the SHUTDOWN
* with the updated last sequential TSN received from its peer.
*
* The return value is the disposition.
*/
enum sctp_disposition sctp_sf_do_9_2_start_shutdown(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *reply;
/* Once all its outstanding data has been acknowledged, the
* endpoint shall send a SHUTDOWN chunk to its peer including
* in the Cumulative TSN Ack field the last sequential TSN it
* has received from the peer.
*/
reply = sctp_make_shutdown(asoc, arg);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN chunk and the timeout for the
* T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* It shall then start the T2-shutdown timer */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* RFC 4960 Section 9.2
* The sender of the SHUTDOWN MAY also start an overall guard timer
* 'T5-shutdown-guard' to bound the overall time for shutdown sequence.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* and enter the SHUTDOWN-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_SENT));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Generate a SHUTDOWN ACK now that everything is SACK'd.
*
* From Section 9.2:
*
* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK and start a T2-shutdown timer of its own,
* entering the SHUTDOWN-ACK-SENT state. If the timer expires, the
* endpoint must re-send the SHUTDOWN ACK.
*
* The return value is the disposition.
*/
enum sctp_disposition sctp_sf_do_9_2_shutdown_ack(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
/* There are 2 ways of getting here:
* 1) called in response to a SHUTDOWN chunk
* 2) called when SCTP_EVENT_NO_PENDING_TSN event is issued.
*
* For the case (2), the arg parameter is set to NULL. We need
* to check that we have a chunk before accessing it's fields.
*/
if (chunk) {
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg,
commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(
chunk, sizeof(struct sctp_shutdown_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type,
arg, commands);
}
/* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK ...
*/
reply = sctp_make_shutdown_ack(asoc, chunk);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and start/restart a T2-shutdown timer of its own, */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* Enter the SHUTDOWN-ACK-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_ACK_SENT));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Ignore the event defined as other
*
* The return value is the disposition of the event.
*/
enum sctp_disposition sctp_sf_ignore_other(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
pr_debug("%s: the event other type:%d is ignored\n",
__func__, type.other);
return SCTP_DISPOSITION_DISCARD;
}
/************************************************************
* These are the state functions for handling timeout events.
************************************************************/
/*
* RTX Timeout
*
* Section: 6.3.3 Handle T3-rtx Expiration
*
* Whenever the retransmission timer T3-rtx expires for a destination
* address, do the following:
* [See below]
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_do_6_3_3_rtx(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_transport *transport = arg;
SCTP_INC_STATS(net, SCTP_MIB_T3_RTX_EXPIREDS);
if (asoc->overall_error_count >= asoc->max_retrans) {
if (asoc->peer.zero_window_announced &&
asoc->state == SCTP_STATE_SHUTDOWN_PENDING) {
/*
* We are here likely because the receiver had its rwnd
* closed for a while and we have not been able to
* transmit the locally queued data within the maximum
* retransmission attempts limit. Start the T5
* shutdown guard timer to give the receiver one last
* chance and some additional time to recover before
* aborting.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START_ONCE,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
}
/* E1) For the destination address for which the timer
* expires, adjust its ssthresh with rules defined in Section
* 7.2.3 and set the cwnd <- MTU.
*/
/* E2) For the destination address for which the timer
* expires, set RTO <- RTO * 2 ("back off the timer"). The
* maximum value discussed in rule C7 above (RTO.max) may be
* used to provide an upper bound to this doubling operation.
*/
/* E3) Determine how many of the earliest (i.e., lowest TSN)
* outstanding DATA chunks for the address for which the
* T3-rtx has expired will fit into a single packet, subject
* to the MTU constraint for the path corresponding to the
* destination transport address to which the retransmission
* is being sent (this may be different from the address for
* which the timer expires [see Section 6.4]). Call this
* value K. Bundle and retransmit those K DATA chunks in a
* single packet to the destination endpoint.
*
* Note: Any DATA chunks that were sent to the address for
* which the T3-rtx timer expired but did not fit in one MTU
* (rule E3 above), should be marked for retransmission and
* sent as soon as cwnd allows (normally when a SACK arrives).
*/
/* Do some failure management (Section 8.2). */
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport));
/* NB: Rules E4 and F1 are implicit in R1. */
sctp_add_cmd_sf(commands, SCTP_CMD_RETRAN, SCTP_TRANSPORT(transport));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Generate delayed SACK on timeout
*
* Section: 6.2 Acknowledgement on Reception of DATA Chunks
*
* The guidelines on delayed acknowledgement algorithm specified in
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
* acknowledgement SHOULD be generated for at least every second packet
* (not every second DATA chunk) received, and SHOULD be generated
* within 200 ms of the arrival of any unacknowledged DATA chunk. In
* some situations it may be beneficial for an SCTP transmitter to be
* more conservative than the algorithms detailed in this document
* allow. However, an SCTP transmitter MUST NOT be more aggressive than
* the following algorithms allow.
*/
enum sctp_disposition sctp_sf_do_6_2_sack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
SCTP_INC_STATS(net, SCTP_MIB_DELAY_SACK_EXPIREDS);
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_t1_init_timer_expire
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* RFC 2960 Section 4 Notes
* 2) If the T1-init timer expires, the endpoint MUST retransmit INIT
* and re-start the T1-init timer without changing state. This MUST
* be repeated up to 'Max.Init.Retransmits' times. After that, the
* endpoint MUST abort the initialization process and report the
* error to SCTP user.
*
* Outputs
* (timers, events)
*
*/
enum sctp_disposition sctp_sf_t1_init_timer_expire(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
int attempts = asoc->init_err_counter + 1;
struct sctp_chunk *repl = NULL;
struct sctp_bind_addr *bp;
pr_debug("%s: timer T1 expired (INIT)\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T1_INIT_EXPIREDS);
if (attempts <= asoc->max_init_attempts) {
bp = (struct sctp_bind_addr *) &asoc->base.bind_addr;
repl = sctp_make_init(asoc, bp, GFP_ATOMIC, 0);
if (!repl)
return SCTP_DISPOSITION_NOMEM;
/* Choose transport for INIT. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Issue a sideeffect to do the needed accounting. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
} else {
pr_debug("%s: giving up on INIT, attempts:%d "
"max_init_attempts:%d\n", __func__, attempts,
asoc->max_init_attempts);
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
return SCTP_DISPOSITION_DELETE_TCB;
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_t1_cookie_timer_expire
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* RFC 2960 Section 4 Notes
* 3) If the T1-cookie timer expires, the endpoint MUST retransmit
* COOKIE ECHO and re-start the T1-cookie timer without changing
* state. This MUST be repeated up to 'Max.Init.Retransmits' times.
* After that, the endpoint MUST abort the initialization process and
* report the error to SCTP user.
*
* Outputs
* (timers, events)
*
*/
enum sctp_disposition sctp_sf_t1_cookie_timer_expire(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
int attempts = asoc->init_err_counter + 1;
struct sctp_chunk *repl = NULL;
pr_debug("%s: timer T1 expired (COOKIE-ECHO)\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T1_COOKIE_EXPIREDS);
if (attempts <= asoc->max_init_attempts) {
repl = sctp_make_cookie_echo(asoc, NULL);
if (!repl)
return SCTP_DISPOSITION_NOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Issue a sideeffect to do the needed accounting. */
sctp_add_cmd_sf(commands, SCTP_CMD_COOKIEECHO_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
return SCTP_DISPOSITION_DELETE_TCB;
}
return SCTP_DISPOSITION_CONSUME;
}
/* RFC2960 9.2 If the timer expires, the endpoint must re-send the SHUTDOWN
* with the updated last sequential TSN received from its peer.
*
* An endpoint should limit the number of retransmission of the
* SHUTDOWN chunk to the protocol parameter 'Association.Max.Retrans'.
* If this threshold is exceeded the endpoint should destroy the TCB and
* MUST report the peer endpoint unreachable to the upper layer (and
* thus the association enters the CLOSED state). The reception of any
* packet from its peer (i.e. as the peer sends all of its queued DATA
* chunks) should clear the endpoint's retransmission count and restart
* the T2-Shutdown timer, giving its peer ample opportunity to transmit
* all of its queued DATA chunks that have not yet been sent.
*/
enum sctp_disposition sctp_sf_t2_timer_expire(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *reply = NULL;
pr_debug("%s: timer T2 expired\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T2_SHUTDOWN_EXPIREDS);
((struct sctp_association *)asoc)->shutdown_retries++;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* Note: CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
switch (asoc->state) {
case SCTP_STATE_SHUTDOWN_SENT:
reply = sctp_make_shutdown(asoc, NULL);
break;
case SCTP_STATE_SHUTDOWN_ACK_SENT:
reply = sctp_make_shutdown_ack(asoc, NULL);
break;
default:
BUG();
break;
}
if (!reply)
goto nomem;
/* Do some failure management (Section 8.2).
* If we remove the transport an SHUTDOWN was last sent to, don't
* do failure management.
*/
if (asoc->shutdown_last_sent_to)
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE,
SCTP_TRANSPORT(asoc->shutdown_last_sent_to));
/* Set the transport for the SHUTDOWN/ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* Restart the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* ADDIP Section 4.1 ASCONF Chunk Procedures
* If the T4 RTO timer expires the endpoint should do B1 to B5
*/
enum sctp_disposition sctp_sf_t4_timer_expire(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *chunk = asoc->addip_last_asconf;
struct sctp_transport *transport = chunk->transport;
SCTP_INC_STATS(net, SCTP_MIB_T4_RTO_EXPIREDS);
/* ADDIP 4.1 B1) Increment the error counters and perform path failure
* detection on the appropriate destination address as defined in
* RFC2960 [5] section 8.1 and 8.2.
*/
if (transport)
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE,
SCTP_TRANSPORT(transport));
/* Reconfig T4 timer and transport. */
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk));
/* ADDIP 4.1 B2) Increment the association error counters and perform
* endpoint failure detection on the association as defined in
* RFC2960 [5] section 8.1 and 8.2.
* association error counter is incremented in SCTP_CMD_STRIKE.
*/
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
/* ADDIP 4.1 B3) Back-off the destination address RTO value to which
* the ASCONF chunk was sent by doubling the RTO timer value.
* This is done in SCTP_CMD_STRIKE.
*/
/* ADDIP 4.1 B4) Re-transmit the ASCONF Chunk last sent and if possible
* choose an alternate destination address (please refer to RFC2960
* [5] section 6.4.1). An endpoint MUST NOT add new parameters to this
* chunk, it MUST be the same (including its serial number) as the last
* ASCONF sent.
*/
sctp_chunk_hold(asoc->addip_last_asconf);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(asoc->addip_last_asconf));
/* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different
* destination is selected, then the RTO used will be that of the new
* destination address.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
return SCTP_DISPOSITION_CONSUME;
}
/* sctpimpguide-05 Section 2.12.2
* The sender of the SHUTDOWN MAY also start an overall guard timer
* 'T5-shutdown-guard' to bound the overall time for shutdown sequence.
* At the expiration of this timer the sender SHOULD abort the association
* by sending an ABORT chunk.
*/
enum sctp_disposition sctp_sf_t5_timer_expire(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
struct sctp_chunk *reply = NULL;
pr_debug("%s: timer T5 expired\n", __func__);
SCTP_INC_STATS(net, SCTP_MIB_T5_SHUTDOWN_GUARD_EXPIREDS);
reply = sctp_make_abort(asoc, NULL, 0);
if (!reply)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Handle expiration of AUTOCLOSE timer. When the autoclose timer expires,
* the association is automatically closed by starting the shutdown process.
* The work that needs to be done is same as when SHUTDOWN is initiated by
* the user. So this routine looks same as sctp_sf_do_9_2_prm_shutdown().
*/
enum sctp_disposition sctp_sf_autoclose_timer_expire(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
enum sctp_disposition disposition;
SCTP_INC_STATS(net, SCTP_MIB_AUTOCLOSE_EXPIREDS);
/* From 9.2 Shutdown of an Association
* Upon receipt of the SHUTDOWN primitive from its upper
* layer, the endpoint enters SHUTDOWN-PENDING state and
* remains there until all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_PENDING));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_start_shutdown(net, ep, asoc, type,
NULL, commands);
}
return disposition;
}
/*****************************************************************************
* These are sa state functions which could apply to all types of events.
****************************************************************************/
/*
* This table entry is not implemented.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_not_impl(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg, struct sctp_cmd_seq *commands)
{
return SCTP_DISPOSITION_NOT_IMPL;
}
/*
* This table entry represents a bug.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_bug(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg, struct sctp_cmd_seq *commands)
{
return SCTP_DISPOSITION_BUG;
}
/*
* This table entry represents the firing of a timer in the wrong state.
* Since timer deletion cannot be guaranteed a timer 'may' end up firing
* when the association is in the wrong state. This event should
* be ignored, so as to prevent any rearming of the timer.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
enum sctp_disposition sctp_sf_timer_ignore(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const union sctp_subtype type,
void *arg,
struct sctp_cmd_seq *commands)
{
pr_debug("%s: timer %d ignored\n", __func__, type.chunk);
return SCTP_DISPOSITION_CONSUME;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* Pull the SACK chunk based on the SACK header. */
static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk)
{
struct sctp_sackhdr *sack;
__u16 num_dup_tsns;
unsigned int len;
__u16 num_blocks;
/* Protect ourselves from reading too far into
* the skb from a bogus sender.
*/
sack = (struct sctp_sackhdr *) chunk->skb->data;
num_blocks = ntohs(sack->num_gap_ack_blocks);
num_dup_tsns = ntohs(sack->num_dup_tsns);
len = sizeof(struct sctp_sackhdr);
len += (num_blocks + num_dup_tsns) * sizeof(__u32);
if (len > chunk->skb->len)
return NULL;
skb_pull(chunk->skb, len);
return sack;
}
/* Create an ABORT packet to be sent as a response, with the specified
* error causes.
*/
static struct sctp_packet *sctp_abort_pkt_new(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
const void *payload, size_t paylen)
{
struct sctp_packet *packet;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
/* Make an ABORT.
* The T bit will be set if the asoc is NULL.
*/
abort = sctp_make_abort(asoc, chunk, paylen);
if (!abort) {
sctp_ootb_pkt_free(packet);
return NULL;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Add specified error causes, i.e., payload, to the
* end of the chunk.
*/
sctp_addto_chunk(abort, paylen, payload);
/* Set the skb to the belonging sock for accounting. */
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
}
return packet;
}
/* Allocate a packet for responding in the OOTB conditions. */
static struct sctp_packet *sctp_ootb_pkt_new(
struct net *net,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_transport *transport;
struct sctp_packet *packet;
__u16 sport, dport;
__u32 vtag;
/* Get the source and destination port from the inbound packet. */
sport = ntohs(chunk->sctp_hdr->dest);
dport = ntohs(chunk->sctp_hdr->source);
/* The V-tag is going to be the same as the inbound packet if no
* association exists, otherwise, use the peer's vtag.
*/
if (asoc) {
/* Special case the INIT-ACK as there is no peer's vtag
* yet.
*/
switch (chunk->chunk_hdr->type) {
case SCTP_CID_INIT:
case SCTP_CID_INIT_ACK:
{
struct sctp_initack_chunk *initack;
initack = (struct sctp_initack_chunk *)chunk->chunk_hdr;
vtag = ntohl(initack->init_hdr.init_tag);
break;
}
default:
vtag = asoc->peer.i.init_tag;
break;
}
} else {
/* Special case the INIT and stale COOKIE_ECHO as there is no
* vtag yet.
*/
switch (chunk->chunk_hdr->type) {
case SCTP_CID_INIT:
{
struct sctp_init_chunk *init;
init = (struct sctp_init_chunk *)chunk->chunk_hdr;
vtag = ntohl(init->init_hdr.init_tag);
break;
}
default:
vtag = ntohl(chunk->sctp_hdr->vtag);
break;
}
}
/* Make a transport for the bucket, Eliza... */
transport = sctp_transport_new(net, sctp_source(chunk), GFP_ATOMIC);
if (!transport)
goto nomem;
transport->encap_port = SCTP_INPUT_CB(chunk->skb)->encap_port;
/* Cache a route for the transport with the chunk's destination as
* the source address.
*/
sctp_transport_route(transport, (union sctp_addr *)&chunk->dest,
sctp_sk(net->sctp.ctl_sock));
packet = &transport->packet;
sctp_packet_init(packet, transport, sport, dport);
sctp_packet_config(packet, vtag, 0);
return packet;
nomem:
return NULL;
}
/* Free the packet allocated earlier for responding in the OOTB condition. */
void sctp_ootb_pkt_free(struct sctp_packet *packet)
{
sctp_transport_free(packet->transport);
}
/* Send a stale cookie error when a invalid COOKIE ECHO chunk is found */
static void sctp_send_stale_cookie_err(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
struct sctp_cmd_seq *commands,
struct sctp_chunk *err_chunk)
{
struct sctp_packet *packet;
if (err_chunk) {
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
struct sctp_signed_cookie *cookie;
/* Override the OOTB vtag from the cookie. */
cookie = chunk->subh.cookie_hdr;
packet->vtag = cookie->c.peer_vtag;
/* Set the skb to the belonging sock for accounting. */
err_chunk->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, err_chunk);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
} else
sctp_chunk_free (err_chunk);
}
}
/* Process a data chunk */
static int sctp_eat_data(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_cmd_seq *commands)
{
struct sctp_tsnmap *map = (struct sctp_tsnmap *)&asoc->peer.tsn_map;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
struct sctp_datahdr *data_hdr;
struct sctp_chunk *err;
enum sctp_verb deliver;
size_t datalen;
__u32 tsn;
int tmp;
data_hdr = (struct sctp_datahdr *)chunk->skb->data;
chunk->subh.data_hdr = data_hdr;
skb_pull(chunk->skb, sctp_datahdr_len(&asoc->stream));
tsn = ntohl(data_hdr->tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* ASSERT: Now skb->data is really the user data. */
/* Process ECN based congestion.
*
* Since the chunk structure is reused for all chunks within
* a packet, we use ecn_ce_done to track if we've already
* done CE processing for this packet.
*
* We need to do ECN processing even if we plan to discard the
* chunk later.
*/
if (asoc->peer.ecn_capable && !chunk->ecn_ce_done) {
struct sctp_af *af = SCTP_INPUT_CB(chunk->skb)->af;
chunk->ecn_ce_done = 1;
if (af->is_ce(sctp_gso_headskb(chunk->skb))) {
/* Do real work as side effect. */
sctp_add_cmd_sf(commands, SCTP_CMD_ECN_CE,
SCTP_U32(tsn));
}
}
tmp = sctp_tsnmap_check(&asoc->peer.tsn_map, tsn);
if (tmp < 0) {
/* The TSN is too high--silently discard the chunk and
* count on it getting retransmitted later.
*/
if (chunk->asoc)
chunk->asoc->stats.outofseqtsns++;
return SCTP_IERROR_HIGH_TSN;
} else if (tmp > 0) {
/* This is a duplicate. Record it. */
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_DUP, SCTP_U32(tsn));
return SCTP_IERROR_DUP_TSN;
}
/* This is a new TSN. */
/* Discard if there is no room in the receive window.
* Actually, allow a little bit of overflow (up to a MTU).
*/
datalen = ntohs(chunk->chunk_hdr->length);
datalen -= sctp_datachk_len(&asoc->stream);
deliver = SCTP_CMD_CHUNK_ULP;
/* Think about partial delivery. */
if ((datalen >= asoc->rwnd) && (!asoc->ulpq.pd_mode)) {
/* Even if we don't accept this chunk there is
* memory pressure.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PART_DELIVER, SCTP_NULL());
}
/* Spill over rwnd a little bit. Note: While allowed, this spill over
* seems a bit troublesome in that frag_point varies based on
* PMTU. In cases, such as loopback, this might be a rather
* large spill over.
*/
if ((!chunk->data_accepted) && (!asoc->rwnd || asoc->rwnd_over ||
(datalen > asoc->rwnd + asoc->frag_point))) {
/* If this is the next TSN, consider reneging to make
* room. Note: Playing nice with a confused sender. A
* malicious sender can still eat up all our buffer
* space and in the future we may want to detect and
* do more drastic reneging.
*/
if (sctp_tsnmap_has_gap(map) &&
(sctp_tsnmap_get_ctsn(map) + 1) == tsn) {
pr_debug("%s: reneging for tsn:%u\n", __func__, tsn);
deliver = SCTP_CMD_RENEGE;
} else {
pr_debug("%s: discard tsn:%u len:%zu, rwnd:%d\n",
__func__, tsn, datalen, asoc->rwnd);
return SCTP_IERROR_IGNORE_TSN;
}
}
/*
* Also try to renege to limit our memory usage in the event that
* we are under memory pressure
* If we can't renege, don't worry about it, the sk_rmem_schedule
* in sctp_ulpevent_make_rcvmsg will drop the frame if we grow our
* memory usage too much
*/
if (sk_under_memory_pressure(sk)) {
if (sctp_tsnmap_has_gap(map) &&
(sctp_tsnmap_get_ctsn(map) + 1) == tsn) {
pr_debug("%s: under pressure, reneging for tsn:%u\n",
__func__, tsn);
deliver = SCTP_CMD_RENEGE;
}
}
/*
* Section 3.3.10.9 No User Data (9)
*
* Cause of error
* ---------------
* No User Data: This error cause is returned to the originator of a
* DATA chunk if a received DATA chunk has no user data.
*/
if (unlikely(0 == datalen)) {
err = sctp_make_abort_no_data(asoc, chunk, tsn);
if (err) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_DATA));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_IERROR_NO_DATA;
}
chunk->data_accepted = 1;
/* Note: Some chunks may get overcounted (if we drop) or overcounted
* if we renege and the chunk arrives again.
*/
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
SCTP_INC_STATS(net, SCTP_MIB_INUNORDERCHUNKS);
if (chunk->asoc)
chunk->asoc->stats.iuodchunks++;
} else {
SCTP_INC_STATS(net, SCTP_MIB_INORDERCHUNKS);
if (chunk->asoc)
chunk->asoc->stats.iodchunks++;
}
/* RFC 2960 6.5 Stream Identifier and Stream Sequence Number
*
* If an endpoint receive a DATA chunk with an invalid stream
* identifier, it shall acknowledge the reception of the DATA chunk
* following the normal procedure, immediately send an ERROR chunk
* with cause set to "Invalid Stream Identifier" (See Section 3.3.10)
* and discard the DATA chunk.
*/
if (ntohs(data_hdr->stream) >= asoc->stream.incnt) {
/* Mark tsn as received even though we drop it */
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_TSN, SCTP_U32(tsn));
err = sctp_make_op_error(asoc, chunk, SCTP_ERROR_INV_STRM,
&data_hdr->stream,
sizeof(data_hdr->stream),
sizeof(u16));
if (err)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
return SCTP_IERROR_BAD_STREAM;
}
/* Check to see if the SSN is possible for this TSN.
* The biggest gap we can record is 4K wide. Since SSNs wrap
* at an unsigned short, there is no way that an SSN can
* wrap and for a valid TSN. We can simply check if the current
* SSN is smaller then the next expected one. If it is, it wrapped
* and is invalid.
*/
if (!asoc->stream.si->validate_data(chunk))
return SCTP_IERROR_PROTO_VIOLATION;
/* Send the data up to the user. Note: Schedule the
* SCTP_CMD_CHUNK_ULP cmd before the SCTP_CMD_GEN_SACK, as the SACK
* chunk needs the updated rwnd.
*/
sctp_add_cmd_sf(commands, deliver, SCTP_CHUNK(chunk));
return SCTP_IERROR_NO_ERROR;
}
| linux-master | net/sctp/sm_statefuns.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright Red Hat Inc. 2017
*
* This file is part of the SCTP kernel implementation
*
* These functions implement sctp diag support.
*
* Please send any bug reports or fixes you make to the
* email addresched(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Xin Long <[email protected]>
*/
#include <linux/module.h>
#include <linux/inet_diag.h>
#include <linux/sock_diag.h>
#include <net/sctp/sctp.h>
static void sctp_diag_get_info(struct sock *sk, struct inet_diag_msg *r,
void *info);
/* define some functions to make asoc/ep fill look clean */
static void inet_diag_msg_sctpasoc_fill(struct inet_diag_msg *r,
struct sock *sk,
struct sctp_association *asoc)
{
union sctp_addr laddr, paddr;
struct dst_entry *dst;
struct timer_list *t3_rtx = &asoc->peer.primary_path->T3_rtx_timer;
laddr = list_entry(asoc->base.bind_addr.address_list.next,
struct sctp_sockaddr_entry, list)->a;
paddr = asoc->peer.primary_path->ipaddr;
dst = asoc->peer.primary_path->dst;
r->idiag_family = sk->sk_family;
r->id.idiag_sport = htons(asoc->base.bind_addr.port);
r->id.idiag_dport = htons(asoc->peer.port);
r->id.idiag_if = dst ? dst->dev->ifindex : 0;
sock_diag_save_cookie(sk, r->id.idiag_cookie);
#if IS_ENABLED(CONFIG_IPV6)
if (sk->sk_family == AF_INET6) {
*(struct in6_addr *)r->id.idiag_src = laddr.v6.sin6_addr;
*(struct in6_addr *)r->id.idiag_dst = paddr.v6.sin6_addr;
} else
#endif
{
memset(&r->id.idiag_src, 0, sizeof(r->id.idiag_src));
memset(&r->id.idiag_dst, 0, sizeof(r->id.idiag_dst));
r->id.idiag_src[0] = laddr.v4.sin_addr.s_addr;
r->id.idiag_dst[0] = paddr.v4.sin_addr.s_addr;
}
r->idiag_state = asoc->state;
if (timer_pending(t3_rtx)) {
r->idiag_timer = SCTP_EVENT_TIMEOUT_T3_RTX;
r->idiag_retrans = asoc->rtx_data_chunks;
r->idiag_expires = jiffies_to_msecs(t3_rtx->expires - jiffies);
}
}
static int inet_diag_msg_sctpladdrs_fill(struct sk_buff *skb,
struct list_head *address_list)
{
struct sctp_sockaddr_entry *laddr;
int addrlen = sizeof(struct sockaddr_storage);
int addrcnt = 0;
struct nlattr *attr;
void *info = NULL;
list_for_each_entry_rcu(laddr, address_list, list)
addrcnt++;
attr = nla_reserve(skb, INET_DIAG_LOCALS, addrlen * addrcnt);
if (!attr)
return -EMSGSIZE;
info = nla_data(attr);
list_for_each_entry_rcu(laddr, address_list, list) {
memcpy(info, &laddr->a, sizeof(laddr->a));
memset(info + sizeof(laddr->a), 0, addrlen - sizeof(laddr->a));
info += addrlen;
}
return 0;
}
static int inet_diag_msg_sctpaddrs_fill(struct sk_buff *skb,
struct sctp_association *asoc)
{
int addrlen = sizeof(struct sockaddr_storage);
struct sctp_transport *from;
struct nlattr *attr;
void *info = NULL;
attr = nla_reserve(skb, INET_DIAG_PEERS,
addrlen * asoc->peer.transport_count);
if (!attr)
return -EMSGSIZE;
info = nla_data(attr);
list_for_each_entry(from, &asoc->peer.transport_addr_list,
transports) {
memcpy(info, &from->ipaddr, sizeof(from->ipaddr));
memset(info + sizeof(from->ipaddr), 0,
addrlen - sizeof(from->ipaddr));
info += addrlen;
}
return 0;
}
/* sctp asoc/ep fill*/
static int inet_sctp_diag_fill(struct sock *sk, struct sctp_association *asoc,
struct sk_buff *skb,
const struct inet_diag_req_v2 *req,
struct user_namespace *user_ns,
int portid, u32 seq, u16 nlmsg_flags,
const struct nlmsghdr *unlh,
bool net_admin)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct list_head *addr_list;
struct inet_diag_msg *r;
struct nlmsghdr *nlh;
int ext = req->idiag_ext;
struct sctp_infox infox;
void *info = NULL;
nlh = nlmsg_put(skb, portid, seq, unlh->nlmsg_type, sizeof(*r),
nlmsg_flags);
if (!nlh)
return -EMSGSIZE;
r = nlmsg_data(nlh);
BUG_ON(!sk_fullsock(sk));
r->idiag_timer = 0;
r->idiag_retrans = 0;
r->idiag_expires = 0;
if (asoc) {
inet_diag_msg_sctpasoc_fill(r, sk, asoc);
} else {
inet_diag_msg_common_fill(r, sk);
r->idiag_state = sk->sk_state;
}
if (inet_diag_msg_attrs_fill(sk, skb, r, ext, user_ns, net_admin))
goto errout;
if (ext & (1 << (INET_DIAG_SKMEMINFO - 1))) {
u32 mem[SK_MEMINFO_VARS];
int amt;
if (asoc && asoc->ep->sndbuf_policy)
amt = asoc->sndbuf_used;
else
amt = sk_wmem_alloc_get(sk);
mem[SK_MEMINFO_WMEM_ALLOC] = amt;
if (asoc && asoc->ep->rcvbuf_policy)
amt = atomic_read(&asoc->rmem_alloc);
else
amt = sk_rmem_alloc_get(sk);
mem[SK_MEMINFO_RMEM_ALLOC] = amt;
mem[SK_MEMINFO_RCVBUF] = sk->sk_rcvbuf;
mem[SK_MEMINFO_SNDBUF] = sk->sk_sndbuf;
mem[SK_MEMINFO_FWD_ALLOC] = sk->sk_forward_alloc;
mem[SK_MEMINFO_WMEM_QUEUED] = sk->sk_wmem_queued;
mem[SK_MEMINFO_OPTMEM] = atomic_read(&sk->sk_omem_alloc);
mem[SK_MEMINFO_BACKLOG] = READ_ONCE(sk->sk_backlog.len);
mem[SK_MEMINFO_DROPS] = atomic_read(&sk->sk_drops);
if (nla_put(skb, INET_DIAG_SKMEMINFO, sizeof(mem), &mem) < 0)
goto errout;
}
if (ext & (1 << (INET_DIAG_INFO - 1))) {
struct nlattr *attr;
attr = nla_reserve_64bit(skb, INET_DIAG_INFO,
sizeof(struct sctp_info),
INET_DIAG_PAD);
if (!attr)
goto errout;
info = nla_data(attr);
}
infox.sctpinfo = (struct sctp_info *)info;
infox.asoc = asoc;
sctp_diag_get_info(sk, r, &infox);
addr_list = asoc ? &asoc->base.bind_addr.address_list
: &ep->base.bind_addr.address_list;
if (inet_diag_msg_sctpladdrs_fill(skb, addr_list))
goto errout;
if (asoc && (ext & (1 << (INET_DIAG_CONG - 1))))
if (nla_put_string(skb, INET_DIAG_CONG, "reno") < 0)
goto errout;
if (asoc && inet_diag_msg_sctpaddrs_fill(skb, asoc))
goto errout;
nlmsg_end(skb, nlh);
return 0;
errout:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
/* callback and param */
struct sctp_comm_param {
struct sk_buff *skb;
struct netlink_callback *cb;
const struct inet_diag_req_v2 *r;
const struct nlmsghdr *nlh;
bool net_admin;
};
static size_t inet_assoc_attr_size(struct sctp_association *asoc)
{
int addrlen = sizeof(struct sockaddr_storage);
int addrcnt = 0;
struct sctp_sockaddr_entry *laddr;
list_for_each_entry_rcu(laddr, &asoc->base.bind_addr.address_list,
list)
addrcnt++;
return nla_total_size(sizeof(struct sctp_info))
+ nla_total_size(addrlen * asoc->peer.transport_count)
+ nla_total_size(addrlen * addrcnt)
+ nla_total_size(sizeof(struct inet_diag_msg))
+ inet_diag_msg_attrs_size()
+ nla_total_size(sizeof(struct inet_diag_meminfo))
+ 64;
}
static int sctp_sock_dump_one(struct sctp_endpoint *ep, struct sctp_transport *tsp, void *p)
{
struct sctp_association *assoc = tsp->asoc;
struct sctp_comm_param *commp = p;
struct sock *sk = ep->base.sk;
const struct inet_diag_req_v2 *req = commp->r;
struct sk_buff *skb = commp->skb;
struct sk_buff *rep;
int err;
err = sock_diag_check_cookie(sk, req->id.idiag_cookie);
if (err)
return err;
rep = nlmsg_new(inet_assoc_attr_size(assoc), GFP_KERNEL);
if (!rep)
return -ENOMEM;
lock_sock(sk);
if (ep != assoc->ep) {
err = -EAGAIN;
goto out;
}
err = inet_sctp_diag_fill(sk, assoc, rep, req, sk_user_ns(NETLINK_CB(skb).sk),
NETLINK_CB(skb).portid, commp->nlh->nlmsg_seq, 0,
commp->nlh, commp->net_admin);
if (err < 0) {
WARN_ON(err == -EMSGSIZE);
goto out;
}
release_sock(sk);
return nlmsg_unicast(sock_net(skb->sk)->diag_nlsk, rep, NETLINK_CB(skb).portid);
out:
release_sock(sk);
kfree_skb(rep);
return err;
}
static int sctp_sock_dump(struct sctp_endpoint *ep, struct sctp_transport *tsp, void *p)
{
struct sctp_comm_param *commp = p;
struct sock *sk = ep->base.sk;
struct sk_buff *skb = commp->skb;
struct netlink_callback *cb = commp->cb;
const struct inet_diag_req_v2 *r = commp->r;
struct sctp_association *assoc;
int err = 0;
lock_sock(sk);
if (ep != tsp->asoc->ep)
goto release;
list_for_each_entry(assoc, &ep->asocs, asocs) {
if (cb->args[4] < cb->args[1])
goto next;
if (r->id.idiag_sport != htons(assoc->base.bind_addr.port) &&
r->id.idiag_sport)
goto next;
if (r->id.idiag_dport != htons(assoc->peer.port) &&
r->id.idiag_dport)
goto next;
if (!cb->args[3] &&
inet_sctp_diag_fill(sk, NULL, skb, r,
sk_user_ns(NETLINK_CB(cb->skb).sk),
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
NLM_F_MULTI, cb->nlh,
commp->net_admin) < 0) {
err = 1;
goto release;
}
cb->args[3] = 1;
if (inet_sctp_diag_fill(sk, assoc, skb, r,
sk_user_ns(NETLINK_CB(cb->skb).sk),
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, 0, cb->nlh,
commp->net_admin) < 0) {
err = 1;
goto release;
}
next:
cb->args[4]++;
}
cb->args[1] = 0;
cb->args[3] = 0;
cb->args[4] = 0;
release:
release_sock(sk);
return err;
}
static int sctp_sock_filter(struct sctp_endpoint *ep, struct sctp_transport *tsp, void *p)
{
struct sctp_comm_param *commp = p;
struct sock *sk = ep->base.sk;
const struct inet_diag_req_v2 *r = commp->r;
/* find the ep only once through the transports by this condition */
if (!list_is_first(&tsp->asoc->asocs, &ep->asocs))
return 0;
if (r->sdiag_family != AF_UNSPEC && sk->sk_family != r->sdiag_family)
return 0;
return 1;
}
static int sctp_ep_dump(struct sctp_endpoint *ep, void *p)
{
struct sctp_comm_param *commp = p;
struct sock *sk = ep->base.sk;
struct sk_buff *skb = commp->skb;
struct netlink_callback *cb = commp->cb;
const struct inet_diag_req_v2 *r = commp->r;
struct net *net = sock_net(skb->sk);
struct inet_sock *inet = inet_sk(sk);
int err = 0;
if (!net_eq(sock_net(sk), net))
goto out;
if (cb->args[4] < cb->args[1])
goto next;
if (!(r->idiag_states & TCPF_LISTEN) && !list_empty(&ep->asocs))
goto next;
if (r->sdiag_family != AF_UNSPEC &&
sk->sk_family != r->sdiag_family)
goto next;
if (r->id.idiag_sport != inet->inet_sport &&
r->id.idiag_sport)
goto next;
if (r->id.idiag_dport != inet->inet_dport &&
r->id.idiag_dport)
goto next;
if (inet_sctp_diag_fill(sk, NULL, skb, r,
sk_user_ns(NETLINK_CB(cb->skb).sk),
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
cb->nlh, commp->net_admin) < 0) {
err = 2;
goto out;
}
next:
cb->args[4]++;
out:
return err;
}
/* define the functions for sctp_diag_handler*/
static void sctp_diag_get_info(struct sock *sk, struct inet_diag_msg *r,
void *info)
{
struct sctp_infox *infox = (struct sctp_infox *)info;
if (infox->asoc) {
r->idiag_rqueue = atomic_read(&infox->asoc->rmem_alloc);
r->idiag_wqueue = infox->asoc->sndbuf_used;
} else {
r->idiag_rqueue = READ_ONCE(sk->sk_ack_backlog);
r->idiag_wqueue = READ_ONCE(sk->sk_max_ack_backlog);
}
if (infox->sctpinfo)
sctp_get_sctp_info(sk, infox->asoc, infox->sctpinfo);
}
static int sctp_diag_dump_one(struct netlink_callback *cb,
const struct inet_diag_req_v2 *req)
{
struct sk_buff *skb = cb->skb;
struct net *net = sock_net(skb->sk);
const struct nlmsghdr *nlh = cb->nlh;
union sctp_addr laddr, paddr;
int dif = req->id.idiag_if;
struct sctp_comm_param commp = {
.skb = skb,
.r = req,
.nlh = nlh,
.net_admin = netlink_net_capable(skb, CAP_NET_ADMIN),
};
if (req->sdiag_family == AF_INET) {
laddr.v4.sin_port = req->id.idiag_sport;
laddr.v4.sin_addr.s_addr = req->id.idiag_src[0];
laddr.v4.sin_family = AF_INET;
paddr.v4.sin_port = req->id.idiag_dport;
paddr.v4.sin_addr.s_addr = req->id.idiag_dst[0];
paddr.v4.sin_family = AF_INET;
} else {
laddr.v6.sin6_port = req->id.idiag_sport;
memcpy(&laddr.v6.sin6_addr, req->id.idiag_src,
sizeof(laddr.v6.sin6_addr));
laddr.v6.sin6_family = AF_INET6;
paddr.v6.sin6_port = req->id.idiag_dport;
memcpy(&paddr.v6.sin6_addr, req->id.idiag_dst,
sizeof(paddr.v6.sin6_addr));
paddr.v6.sin6_family = AF_INET6;
}
return sctp_transport_lookup_process(sctp_sock_dump_one,
net, &laddr, &paddr, &commp, dif);
}
static void sctp_diag_dump(struct sk_buff *skb, struct netlink_callback *cb,
const struct inet_diag_req_v2 *r)
{
u32 idiag_states = r->idiag_states;
struct net *net = sock_net(skb->sk);
struct sctp_comm_param commp = {
.skb = skb,
.cb = cb,
.r = r,
.net_admin = netlink_net_capable(cb->skb, CAP_NET_ADMIN),
};
int pos = cb->args[2];
/* eps hashtable dumps
* args:
* 0 : if it will traversal listen sock
* 1 : to record the sock pos of this time's traversal
* 4 : to work as a temporary variable to traversal list
*/
if (cb->args[0] == 0) {
if (!(idiag_states & TCPF_LISTEN))
goto skip;
if (sctp_for_each_endpoint(sctp_ep_dump, &commp))
goto done;
skip:
cb->args[0] = 1;
cb->args[1] = 0;
cb->args[4] = 0;
}
/* asocs by transport hashtable dump
* args:
* 1 : to record the assoc pos of this time's traversal
* 2 : to record the transport pos of this time's traversal
* 3 : to mark if we have dumped the ep info of the current asoc
* 4 : to work as a temporary variable to traversal list
* 5 : to save the sk we get from travelsing the tsp list.
*/
if (!(idiag_states & ~(TCPF_LISTEN | TCPF_CLOSE)))
goto done;
sctp_transport_traverse_process(sctp_sock_filter, sctp_sock_dump,
net, &pos, &commp);
cb->args[2] = pos;
done:
cb->args[1] = cb->args[4];
cb->args[4] = 0;
}
static const struct inet_diag_handler sctp_diag_handler = {
.dump = sctp_diag_dump,
.dump_one = sctp_diag_dump_one,
.idiag_get_info = sctp_diag_get_info,
.idiag_type = IPPROTO_SCTP,
.idiag_info_size = sizeof(struct sctp_info),
};
static int __init sctp_diag_init(void)
{
return inet_diag_register(&sctp_diag_handler);
}
static void __exit sctp_diag_exit(void)
{
inet_diag_unregister(&sctp_diag_handler);
}
module_init(sctp_diag_init);
module_exit(sctp_diag_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_NETLINK, NETLINK_SOCK_DIAG, 2-132);
| linux-master | net/sctp/diag.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
*
* This file is part of the SCTP kernel implementation
*
* These functions work with the state functions in sctp_sm_statefuns.c
* to implement that state operations. These functions implement the
* steps which require modifying existing data structures.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Jon Grimm <[email protected]>
* Hui Huang <[email protected]>
* Dajiang Zhang <[email protected]>
* Daisy Chang <[email protected]>
* Sridhar Samudrala <[email protected]>
* Ardelle Fan <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/skbuff.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/ip.h>
#include <linux/gfp.h>
#include <net/sock.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/stream_sched.h>
static int sctp_cmd_interpreter(enum sctp_event_type event_type,
union sctp_subtype subtype,
enum sctp_state state,
struct sctp_endpoint *ep,
struct sctp_association *asoc,
void *event_arg,
enum sctp_disposition status,
struct sctp_cmd_seq *commands,
gfp_t gfp);
static int sctp_side_effects(enum sctp_event_type event_type,
union sctp_subtype subtype,
enum sctp_state state,
struct sctp_endpoint *ep,
struct sctp_association **asoc,
void *event_arg,
enum sctp_disposition status,
struct sctp_cmd_seq *commands,
gfp_t gfp);
/********************************************************************
* Helper functions
********************************************************************/
/* A helper function for delayed processing of INET ECN CE bit. */
static void sctp_do_ecn_ce_work(struct sctp_association *asoc,
__u32 lowest_tsn)
{
/* Save the TSN away for comparison when we receive CWR */
asoc->last_ecne_tsn = lowest_tsn;
asoc->need_ecne = 1;
}
/* Helper function for delayed processing of SCTP ECNE chunk. */
/* RFC 2960 Appendix A
*
* RFC 2481 details a specific bit for a sender to send in
* the header of its next outbound TCP segment to indicate to
* its peer that it has reduced its congestion window. This
* is termed the CWR bit. For SCTP the same indication is made
* by including the CWR chunk. This chunk contains one data
* element, i.e. the TSN number that was sent in the ECNE chunk.
* This element represents the lowest TSN number in the datagram
* that was originally marked with the CE bit.
*/
static struct sctp_chunk *sctp_do_ecn_ecne_work(struct sctp_association *asoc,
__u32 lowest_tsn,
struct sctp_chunk *chunk)
{
struct sctp_chunk *repl;
/* Our previously transmitted packet ran into some congestion
* so we should take action by reducing cwnd and ssthresh
* and then ACK our peer that we we've done so by
* sending a CWR.
*/
/* First, try to determine if we want to actually lower
* our cwnd variables. Only lower them if the ECNE looks more
* recent than the last response.
*/
if (TSN_lt(asoc->last_cwr_tsn, lowest_tsn)) {
struct sctp_transport *transport;
/* Find which transport's congestion variables
* need to be adjusted.
*/
transport = sctp_assoc_lookup_tsn(asoc, lowest_tsn);
/* Update the congestion variables. */
if (transport)
sctp_transport_lower_cwnd(transport,
SCTP_LOWER_CWND_ECNE);
asoc->last_cwr_tsn = lowest_tsn;
}
/* Always try to quiet the other end. In case of lost CWR,
* resend last_cwr_tsn.
*/
repl = sctp_make_cwr(asoc, asoc->last_cwr_tsn, chunk);
/* If we run out of memory, it will look like a lost CWR. We'll
* get back in sync eventually.
*/
return repl;
}
/* Helper function to do delayed processing of ECN CWR chunk. */
static void sctp_do_ecn_cwr_work(struct sctp_association *asoc,
__u32 lowest_tsn)
{
/* Turn off ECNE getting auto-prepended to every outgoing
* packet
*/
asoc->need_ecne = 0;
}
/* Generate SACK if necessary. We call this at the end of a packet. */
static int sctp_gen_sack(struct sctp_association *asoc, int force,
struct sctp_cmd_seq *commands)
{
struct sctp_transport *trans = asoc->peer.last_data_from;
__u32 ctsn, max_tsn_seen;
struct sctp_chunk *sack;
int error = 0;
if (force ||
(!trans && (asoc->param_flags & SPP_SACKDELAY_DISABLE)) ||
(trans && (trans->param_flags & SPP_SACKDELAY_DISABLE)))
asoc->peer.sack_needed = 1;
ctsn = sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map);
max_tsn_seen = sctp_tsnmap_get_max_tsn_seen(&asoc->peer.tsn_map);
/* From 12.2 Parameters necessary per association (i.e. the TCB):
*
* Ack State : This flag indicates if the next received packet
* : is to be responded to with a SACK. ...
* : When DATA chunks are out of order, SACK's
* : are not delayed (see Section 6).
*
* [This is actually not mentioned in Section 6, but we
* implement it here anyway. --piggy]
*/
if (max_tsn_seen != ctsn)
asoc->peer.sack_needed = 1;
/* From 6.2 Acknowledgement on Reception of DATA Chunks:
*
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically,
* an acknowledgement SHOULD be generated for at least every
* second packet (not every second DATA chunk) received, and
* SHOULD be generated within 200 ms of the arrival of any
* unacknowledged DATA chunk. ...
*/
if (!asoc->peer.sack_needed) {
asoc->peer.sack_cnt++;
/* Set the SACK delay timeout based on the
* SACK delay for the last transport
* data was received from, or the default
* for the association.
*/
if (trans) {
/* We will need a SACK for the next packet. */
if (asoc->peer.sack_cnt >= trans->sackfreq - 1)
asoc->peer.sack_needed = 1;
asoc->timeouts[SCTP_EVENT_TIMEOUT_SACK] =
trans->sackdelay;
} else {
/* We will need a SACK for the next packet. */
if (asoc->peer.sack_cnt >= asoc->sackfreq - 1)
asoc->peer.sack_needed = 1;
asoc->timeouts[SCTP_EVENT_TIMEOUT_SACK] =
asoc->sackdelay;
}
/* Restart the SACK timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_SACK));
} else {
__u32 old_a_rwnd = asoc->a_rwnd;
asoc->a_rwnd = asoc->rwnd;
sack = sctp_make_sack(asoc);
if (!sack) {
asoc->a_rwnd = old_a_rwnd;
goto nomem;
}
asoc->peer.sack_needed = 0;
asoc->peer.sack_cnt = 0;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(sack));
/* Stop the SACK timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_SACK));
}
return error;
nomem:
error = -ENOMEM;
return error;
}
/* When the T3-RTX timer expires, it calls this function to create the
* relevant state machine event.
*/
void sctp_generate_t3_rtx_event(struct timer_list *t)
{
struct sctp_transport *transport =
from_timer(transport, t, T3_rtx_timer);
struct sctp_association *asoc = transport->asoc;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
int error;
/* Check whether a task is in the sock. */
bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
pr_debug("%s: sock is busy\n", __func__);
/* Try again later. */
if (!mod_timer(&transport->T3_rtx_timer, jiffies + (HZ/20)))
sctp_transport_hold(transport);
goto out_unlock;
}
/* Run through the state machine. */
error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT,
SCTP_ST_TIMEOUT(SCTP_EVENT_TIMEOUT_T3_RTX),
asoc->state,
asoc->ep, asoc,
transport, GFP_ATOMIC);
if (error)
sk->sk_err = -error;
out_unlock:
bh_unlock_sock(sk);
sctp_transport_put(transport);
}
/* This is a sa interface for producing timeout events. It works
* for timeouts which use the association as their parameter.
*/
static void sctp_generate_timeout_event(struct sctp_association *asoc,
enum sctp_event_timeout timeout_type)
{
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
int error = 0;
bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
pr_debug("%s: sock is busy: timer %d\n", __func__,
timeout_type);
/* Try again later. */
if (!mod_timer(&asoc->timers[timeout_type], jiffies + (HZ/20)))
sctp_association_hold(asoc);
goto out_unlock;
}
/* Is this association really dead and just waiting around for
* the timer to let go of the reference?
*/
if (asoc->base.dead)
goto out_unlock;
/* Run through the state machine. */
error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT,
SCTP_ST_TIMEOUT(timeout_type),
asoc->state, asoc->ep, asoc,
(void *)timeout_type, GFP_ATOMIC);
if (error)
sk->sk_err = -error;
out_unlock:
bh_unlock_sock(sk);
sctp_association_put(asoc);
}
static void sctp_generate_t1_cookie_event(struct timer_list *t)
{
struct sctp_association *asoc =
from_timer(asoc, t, timers[SCTP_EVENT_TIMEOUT_T1_COOKIE]);
sctp_generate_timeout_event(asoc, SCTP_EVENT_TIMEOUT_T1_COOKIE);
}
static void sctp_generate_t1_init_event(struct timer_list *t)
{
struct sctp_association *asoc =
from_timer(asoc, t, timers[SCTP_EVENT_TIMEOUT_T1_INIT]);
sctp_generate_timeout_event(asoc, SCTP_EVENT_TIMEOUT_T1_INIT);
}
static void sctp_generate_t2_shutdown_event(struct timer_list *t)
{
struct sctp_association *asoc =
from_timer(asoc, t, timers[SCTP_EVENT_TIMEOUT_T2_SHUTDOWN]);
sctp_generate_timeout_event(asoc, SCTP_EVENT_TIMEOUT_T2_SHUTDOWN);
}
static void sctp_generate_t4_rto_event(struct timer_list *t)
{
struct sctp_association *asoc =
from_timer(asoc, t, timers[SCTP_EVENT_TIMEOUT_T4_RTO]);
sctp_generate_timeout_event(asoc, SCTP_EVENT_TIMEOUT_T4_RTO);
}
static void sctp_generate_t5_shutdown_guard_event(struct timer_list *t)
{
struct sctp_association *asoc =
from_timer(asoc, t,
timers[SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD]);
sctp_generate_timeout_event(asoc,
SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD);
} /* sctp_generate_t5_shutdown_guard_event() */
static void sctp_generate_autoclose_event(struct timer_list *t)
{
struct sctp_association *asoc =
from_timer(asoc, t, timers[SCTP_EVENT_TIMEOUT_AUTOCLOSE]);
sctp_generate_timeout_event(asoc, SCTP_EVENT_TIMEOUT_AUTOCLOSE);
}
/* Generate a heart beat event. If the sock is busy, reschedule. Make
* sure that the transport is still valid.
*/
void sctp_generate_heartbeat_event(struct timer_list *t)
{
struct sctp_transport *transport = from_timer(transport, t, hb_timer);
struct sctp_association *asoc = transport->asoc;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
u32 elapsed, timeout;
int error = 0;
bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
pr_debug("%s: sock is busy\n", __func__);
/* Try again later. */
if (!mod_timer(&transport->hb_timer, jiffies + (HZ/20)))
sctp_transport_hold(transport);
goto out_unlock;
}
/* Check if we should still send the heartbeat or reschedule */
elapsed = jiffies - transport->last_time_sent;
timeout = sctp_transport_timeout(transport);
if (elapsed < timeout) {
elapsed = timeout - elapsed;
if (!mod_timer(&transport->hb_timer, jiffies + elapsed))
sctp_transport_hold(transport);
goto out_unlock;
}
error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT,
SCTP_ST_TIMEOUT(SCTP_EVENT_TIMEOUT_HEARTBEAT),
asoc->state, asoc->ep, asoc,
transport, GFP_ATOMIC);
if (error)
sk->sk_err = -error;
out_unlock:
bh_unlock_sock(sk);
sctp_transport_put(transport);
}
/* Handle the timeout of the ICMP protocol unreachable timer. Trigger
* the correct state machine transition that will close the association.
*/
void sctp_generate_proto_unreach_event(struct timer_list *t)
{
struct sctp_transport *transport =
from_timer(transport, t, proto_unreach_timer);
struct sctp_association *asoc = transport->asoc;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
pr_debug("%s: sock is busy\n", __func__);
/* Try again later. */
if (!mod_timer(&transport->proto_unreach_timer,
jiffies + (HZ/20)))
sctp_transport_hold(transport);
goto out_unlock;
}
/* Is this structure just waiting around for us to actually
* get destroyed?
*/
if (asoc->base.dead)
goto out_unlock;
sctp_do_sm(net, SCTP_EVENT_T_OTHER,
SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH),
asoc->state, asoc->ep, asoc, transport, GFP_ATOMIC);
out_unlock:
bh_unlock_sock(sk);
sctp_transport_put(transport);
}
/* Handle the timeout of the RE-CONFIG timer. */
void sctp_generate_reconf_event(struct timer_list *t)
{
struct sctp_transport *transport =
from_timer(transport, t, reconf_timer);
struct sctp_association *asoc = transport->asoc;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
int error = 0;
bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
pr_debug("%s: sock is busy\n", __func__);
/* Try again later. */
if (!mod_timer(&transport->reconf_timer, jiffies + (HZ / 20)))
sctp_transport_hold(transport);
goto out_unlock;
}
/* This happens when the response arrives after the timer is triggered. */
if (!asoc->strreset_chunk)
goto out_unlock;
error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT,
SCTP_ST_TIMEOUT(SCTP_EVENT_TIMEOUT_RECONF),
asoc->state, asoc->ep, asoc,
transport, GFP_ATOMIC);
if (error)
sk->sk_err = -error;
out_unlock:
bh_unlock_sock(sk);
sctp_transport_put(transport);
}
/* Handle the timeout of the probe timer. */
void sctp_generate_probe_event(struct timer_list *t)
{
struct sctp_transport *transport = from_timer(transport, t, probe_timer);
struct sctp_association *asoc = transport->asoc;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
int error = 0;
bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
pr_debug("%s: sock is busy\n", __func__);
/* Try again later. */
if (!mod_timer(&transport->probe_timer, jiffies + (HZ / 20)))
sctp_transport_hold(transport);
goto out_unlock;
}
error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT,
SCTP_ST_TIMEOUT(SCTP_EVENT_TIMEOUT_PROBE),
asoc->state, asoc->ep, asoc,
transport, GFP_ATOMIC);
if (error)
sk->sk_err = -error;
out_unlock:
bh_unlock_sock(sk);
sctp_transport_put(transport);
}
/* Inject a SACK Timeout event into the state machine. */
static void sctp_generate_sack_event(struct timer_list *t)
{
struct sctp_association *asoc =
from_timer(asoc, t, timers[SCTP_EVENT_TIMEOUT_SACK]);
sctp_generate_timeout_event(asoc, SCTP_EVENT_TIMEOUT_SACK);
}
sctp_timer_event_t *sctp_timer_events[SCTP_NUM_TIMEOUT_TYPES] = {
[SCTP_EVENT_TIMEOUT_NONE] = NULL,
[SCTP_EVENT_TIMEOUT_T1_COOKIE] = sctp_generate_t1_cookie_event,
[SCTP_EVENT_TIMEOUT_T1_INIT] = sctp_generate_t1_init_event,
[SCTP_EVENT_TIMEOUT_T2_SHUTDOWN] = sctp_generate_t2_shutdown_event,
[SCTP_EVENT_TIMEOUT_T3_RTX] = NULL,
[SCTP_EVENT_TIMEOUT_T4_RTO] = sctp_generate_t4_rto_event,
[SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD] =
sctp_generate_t5_shutdown_guard_event,
[SCTP_EVENT_TIMEOUT_HEARTBEAT] = NULL,
[SCTP_EVENT_TIMEOUT_RECONF] = NULL,
[SCTP_EVENT_TIMEOUT_SACK] = sctp_generate_sack_event,
[SCTP_EVENT_TIMEOUT_AUTOCLOSE] = sctp_generate_autoclose_event,
};
/* RFC 2960 8.2 Path Failure Detection
*
* When its peer endpoint is multi-homed, an endpoint should keep a
* error counter for each of the destination transport addresses of the
* peer endpoint.
*
* Each time the T3-rtx timer expires on any address, or when a
* HEARTBEAT sent to an idle address is not acknowledged within a RTO,
* the error counter of that destination address will be incremented.
* When the value in the error counter exceeds the protocol parameter
* 'Path.Max.Retrans' of that destination address, the endpoint should
* mark the destination transport address as inactive, and a
* notification SHOULD be sent to the upper layer.
*
*/
static void sctp_do_8_2_transport_strike(struct sctp_cmd_seq *commands,
struct sctp_association *asoc,
struct sctp_transport *transport,
int is_hb)
{
/* The check for association's overall error counter exceeding the
* threshold is done in the state function.
*/
/* We are here due to a timer expiration. If the timer was
* not a HEARTBEAT, then normal error tracking is done.
* If the timer was a heartbeat, we only increment error counts
* when we already have an outstanding HEARTBEAT that has not
* been acknowledged.
* Additionally, some tranport states inhibit error increments.
*/
if (!is_hb) {
asoc->overall_error_count++;
if (transport->state != SCTP_INACTIVE)
transport->error_count++;
} else if (transport->hb_sent) {
if (transport->state != SCTP_UNCONFIRMED)
asoc->overall_error_count++;
if (transport->state != SCTP_INACTIVE)
transport->error_count++;
}
/* If the transport error count is greater than the pf_retrans
* threshold, and less than pathmaxrtx, and if the current state
* is SCTP_ACTIVE, then mark this transport as Partially Failed,
* see SCTP Quick Failover Draft, section 5.1
*/
if (asoc->base.net->sctp.pf_enable &&
transport->state == SCTP_ACTIVE &&
transport->error_count < transport->pathmaxrxt &&
transport->error_count > transport->pf_retrans) {
sctp_assoc_control_transport(asoc, transport,
SCTP_TRANSPORT_PF,
0);
/* Update the hb timer to resend a heartbeat every rto */
sctp_transport_reset_hb_timer(transport);
}
if (transport->state != SCTP_INACTIVE &&
(transport->error_count > transport->pathmaxrxt)) {
pr_debug("%s: association:%p transport addr:%pISpc failed\n",
__func__, asoc, &transport->ipaddr.sa);
sctp_assoc_control_transport(asoc, transport,
SCTP_TRANSPORT_DOWN,
SCTP_FAILED_THRESHOLD);
}
if (transport->error_count > transport->ps_retrans &&
asoc->peer.primary_path == transport &&
asoc->peer.active_path != transport)
sctp_assoc_set_primary(asoc, asoc->peer.active_path);
/* E2) For the destination address for which the timer
* expires, set RTO <- RTO * 2 ("back off the timer"). The
* maximum value discussed in rule C7 above (RTO.max) may be
* used to provide an upper bound to this doubling operation.
*
* Special Case: the first HB doesn't trigger exponential backoff.
* The first unacknowledged HB triggers it. We do this with a flag
* that indicates that we have an outstanding HB.
*/
if (!is_hb || transport->hb_sent) {
transport->rto = min((transport->rto * 2), transport->asoc->rto_max);
sctp_max_rto(asoc, transport);
}
}
/* Worker routine to handle INIT command failure. */
static void sctp_cmd_init_failed(struct sctp_cmd_seq *commands,
struct sctp_association *asoc,
unsigned int error)
{
struct sctp_ulpevent *event;
event = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_CANT_STR_ASSOC,
(__u16)error, 0, 0, NULL,
GFP_ATOMIC);
if (event)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(event));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
/* SEND_FAILED sent later when cleaning up the association. */
asoc->outqueue.error = error;
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
}
/* Worker routine to handle SCTP_CMD_ASSOC_FAILED. */
static void sctp_cmd_assoc_failed(struct sctp_cmd_seq *commands,
struct sctp_association *asoc,
enum sctp_event_type event_type,
union sctp_subtype subtype,
struct sctp_chunk *chunk,
unsigned int error)
{
struct sctp_ulpevent *event;
struct sctp_chunk *abort;
/* Cancel any partial delivery in progress. */
asoc->stream.si->abort_pd(&asoc->ulpq, GFP_ATOMIC);
if (event_type == SCTP_EVENT_T_CHUNK && subtype.chunk == SCTP_CID_ABORT)
event = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_COMM_LOST,
(__u16)error, 0, 0, chunk,
GFP_ATOMIC);
else
event = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_COMM_LOST,
(__u16)error, 0, 0, NULL,
GFP_ATOMIC);
if (event)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(event));
if (asoc->overall_error_count >= asoc->max_retrans) {
abort = sctp_make_violation_max_retrans(asoc, chunk);
if (abort)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
/* SEND_FAILED sent later when cleaning up the association. */
asoc->outqueue.error = error;
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
}
/* Process an init chunk (may be real INIT/INIT-ACK or an embedded INIT
* inside the cookie. In reality, this is only used for INIT-ACK processing
* since all other cases use "temporary" associations and can do all
* their work in statefuns directly.
*/
static int sctp_cmd_process_init(struct sctp_cmd_seq *commands,
struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_init_chunk *peer_init,
gfp_t gfp)
{
int error;
/* We only process the init as a sideeffect in a single
* case. This is when we process the INIT-ACK. If we
* fail during INIT processing (due to malloc problems),
* just return the error and stop processing the stack.
*/
if (!sctp_process_init(asoc, chunk, sctp_source(chunk), peer_init, gfp))
error = -ENOMEM;
else
error = 0;
return error;
}
/* Helper function to break out starting up of heartbeat timers. */
static void sctp_cmd_hb_timers_start(struct sctp_cmd_seq *cmds,
struct sctp_association *asoc)
{
struct sctp_transport *t;
/* Start a heartbeat timer for each transport on the association.
* hold a reference on the transport to make sure none of
* the needed data structures go away.
*/
list_for_each_entry(t, &asoc->peer.transport_addr_list, transports)
sctp_transport_reset_hb_timer(t);
}
static void sctp_cmd_hb_timers_stop(struct sctp_cmd_seq *cmds,
struct sctp_association *asoc)
{
struct sctp_transport *t;
/* Stop all heartbeat timers. */
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
if (del_timer(&t->hb_timer))
sctp_transport_put(t);
}
}
/* Helper function to stop any pending T3-RTX timers */
static void sctp_cmd_t3_rtx_timers_stop(struct sctp_cmd_seq *cmds,
struct sctp_association *asoc)
{
struct sctp_transport *t;
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
if (del_timer(&t->T3_rtx_timer))
sctp_transport_put(t);
}
}
/* Helper function to handle the reception of an HEARTBEAT ACK. */
static void sctp_cmd_transport_on(struct sctp_cmd_seq *cmds,
struct sctp_association *asoc,
struct sctp_transport *t,
struct sctp_chunk *chunk)
{
struct sctp_sender_hb_info *hbinfo;
int was_unconfirmed = 0;
/* 8.3 Upon the receipt of the HEARTBEAT ACK, the sender of the
* HEARTBEAT should clear the error counter of the destination
* transport address to which the HEARTBEAT was sent.
*/
t->error_count = 0;
/*
* Although RFC4960 specifies that the overall error count must
* be cleared when a HEARTBEAT ACK is received, we make an
* exception while in SHUTDOWN PENDING. If the peer keeps its
* window shut forever, we may never be able to transmit our
* outstanding data and rely on the retransmission limit be reached
* to shutdown the association.
*/
if (t->asoc->state < SCTP_STATE_SHUTDOWN_PENDING)
t->asoc->overall_error_count = 0;
/* Clear the hb_sent flag to signal that we had a good
* acknowledgement.
*/
t->hb_sent = 0;
/* Mark the destination transport address as active if it is not so
* marked.
*/
if ((t->state == SCTP_INACTIVE) || (t->state == SCTP_UNCONFIRMED)) {
was_unconfirmed = 1;
sctp_assoc_control_transport(asoc, t, SCTP_TRANSPORT_UP,
SCTP_HEARTBEAT_SUCCESS);
}
if (t->state == SCTP_PF)
sctp_assoc_control_transport(asoc, t, SCTP_TRANSPORT_UP,
SCTP_HEARTBEAT_SUCCESS);
/* HB-ACK was received for a the proper HB. Consider this
* forward progress.
*/
if (t->dst)
sctp_transport_dst_confirm(t);
/* The receiver of the HEARTBEAT ACK should also perform an
* RTT measurement for that destination transport address
* using the time value carried in the HEARTBEAT ACK chunk.
* If the transport's rto_pending variable has been cleared,
* it was most likely due to a retransmit. However, we want
* to re-enable it to properly update the rto.
*/
if (t->rto_pending == 0)
t->rto_pending = 1;
hbinfo = (struct sctp_sender_hb_info *)chunk->skb->data;
sctp_transport_update_rto(t, (jiffies - hbinfo->sent_at));
/* Update the heartbeat timer. */
sctp_transport_reset_hb_timer(t);
if (was_unconfirmed && asoc->peer.transport_count == 1)
sctp_transport_immediate_rtx(t);
}
/* Helper function to process the process SACK command. */
static int sctp_cmd_process_sack(struct sctp_cmd_seq *cmds,
struct sctp_association *asoc,
struct sctp_chunk *chunk)
{
int err = 0;
if (sctp_outq_sack(&asoc->outqueue, chunk)) {
/* There are no more TSNs awaiting SACK. */
err = sctp_do_sm(asoc->base.net, SCTP_EVENT_T_OTHER,
SCTP_ST_OTHER(SCTP_EVENT_NO_PENDING_TSN),
asoc->state, asoc->ep, asoc, NULL,
GFP_ATOMIC);
}
return err;
}
/* Helper function to set the timeout value for T2-SHUTDOWN timer and to set
* the transport for a shutdown chunk.
*/
static void sctp_cmd_setup_t2(struct sctp_cmd_seq *cmds,
struct sctp_association *asoc,
struct sctp_chunk *chunk)
{
struct sctp_transport *t;
if (chunk->transport)
t = chunk->transport;
else {
t = sctp_assoc_choose_alter_transport(asoc,
asoc->shutdown_last_sent_to);
chunk->transport = t;
}
asoc->shutdown_last_sent_to = t;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T2_SHUTDOWN] = t->rto;
}
/* Helper function to change the state of an association. */
static void sctp_cmd_new_state(struct sctp_cmd_seq *cmds,
struct sctp_association *asoc,
enum sctp_state state)
{
struct sock *sk = asoc->base.sk;
asoc->state = state;
pr_debug("%s: asoc:%p[%s]\n", __func__, asoc, sctp_state_tbl[state]);
if (sctp_style(sk, TCP)) {
/* Change the sk->sk_state of a TCP-style socket that has
* successfully completed a connect() call.
*/
if (sctp_state(asoc, ESTABLISHED) && sctp_sstate(sk, CLOSED))
inet_sk_set_state(sk, SCTP_SS_ESTABLISHED);
/* Set the RCV_SHUTDOWN flag when a SHUTDOWN is received. */
if (sctp_state(asoc, SHUTDOWN_RECEIVED) &&
sctp_sstate(sk, ESTABLISHED)) {
inet_sk_set_state(sk, SCTP_SS_CLOSING);
sk->sk_shutdown |= RCV_SHUTDOWN;
}
}
if (sctp_state(asoc, COOKIE_WAIT)) {
/* Reset init timeouts since they may have been
* increased due to timer expirations.
*/
asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_INIT] =
asoc->rto_initial;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_COOKIE] =
asoc->rto_initial;
}
if (sctp_state(asoc, ESTABLISHED)) {
kfree(asoc->peer.cookie);
asoc->peer.cookie = NULL;
}
if (sctp_state(asoc, ESTABLISHED) ||
sctp_state(asoc, CLOSED) ||
sctp_state(asoc, SHUTDOWN_RECEIVED)) {
/* Wake up any processes waiting in the asoc's wait queue in
* sctp_wait_for_connect() or sctp_wait_for_sndbuf().
*/
if (waitqueue_active(&asoc->wait))
wake_up_interruptible(&asoc->wait);
/* Wake up any processes waiting in the sk's sleep queue of
* a TCP-style or UDP-style peeled-off socket in
* sctp_wait_for_accept() or sctp_wait_for_packet().
* For a UDP-style socket, the waiters are woken up by the
* notifications.
*/
if (!sctp_style(sk, UDP))
sk->sk_state_change(sk);
}
if (sctp_state(asoc, SHUTDOWN_PENDING) &&
!sctp_outq_is_empty(&asoc->outqueue))
sctp_outq_uncork(&asoc->outqueue, GFP_ATOMIC);
}
/* Helper function to delete an association. */
static void sctp_cmd_delete_tcb(struct sctp_cmd_seq *cmds,
struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
/* If it is a non-temporary association belonging to a TCP-style
* listening socket that is not closed, do not free it so that accept()
* can pick it up later.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING) &&
(!asoc->temp) && (sk->sk_shutdown != SHUTDOWN_MASK))
return;
sctp_association_free(asoc);
}
/*
* ADDIP Section 4.1 ASCONF Chunk Procedures
* A4) Start a T-4 RTO timer, using the RTO value of the selected
* destination address (we use active path instead of primary path just
* because primary path may be inactive.
*/
static void sctp_cmd_setup_t4(struct sctp_cmd_seq *cmds,
struct sctp_association *asoc,
struct sctp_chunk *chunk)
{
struct sctp_transport *t;
t = sctp_assoc_choose_alter_transport(asoc, chunk->transport);
asoc->timeouts[SCTP_EVENT_TIMEOUT_T4_RTO] = t->rto;
chunk->transport = t;
}
/* Process an incoming Operation Error Chunk. */
static void sctp_cmd_process_operr(struct sctp_cmd_seq *cmds,
struct sctp_association *asoc,
struct sctp_chunk *chunk)
{
struct sctp_errhdr *err_hdr;
struct sctp_ulpevent *ev;
while (chunk->chunk_end > chunk->skb->data) {
err_hdr = (struct sctp_errhdr *)(chunk->skb->data);
ev = sctp_ulpevent_make_remote_error(asoc, chunk, 0,
GFP_ATOMIC);
if (!ev)
return;
asoc->stream.si->enqueue_event(&asoc->ulpq, ev);
switch (err_hdr->cause) {
case SCTP_ERROR_UNKNOWN_CHUNK:
{
struct sctp_chunkhdr *unk_chunk_hdr;
unk_chunk_hdr = (struct sctp_chunkhdr *)(err_hdr + 1);
switch (unk_chunk_hdr->type) {
/* ADDIP 4.1 A9) If the peer responds to an ASCONF with
* an ERROR chunk reporting that it did not recognized
* the ASCONF chunk type, the sender of the ASCONF MUST
* NOT send any further ASCONF chunks and MUST stop its
* T-4 timer.
*/
case SCTP_CID_ASCONF:
if (asoc->peer.asconf_capable == 0)
break;
asoc->peer.asconf_capable = 0;
sctp_add_cmd_sf(cmds, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
break;
default:
break;
}
break;
}
default:
break;
}
}
}
/* Helper function to remove the association non-primary peer
* transports.
*/
static void sctp_cmd_del_non_primary(struct sctp_association *asoc)
{
struct sctp_transport *t;
struct list_head *temp;
struct list_head *pos;
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
t = list_entry(pos, struct sctp_transport, transports);
if (!sctp_cmp_addr_exact(&t->ipaddr,
&asoc->peer.primary_addr)) {
sctp_assoc_rm_peer(asoc, t);
}
}
}
/* Helper function to set sk_err on a 1-1 style socket. */
static void sctp_cmd_set_sk_err(struct sctp_association *asoc, int error)
{
struct sock *sk = asoc->base.sk;
if (!sctp_style(sk, UDP))
sk->sk_err = error;
}
/* Helper function to generate an association change event */
static void sctp_cmd_assoc_change(struct sctp_cmd_seq *commands,
struct sctp_association *asoc,
u8 state)
{
struct sctp_ulpevent *ev;
ev = sctp_ulpevent_make_assoc_change(asoc, 0, state, 0,
asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (ev)
asoc->stream.si->enqueue_event(&asoc->ulpq, ev);
}
static void sctp_cmd_peer_no_auth(struct sctp_cmd_seq *commands,
struct sctp_association *asoc)
{
struct sctp_ulpevent *ev;
ev = sctp_ulpevent_make_authkey(asoc, 0, SCTP_AUTH_NO_AUTH, GFP_ATOMIC);
if (ev)
asoc->stream.si->enqueue_event(&asoc->ulpq, ev);
}
/* Helper function to generate an adaptation indication event */
static void sctp_cmd_adaptation_ind(struct sctp_cmd_seq *commands,
struct sctp_association *asoc)
{
struct sctp_ulpevent *ev;
ev = sctp_ulpevent_make_adaptation_indication(asoc, GFP_ATOMIC);
if (ev)
asoc->stream.si->enqueue_event(&asoc->ulpq, ev);
}
static void sctp_cmd_t1_timer_update(struct sctp_association *asoc,
enum sctp_event_timeout timer,
char *name)
{
struct sctp_transport *t;
t = asoc->init_last_sent_to;
asoc->init_err_counter++;
if (t->init_sent_count > (asoc->init_cycle + 1)) {
asoc->timeouts[timer] *= 2;
if (asoc->timeouts[timer] > asoc->max_init_timeo) {
asoc->timeouts[timer] = asoc->max_init_timeo;
}
asoc->init_cycle++;
pr_debug("%s: T1[%s] timeout adjustment init_err_counter:%d"
" cycle:%d timeout:%ld\n", __func__, name,
asoc->init_err_counter, asoc->init_cycle,
asoc->timeouts[timer]);
}
}
/* Send the whole message, chunk by chunk, to the outqueue.
* This way the whole message is queued up and bundling if
* encouraged for small fragments.
*/
static void sctp_cmd_send_msg(struct sctp_association *asoc,
struct sctp_datamsg *msg, gfp_t gfp)
{
struct sctp_chunk *chunk;
list_for_each_entry(chunk, &msg->chunks, frag_list)
sctp_outq_tail(&asoc->outqueue, chunk, gfp);
asoc->outqueue.sched->enqueue(&asoc->outqueue, msg);
}
/* These three macros allow us to pull the debugging code out of the
* main flow of sctp_do_sm() to keep attention focused on the real
* functionality there.
*/
#define debug_pre_sfn() \
pr_debug("%s[pre-fn]: ep:%p, %s, %s, asoc:%p[%s], %s\n", __func__, \
ep, sctp_evttype_tbl[event_type], (*debug_fn)(subtype), \
asoc, sctp_state_tbl[state], state_fn->name)
#define debug_post_sfn() \
pr_debug("%s[post-fn]: asoc:%p, status:%s\n", __func__, asoc, \
sctp_status_tbl[status])
#define debug_post_sfx() \
pr_debug("%s[post-sfx]: error:%d, asoc:%p[%s]\n", __func__, error, \
asoc, sctp_state_tbl[(asoc && sctp_id2assoc(ep->base.sk, \
sctp_assoc2id(asoc))) ? asoc->state : SCTP_STATE_CLOSED])
/*
* This is the master state machine processing function.
*
* If you want to understand all of lksctp, this is a
* good place to start.
*/
int sctp_do_sm(struct net *net, enum sctp_event_type event_type,
union sctp_subtype subtype, enum sctp_state state,
struct sctp_endpoint *ep, struct sctp_association *asoc,
void *event_arg, gfp_t gfp)
{
typedef const char *(printfn_t)(union sctp_subtype);
static printfn_t *table[] = {
NULL, sctp_cname, sctp_tname, sctp_oname, sctp_pname,
};
printfn_t *debug_fn __attribute__ ((unused)) = table[event_type];
const struct sctp_sm_table_entry *state_fn;
struct sctp_cmd_seq commands;
enum sctp_disposition status;
int error = 0;
/* Look up the state function, run it, and then process the
* side effects. These three steps are the heart of lksctp.
*/
state_fn = sctp_sm_lookup_event(net, event_type, state, subtype);
sctp_init_cmd_seq(&commands);
debug_pre_sfn();
status = state_fn->fn(net, ep, asoc, subtype, event_arg, &commands);
debug_post_sfn();
error = sctp_side_effects(event_type, subtype, state,
ep, &asoc, event_arg, status,
&commands, gfp);
debug_post_sfx();
return error;
}
/*****************************************************************
* This the master state function side effect processing function.
*****************************************************************/
static int sctp_side_effects(enum sctp_event_type event_type,
union sctp_subtype subtype,
enum sctp_state state,
struct sctp_endpoint *ep,
struct sctp_association **asoc,
void *event_arg,
enum sctp_disposition status,
struct sctp_cmd_seq *commands,
gfp_t gfp)
{
int error;
/* FIXME - Most of the dispositions left today would be categorized
* as "exceptional" dispositions. For those dispositions, it
* may not be proper to run through any of the commands at all.
* For example, the command interpreter might be run only with
* disposition SCTP_DISPOSITION_CONSUME.
*/
if (0 != (error = sctp_cmd_interpreter(event_type, subtype, state,
ep, *asoc,
event_arg, status,
commands, gfp)))
goto bail;
switch (status) {
case SCTP_DISPOSITION_DISCARD:
pr_debug("%s: ignored sctp protocol event - state:%d, "
"event_type:%d, event_id:%d\n", __func__, state,
event_type, subtype.chunk);
break;
case SCTP_DISPOSITION_NOMEM:
/* We ran out of memory, so we need to discard this
* packet.
*/
/* BUG--we should now recover some memory, probably by
* reneging...
*/
error = -ENOMEM;
break;
case SCTP_DISPOSITION_DELETE_TCB:
case SCTP_DISPOSITION_ABORT:
/* This should now be a command. */
*asoc = NULL;
break;
case SCTP_DISPOSITION_CONSUME:
/*
* We should no longer have much work to do here as the
* real work has been done as explicit commands above.
*/
break;
case SCTP_DISPOSITION_VIOLATION:
net_err_ratelimited("protocol violation state %d chunkid %d\n",
state, subtype.chunk);
break;
case SCTP_DISPOSITION_NOT_IMPL:
pr_warn("unimplemented feature in state %d, event_type %d, event_id %d\n",
state, event_type, subtype.chunk);
break;
case SCTP_DISPOSITION_BUG:
pr_err("bug in state %d, event_type %d, event_id %d\n",
state, event_type, subtype.chunk);
BUG();
break;
default:
pr_err("impossible disposition %d in state %d, event_type %d, event_id %d\n",
status, state, event_type, subtype.chunk);
error = status;
if (error >= 0)
error = -EINVAL;
WARN_ON_ONCE(1);
break;
}
bail:
return error;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* This is the side-effect interpreter. */
static int sctp_cmd_interpreter(enum sctp_event_type event_type,
union sctp_subtype subtype,
enum sctp_state state,
struct sctp_endpoint *ep,
struct sctp_association *asoc,
void *event_arg,
enum sctp_disposition status,
struct sctp_cmd_seq *commands,
gfp_t gfp)
{
struct sctp_sock *sp = sctp_sk(ep->base.sk);
struct sctp_chunk *chunk = NULL, *new_obj;
struct sctp_packet *packet;
struct sctp_sackhdr sackh;
struct timer_list *timer;
struct sctp_transport *t;
unsigned long timeout;
struct sctp_cmd *cmd;
int local_cork = 0;
int error = 0;
int force;
if (SCTP_EVENT_T_TIMEOUT != event_type)
chunk = event_arg;
/* Note: This whole file is a huge candidate for rework.
* For example, each command could either have its own handler, so
* the loop would look like:
* while (cmds)
* cmd->handle(x, y, z)
* --jgrimm
*/
while (NULL != (cmd = sctp_next_cmd(commands))) {
switch (cmd->verb) {
case SCTP_CMD_NOP:
/* Do nothing. */
break;
case SCTP_CMD_NEW_ASOC:
/* Register a new association. */
if (local_cork) {
sctp_outq_uncork(&asoc->outqueue, gfp);
local_cork = 0;
}
/* Register with the endpoint. */
asoc = cmd->obj.asoc;
BUG_ON(asoc->peer.primary_path == NULL);
sctp_endpoint_add_asoc(ep, asoc);
break;
case SCTP_CMD_PURGE_OUTQUEUE:
sctp_outq_teardown(&asoc->outqueue);
break;
case SCTP_CMD_DELETE_TCB:
if (local_cork) {
sctp_outq_uncork(&asoc->outqueue, gfp);
local_cork = 0;
}
/* Delete the current association. */
sctp_cmd_delete_tcb(commands, asoc);
asoc = NULL;
break;
case SCTP_CMD_NEW_STATE:
/* Enter a new state. */
sctp_cmd_new_state(commands, asoc, cmd->obj.state);
break;
case SCTP_CMD_REPORT_TSN:
/* Record the arrival of a TSN. */
error = sctp_tsnmap_mark(&asoc->peer.tsn_map,
cmd->obj.u32, NULL);
break;
case SCTP_CMD_REPORT_FWDTSN:
asoc->stream.si->report_ftsn(&asoc->ulpq, cmd->obj.u32);
break;
case SCTP_CMD_PROCESS_FWDTSN:
asoc->stream.si->handle_ftsn(&asoc->ulpq,
cmd->obj.chunk);
break;
case SCTP_CMD_GEN_SACK:
/* Generate a Selective ACK.
* The argument tells us whether to just count
* the packet and MAYBE generate a SACK, or
* force a SACK out.
*/
force = cmd->obj.i32;
error = sctp_gen_sack(asoc, force, commands);
break;
case SCTP_CMD_PROCESS_SACK:
/* Process an inbound SACK. */
error = sctp_cmd_process_sack(commands, asoc,
cmd->obj.chunk);
break;
case SCTP_CMD_GEN_INIT_ACK:
/* Generate an INIT ACK chunk. */
new_obj = sctp_make_init_ack(asoc, chunk, GFP_ATOMIC,
0);
if (!new_obj) {
error = -ENOMEM;
break;
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(new_obj));
break;
case SCTP_CMD_PEER_INIT:
/* Process a unified INIT from the peer.
* Note: Only used during INIT-ACK processing. If
* there is an error just return to the outter
* layer which will bail.
*/
error = sctp_cmd_process_init(commands, asoc, chunk,
cmd->obj.init, gfp);
break;
case SCTP_CMD_GEN_COOKIE_ECHO:
/* Generate a COOKIE ECHO chunk. */
new_obj = sctp_make_cookie_echo(asoc, chunk);
if (!new_obj) {
if (cmd->obj.chunk)
sctp_chunk_free(cmd->obj.chunk);
error = -ENOMEM;
break;
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(new_obj));
/* If there is an ERROR chunk to be sent along with
* the COOKIE_ECHO, send it, too.
*/
if (cmd->obj.chunk)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(cmd->obj.chunk));
if (new_obj->transport) {
new_obj->transport->init_sent_count++;
asoc->init_last_sent_to = new_obj->transport;
}
/* FIXME - Eventually come up with a cleaner way to
* enabling COOKIE-ECHO + DATA bundling during
* multihoming stale cookie scenarios, the following
* command plays with asoc->peer.retran_path to
* avoid the problem of sending the COOKIE-ECHO and
* DATA in different paths, which could result
* in the association being ABORTed if the DATA chunk
* is processed first by the server. Checking the
* init error counter simply causes this command
* to be executed only during failed attempts of
* association establishment.
*/
if ((asoc->peer.retran_path !=
asoc->peer.primary_path) &&
(asoc->init_err_counter > 0)) {
sctp_add_cmd_sf(commands,
SCTP_CMD_FORCE_PRIM_RETRAN,
SCTP_NULL());
}
break;
case SCTP_CMD_GEN_SHUTDOWN:
/* Generate SHUTDOWN when in SHUTDOWN_SENT state.
* Reset error counts.
*/
asoc->overall_error_count = 0;
/* Generate a SHUTDOWN chunk. */
new_obj = sctp_make_shutdown(asoc, chunk);
if (!new_obj) {
error = -ENOMEM;
break;
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(new_obj));
break;
case SCTP_CMD_CHUNK_ULP:
/* Send a chunk to the sockets layer. */
pr_debug("%s: sm_sideff: chunk_up:%p, ulpq:%p\n",
__func__, cmd->obj.chunk, &asoc->ulpq);
asoc->stream.si->ulpevent_data(&asoc->ulpq,
cmd->obj.chunk,
GFP_ATOMIC);
break;
case SCTP_CMD_EVENT_ULP:
/* Send a notification to the sockets layer. */
pr_debug("%s: sm_sideff: event_up:%p, ulpq:%p\n",
__func__, cmd->obj.ulpevent, &asoc->ulpq);
asoc->stream.si->enqueue_event(&asoc->ulpq,
cmd->obj.ulpevent);
break;
case SCTP_CMD_REPLY:
/* If an caller has not already corked, do cork. */
if (!asoc->outqueue.cork) {
sctp_outq_cork(&asoc->outqueue);
local_cork = 1;
}
/* Send a chunk to our peer. */
sctp_outq_tail(&asoc->outqueue, cmd->obj.chunk, gfp);
break;
case SCTP_CMD_SEND_PKT:
/* Send a full packet to our peer. */
packet = cmd->obj.packet;
sctp_packet_transmit(packet, gfp);
sctp_ootb_pkt_free(packet);
break;
case SCTP_CMD_T1_RETRAN:
/* Mark a transport for retransmission. */
sctp_retransmit(&asoc->outqueue, cmd->obj.transport,
SCTP_RTXR_T1_RTX);
break;
case SCTP_CMD_RETRAN:
/* Mark a transport for retransmission. */
sctp_retransmit(&asoc->outqueue, cmd->obj.transport,
SCTP_RTXR_T3_RTX);
break;
case SCTP_CMD_ECN_CE:
/* Do delayed CE processing. */
sctp_do_ecn_ce_work(asoc, cmd->obj.u32);
break;
case SCTP_CMD_ECN_ECNE:
/* Do delayed ECNE processing. */
new_obj = sctp_do_ecn_ecne_work(asoc, cmd->obj.u32,
chunk);
if (new_obj)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(new_obj));
break;
case SCTP_CMD_ECN_CWR:
/* Do delayed CWR processing. */
sctp_do_ecn_cwr_work(asoc, cmd->obj.u32);
break;
case SCTP_CMD_SETUP_T2:
sctp_cmd_setup_t2(commands, asoc, cmd->obj.chunk);
break;
case SCTP_CMD_TIMER_START_ONCE:
timer = &asoc->timers[cmd->obj.to];
if (timer_pending(timer))
break;
fallthrough;
case SCTP_CMD_TIMER_START:
timer = &asoc->timers[cmd->obj.to];
timeout = asoc->timeouts[cmd->obj.to];
BUG_ON(!timeout);
/*
* SCTP has a hard time with timer starts. Because we process
* timer starts as side effects, it can be hard to tell if we
* have already started a timer or not, which leads to BUG
* halts when we call add_timer. So here, instead of just starting
* a timer, if the timer is already started, and just mod
* the timer with the shorter of the two expiration times
*/
if (!timer_pending(timer))
sctp_association_hold(asoc);
timer_reduce(timer, jiffies + timeout);
break;
case SCTP_CMD_TIMER_RESTART:
timer = &asoc->timers[cmd->obj.to];
timeout = asoc->timeouts[cmd->obj.to];
if (!mod_timer(timer, jiffies + timeout))
sctp_association_hold(asoc);
break;
case SCTP_CMD_TIMER_STOP:
timer = &asoc->timers[cmd->obj.to];
if (del_timer(timer))
sctp_association_put(asoc);
break;
case SCTP_CMD_INIT_CHOOSE_TRANSPORT:
chunk = cmd->obj.chunk;
t = sctp_assoc_choose_alter_transport(asoc,
asoc->init_last_sent_to);
asoc->init_last_sent_to = t;
chunk->transport = t;
t->init_sent_count++;
/* Set the new transport as primary */
sctp_assoc_set_primary(asoc, t);
break;
case SCTP_CMD_INIT_RESTART:
/* Do the needed accounting and updates
* associated with restarting an initialization
* timer. Only multiply the timeout by two if
* all transports have been tried at the current
* timeout.
*/
sctp_cmd_t1_timer_update(asoc,
SCTP_EVENT_TIMEOUT_T1_INIT,
"INIT");
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
break;
case SCTP_CMD_COOKIEECHO_RESTART:
/* Do the needed accounting and updates
* associated with restarting an initialization
* timer. Only multiply the timeout by two if
* all transports have been tried at the current
* timeout.
*/
sctp_cmd_t1_timer_update(asoc,
SCTP_EVENT_TIMEOUT_T1_COOKIE,
"COOKIE");
/* If we've sent any data bundled with
* COOKIE-ECHO we need to resend.
*/
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
sctp_retransmit_mark(&asoc->outqueue, t,
SCTP_RTXR_T1_RTX);
}
sctp_add_cmd_sf(commands,
SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
break;
case SCTP_CMD_INIT_FAILED:
sctp_cmd_init_failed(commands, asoc, cmd->obj.u16);
break;
case SCTP_CMD_ASSOC_FAILED:
sctp_cmd_assoc_failed(commands, asoc, event_type,
subtype, chunk, cmd->obj.u16);
break;
case SCTP_CMD_INIT_COUNTER_INC:
asoc->init_err_counter++;
break;
case SCTP_CMD_INIT_COUNTER_RESET:
asoc->init_err_counter = 0;
asoc->init_cycle = 0;
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
t->init_sent_count = 0;
}
break;
case SCTP_CMD_REPORT_DUP:
sctp_tsnmap_mark_dup(&asoc->peer.tsn_map,
cmd->obj.u32);
break;
case SCTP_CMD_REPORT_BAD_TAG:
pr_debug("%s: vtag mismatch!\n", __func__);
break;
case SCTP_CMD_STRIKE:
/* Mark one strike against a transport. */
sctp_do_8_2_transport_strike(commands, asoc,
cmd->obj.transport, 0);
break;
case SCTP_CMD_TRANSPORT_IDLE:
t = cmd->obj.transport;
sctp_transport_lower_cwnd(t, SCTP_LOWER_CWND_INACTIVE);
break;
case SCTP_CMD_TRANSPORT_HB_SENT:
t = cmd->obj.transport;
sctp_do_8_2_transport_strike(commands, asoc,
t, 1);
t->hb_sent = 1;
break;
case SCTP_CMD_TRANSPORT_ON:
t = cmd->obj.transport;
sctp_cmd_transport_on(commands, asoc, t, chunk);
break;
case SCTP_CMD_HB_TIMERS_START:
sctp_cmd_hb_timers_start(commands, asoc);
break;
case SCTP_CMD_HB_TIMER_UPDATE:
t = cmd->obj.transport;
sctp_transport_reset_hb_timer(t);
break;
case SCTP_CMD_HB_TIMERS_STOP:
sctp_cmd_hb_timers_stop(commands, asoc);
break;
case SCTP_CMD_PROBE_TIMER_UPDATE:
t = cmd->obj.transport;
sctp_transport_reset_probe_timer(t);
break;
case SCTP_CMD_REPORT_ERROR:
error = cmd->obj.error;
break;
case SCTP_CMD_PROCESS_CTSN:
/* Dummy up a SACK for processing. */
sackh.cum_tsn_ack = cmd->obj.be32;
sackh.a_rwnd = htonl(asoc->peer.rwnd +
asoc->outqueue.outstanding_bytes);
sackh.num_gap_ack_blocks = 0;
sackh.num_dup_tsns = 0;
chunk->subh.sack_hdr = &sackh;
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_SACK,
SCTP_CHUNK(chunk));
break;
case SCTP_CMD_DISCARD_PACKET:
/* We need to discard the whole packet.
* Uncork the queue since there might be
* responses pending
*/
chunk->pdiscard = 1;
if (asoc) {
sctp_outq_uncork(&asoc->outqueue, gfp);
local_cork = 0;
}
break;
case SCTP_CMD_RTO_PENDING:
t = cmd->obj.transport;
t->rto_pending = 1;
break;
case SCTP_CMD_PART_DELIVER:
asoc->stream.si->start_pd(&asoc->ulpq, GFP_ATOMIC);
break;
case SCTP_CMD_RENEGE:
asoc->stream.si->renege_events(&asoc->ulpq,
cmd->obj.chunk,
GFP_ATOMIC);
break;
case SCTP_CMD_SETUP_T4:
sctp_cmd_setup_t4(commands, asoc, cmd->obj.chunk);
break;
case SCTP_CMD_PROCESS_OPERR:
sctp_cmd_process_operr(commands, asoc, chunk);
break;
case SCTP_CMD_CLEAR_INIT_TAG:
asoc->peer.i.init_tag = 0;
break;
case SCTP_CMD_DEL_NON_PRIMARY:
sctp_cmd_del_non_primary(asoc);
break;
case SCTP_CMD_T3_RTX_TIMERS_STOP:
sctp_cmd_t3_rtx_timers_stop(commands, asoc);
break;
case SCTP_CMD_FORCE_PRIM_RETRAN:
t = asoc->peer.retran_path;
asoc->peer.retran_path = asoc->peer.primary_path;
sctp_outq_uncork(&asoc->outqueue, gfp);
local_cork = 0;
asoc->peer.retran_path = t;
break;
case SCTP_CMD_SET_SK_ERR:
sctp_cmd_set_sk_err(asoc, cmd->obj.error);
break;
case SCTP_CMD_ASSOC_CHANGE:
sctp_cmd_assoc_change(commands, asoc,
cmd->obj.u8);
break;
case SCTP_CMD_ADAPTATION_IND:
sctp_cmd_adaptation_ind(commands, asoc);
break;
case SCTP_CMD_PEER_NO_AUTH:
sctp_cmd_peer_no_auth(commands, asoc);
break;
case SCTP_CMD_ASSOC_SHKEY:
error = sctp_auth_asoc_init_active_key(asoc,
GFP_ATOMIC);
break;
case SCTP_CMD_UPDATE_INITTAG:
asoc->peer.i.init_tag = cmd->obj.u32;
break;
case SCTP_CMD_SEND_MSG:
if (!asoc->outqueue.cork) {
sctp_outq_cork(&asoc->outqueue);
local_cork = 1;
}
sctp_cmd_send_msg(asoc, cmd->obj.msg, gfp);
break;
case SCTP_CMD_PURGE_ASCONF_QUEUE:
sctp_asconf_queue_teardown(asoc);
break;
case SCTP_CMD_SET_ASOC:
if (asoc && local_cork) {
sctp_outq_uncork(&asoc->outqueue, gfp);
local_cork = 0;
}
asoc = cmd->obj.asoc;
break;
default:
pr_warn("Impossible command: %u\n",
cmd->verb);
break;
}
if (error) {
cmd = sctp_next_cmd(commands);
while (cmd) {
if (cmd->verb == SCTP_CMD_REPLY)
sctp_chunk_free(cmd->obj.chunk);
cmd = sctp_next_cmd(commands);
}
break;
}
}
/* If this is in response to a received chunk, wait until
* we are done with the packet to open the queue so that we don't
* send multiple packets in response to a single request.
*/
if (asoc && SCTP_EVENT_T_CHUNK == event_type && chunk) {
if (chunk->end_of_packet || chunk->singleton)
sctp_outq_uncork(&asoc->outqueue, gfp);
} else if (local_cork)
sctp_outq_uncork(&asoc->outqueue, gfp);
if (sp->data_ready_signalled)
sp->data_ready_signalled = 0;
return error;
}
| linux-master | net/sctp/sm_sideeffect.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2002 Intel Corp.
*
* This file is part of the SCTP kernel implementation
*
* These functions work with the state functions in sctp_sm_statefuns.c
* to implement the state operations. These functions implement the
* steps which require modifying existing data structures.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* C. Robin <[email protected]>
* Jon Grimm <[email protected]>
* Xingang Guo <[email protected]>
* Dajiang Zhang <[email protected]>
* Sridhar Samudrala <[email protected]>
* Daisy Chang <[email protected]>
* Ardelle Fan <[email protected]>
* Kevin Gao <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <crypto/hash.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/skbuff.h>
#include <linux/random.h> /* for get_random_bytes */
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
static struct sctp_chunk *sctp_make_control(const struct sctp_association *asoc,
__u8 type, __u8 flags, int paylen,
gfp_t gfp);
static struct sctp_chunk *sctp_make_data(const struct sctp_association *asoc,
__u8 flags, int paylen, gfp_t gfp);
static struct sctp_chunk *_sctp_make_chunk(const struct sctp_association *asoc,
__u8 type, __u8 flags, int paylen,
gfp_t gfp);
static struct sctp_cookie_param *sctp_pack_cookie(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *init_chunk,
int *cookie_len,
const __u8 *raw_addrs, int addrs_len);
static int sctp_process_param(struct sctp_association *asoc,
union sctp_params param,
const union sctp_addr *peer_addr,
gfp_t gfp);
static void *sctp_addto_param(struct sctp_chunk *chunk, int len,
const void *data);
/* Control chunk destructor */
static void sctp_control_release_owner(struct sk_buff *skb)
{
struct sctp_chunk *chunk = skb_shinfo(skb)->destructor_arg;
if (chunk->shkey) {
struct sctp_shared_key *shkey = chunk->shkey;
struct sctp_association *asoc = chunk->asoc;
/* refcnt == 2 and !list_empty mean after this release, it's
* not being used anywhere, and it's time to notify userland
* that this shkey can be freed if it's been deactivated.
*/
if (shkey->deactivated && !list_empty(&shkey->key_list) &&
refcount_read(&shkey->refcnt) == 2) {
struct sctp_ulpevent *ev;
ev = sctp_ulpevent_make_authkey(asoc, shkey->key_id,
SCTP_AUTH_FREE_KEY,
GFP_KERNEL);
if (ev)
asoc->stream.si->enqueue_event(&asoc->ulpq, ev);
}
sctp_auth_shkey_release(chunk->shkey);
}
}
static void sctp_control_set_owner_w(struct sctp_chunk *chunk)
{
struct sctp_association *asoc = chunk->asoc;
struct sk_buff *skb = chunk->skb;
/* TODO: properly account for control chunks.
* To do it right we'll need:
* 1) endpoint if association isn't known.
* 2) proper memory accounting.
*
* For now don't do anything for now.
*/
if (chunk->auth) {
chunk->shkey = asoc->shkey;
sctp_auth_shkey_hold(chunk->shkey);
}
skb->sk = asoc ? asoc->base.sk : NULL;
skb_shinfo(skb)->destructor_arg = chunk;
skb->destructor = sctp_control_release_owner;
}
/* What was the inbound interface for this chunk? */
int sctp_chunk_iif(const struct sctp_chunk *chunk)
{
struct sk_buff *skb = chunk->skb;
return SCTP_INPUT_CB(skb)->af->skb_iif(skb);
}
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 2: The ECN capable field is reserved for future use of
* Explicit Congestion Notification.
*/
static const struct sctp_paramhdr ecap_param = {
SCTP_PARAM_ECN_CAPABLE,
cpu_to_be16(sizeof(struct sctp_paramhdr)),
};
static const struct sctp_paramhdr prsctp_param = {
SCTP_PARAM_FWD_TSN_SUPPORT,
cpu_to_be16(sizeof(struct sctp_paramhdr)),
};
/* A helper to initialize an op error inside a provided chunk, as most
* cause codes will be embedded inside an abort chunk.
*/
int sctp_init_cause(struct sctp_chunk *chunk, __be16 cause_code,
size_t paylen)
{
struct sctp_errhdr err;
__u16 len;
/* Cause code constants are now defined in network order. */
err.cause = cause_code;
len = sizeof(err) + paylen;
err.length = htons(len);
if (skb_tailroom(chunk->skb) < len)
return -ENOSPC;
chunk->subh.err_hdr = sctp_addto_chunk(chunk, sizeof(err), &err);
return 0;
}
/* 3.3.2 Initiation (INIT) (1)
*
* This chunk is used to initiate a SCTP association between two
* endpoints. The format of the INIT chunk is shown below:
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 1 | Chunk Flags | Chunk Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Initiate Tag |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Advertised Receiver Window Credit (a_rwnd) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Outbound Streams | Number of Inbound Streams |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Initial TSN |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / Optional/Variable-Length Parameters /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*
* The INIT chunk contains the following parameters. Unless otherwise
* noted, each parameter MUST only be included once in the INIT chunk.
*
* Fixed Parameters Status
* ----------------------------------------------
* Initiate Tag Mandatory
* Advertised Receiver Window Credit Mandatory
* Number of Outbound Streams Mandatory
* Number of Inbound Streams Mandatory
* Initial TSN Mandatory
*
* Variable Parameters Status Type Value
* -------------------------------------------------------------
* IPv4 Address (Note 1) Optional 5
* IPv6 Address (Note 1) Optional 6
* Cookie Preservative Optional 9
* Reserved for ECN Capable (Note 2) Optional 32768 (0x8000)
* Host Name Address (Note 3) Optional 11
* Supported Address Types (Note 4) Optional 12
*/
struct sctp_chunk *sctp_make_init(const struct sctp_association *asoc,
const struct sctp_bind_addr *bp,
gfp_t gfp, int vparam_len)
{
struct sctp_supported_ext_param ext_param;
struct sctp_adaptation_ind_param aiparam;
struct sctp_paramhdr *auth_chunks = NULL;
struct sctp_paramhdr *auth_hmacs = NULL;
struct sctp_supported_addrs_param sat;
struct sctp_endpoint *ep = asoc->ep;
struct sctp_chunk *retval = NULL;
int num_types, addrs_len = 0;
struct sctp_inithdr init;
union sctp_params addrs;
struct sctp_sock *sp;
__u8 extensions[5];
size_t chunksize;
__be16 types[2];
int num_ext = 0;
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 1: The INIT chunks can contain multiple addresses that
* can be IPv4 and/or IPv6 in any combination.
*/
/* Convert the provided bind address list to raw format. */
addrs = sctp_bind_addrs_to_raw(bp, &addrs_len, gfp);
init.init_tag = htonl(asoc->c.my_vtag);
init.a_rwnd = htonl(asoc->rwnd);
init.num_outbound_streams = htons(asoc->c.sinit_num_ostreams);
init.num_inbound_streams = htons(asoc->c.sinit_max_instreams);
init.initial_tsn = htonl(asoc->c.initial_tsn);
/* How many address types are needed? */
sp = sctp_sk(asoc->base.sk);
num_types = sp->pf->supported_addrs(sp, types);
chunksize = sizeof(init) + addrs_len;
chunksize += SCTP_PAD4(SCTP_SAT_LEN(num_types));
if (asoc->ep->ecn_enable)
chunksize += sizeof(ecap_param);
if (asoc->ep->prsctp_enable)
chunksize += sizeof(prsctp_param);
/* ADDIP: Section 4.2.7:
* An implementation supporting this extension [ADDIP] MUST list
* the ASCONF,the ASCONF-ACK, and the AUTH chunks in its INIT and
* INIT-ACK parameters.
*/
if (asoc->ep->asconf_enable) {
extensions[num_ext] = SCTP_CID_ASCONF;
extensions[num_ext+1] = SCTP_CID_ASCONF_ACK;
num_ext += 2;
}
if (asoc->ep->reconf_enable) {
extensions[num_ext] = SCTP_CID_RECONF;
num_ext += 1;
}
if (sp->adaptation_ind)
chunksize += sizeof(aiparam);
if (asoc->ep->intl_enable) {
extensions[num_ext] = SCTP_CID_I_DATA;
num_ext += 1;
}
chunksize += vparam_len;
/* Account for AUTH related parameters */
if (ep->auth_enable) {
/* Add random parameter length*/
chunksize += sizeof(asoc->c.auth_random);
/* Add HMACS parameter length if any were defined */
auth_hmacs = (struct sctp_paramhdr *)asoc->c.auth_hmacs;
if (auth_hmacs->length)
chunksize += SCTP_PAD4(ntohs(auth_hmacs->length));
else
auth_hmacs = NULL;
/* Add CHUNKS parameter length */
auth_chunks = (struct sctp_paramhdr *)asoc->c.auth_chunks;
if (auth_chunks->length)
chunksize += SCTP_PAD4(ntohs(auth_chunks->length));
else
auth_chunks = NULL;
extensions[num_ext] = SCTP_CID_AUTH;
num_ext += 1;
}
/* If we have any extensions to report, account for that */
if (num_ext)
chunksize += SCTP_PAD4(sizeof(ext_param) + num_ext);
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 3: An INIT chunk MUST NOT contain more than one Host
* Name address parameter. Moreover, the sender of the INIT
* MUST NOT combine any other address types with the Host Name
* address in the INIT. The receiver of INIT MUST ignore any
* other address types if the Host Name address parameter is
* present in the received INIT chunk.
*
* PLEASE DO NOT FIXME [This version does not support Host Name.]
*/
retval = sctp_make_control(asoc, SCTP_CID_INIT, 0, chunksize, gfp);
if (!retval)
goto nodata;
retval->subh.init_hdr =
sctp_addto_chunk(retval, sizeof(init), &init);
retval->param_hdr.v =
sctp_addto_chunk(retval, addrs_len, addrs.v);
/* RFC 2960 3.3.2 Initiation (INIT) (1)
*
* Note 4: This parameter, when present, specifies all the
* address types the sending endpoint can support. The absence
* of this parameter indicates that the sending endpoint can
* support any address type.
*/
sat.param_hdr.type = SCTP_PARAM_SUPPORTED_ADDRESS_TYPES;
sat.param_hdr.length = htons(SCTP_SAT_LEN(num_types));
sctp_addto_chunk(retval, sizeof(sat), &sat);
sctp_addto_chunk(retval, num_types * sizeof(__u16), &types);
if (asoc->ep->ecn_enable)
sctp_addto_chunk(retval, sizeof(ecap_param), &ecap_param);
/* Add the supported extensions parameter. Be nice and add this
* fist before addiding the parameters for the extensions themselves
*/
if (num_ext) {
ext_param.param_hdr.type = SCTP_PARAM_SUPPORTED_EXT;
ext_param.param_hdr.length = htons(sizeof(ext_param) + num_ext);
sctp_addto_chunk(retval, sizeof(ext_param), &ext_param);
sctp_addto_param(retval, num_ext, extensions);
}
if (asoc->ep->prsctp_enable)
sctp_addto_chunk(retval, sizeof(prsctp_param), &prsctp_param);
if (sp->adaptation_ind) {
aiparam.param_hdr.type = SCTP_PARAM_ADAPTATION_LAYER_IND;
aiparam.param_hdr.length = htons(sizeof(aiparam));
aiparam.adaptation_ind = htonl(sp->adaptation_ind);
sctp_addto_chunk(retval, sizeof(aiparam), &aiparam);
}
/* Add SCTP-AUTH chunks to the parameter list */
if (ep->auth_enable) {
sctp_addto_chunk(retval, sizeof(asoc->c.auth_random),
asoc->c.auth_random);
if (auth_hmacs)
sctp_addto_chunk(retval, ntohs(auth_hmacs->length),
auth_hmacs);
if (auth_chunks)
sctp_addto_chunk(retval, ntohs(auth_chunks->length),
auth_chunks);
}
nodata:
kfree(addrs.v);
return retval;
}
struct sctp_chunk *sctp_make_init_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
gfp_t gfp, int unkparam_len)
{
struct sctp_supported_ext_param ext_param;
struct sctp_adaptation_ind_param aiparam;
struct sctp_paramhdr *auth_chunks = NULL;
struct sctp_paramhdr *auth_random = NULL;
struct sctp_paramhdr *auth_hmacs = NULL;
struct sctp_chunk *retval = NULL;
struct sctp_cookie_param *cookie;
struct sctp_inithdr initack;
union sctp_params addrs;
struct sctp_sock *sp;
__u8 extensions[5];
size_t chunksize;
int num_ext = 0;
int cookie_len;
int addrs_len;
/* Note: there may be no addresses to embed. */
addrs = sctp_bind_addrs_to_raw(&asoc->base.bind_addr, &addrs_len, gfp);
initack.init_tag = htonl(asoc->c.my_vtag);
initack.a_rwnd = htonl(asoc->rwnd);
initack.num_outbound_streams = htons(asoc->c.sinit_num_ostreams);
initack.num_inbound_streams = htons(asoc->c.sinit_max_instreams);
initack.initial_tsn = htonl(asoc->c.initial_tsn);
/* FIXME: We really ought to build the cookie right
* into the packet instead of allocating more fresh memory.
*/
cookie = sctp_pack_cookie(asoc->ep, asoc, chunk, &cookie_len,
addrs.v, addrs_len);
if (!cookie)
goto nomem_cookie;
/* Calculate the total size of allocation, include the reserved
* space for reporting unknown parameters if it is specified.
*/
sp = sctp_sk(asoc->base.sk);
chunksize = sizeof(initack) + addrs_len + cookie_len + unkparam_len;
/* Tell peer that we'll do ECN only if peer advertised such cap. */
if (asoc->peer.ecn_capable)
chunksize += sizeof(ecap_param);
if (asoc->peer.prsctp_capable)
chunksize += sizeof(prsctp_param);
if (asoc->peer.asconf_capable) {
extensions[num_ext] = SCTP_CID_ASCONF;
extensions[num_ext+1] = SCTP_CID_ASCONF_ACK;
num_ext += 2;
}
if (asoc->peer.reconf_capable) {
extensions[num_ext] = SCTP_CID_RECONF;
num_ext += 1;
}
if (sp->adaptation_ind)
chunksize += sizeof(aiparam);
if (asoc->peer.intl_capable) {
extensions[num_ext] = SCTP_CID_I_DATA;
num_ext += 1;
}
if (asoc->peer.auth_capable) {
auth_random = (struct sctp_paramhdr *)asoc->c.auth_random;
chunksize += ntohs(auth_random->length);
auth_hmacs = (struct sctp_paramhdr *)asoc->c.auth_hmacs;
if (auth_hmacs->length)
chunksize += SCTP_PAD4(ntohs(auth_hmacs->length));
else
auth_hmacs = NULL;
auth_chunks = (struct sctp_paramhdr *)asoc->c.auth_chunks;
if (auth_chunks->length)
chunksize += SCTP_PAD4(ntohs(auth_chunks->length));
else
auth_chunks = NULL;
extensions[num_ext] = SCTP_CID_AUTH;
num_ext += 1;
}
if (num_ext)
chunksize += SCTP_PAD4(sizeof(ext_param) + num_ext);
/* Now allocate and fill out the chunk. */
retval = sctp_make_control(asoc, SCTP_CID_INIT_ACK, 0, chunksize, gfp);
if (!retval)
goto nomem_chunk;
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it received the DATA or control chunk
* to which it is replying.
*
* [INIT ACK back to where the INIT came from.]
*/
if (chunk->transport)
retval->transport =
sctp_assoc_lookup_paddr(asoc,
&chunk->transport->ipaddr);
retval->subh.init_hdr =
sctp_addto_chunk(retval, sizeof(initack), &initack);
retval->param_hdr.v = sctp_addto_chunk(retval, addrs_len, addrs.v);
sctp_addto_chunk(retval, cookie_len, cookie);
if (asoc->peer.ecn_capable)
sctp_addto_chunk(retval, sizeof(ecap_param), &ecap_param);
if (num_ext) {
ext_param.param_hdr.type = SCTP_PARAM_SUPPORTED_EXT;
ext_param.param_hdr.length = htons(sizeof(ext_param) + num_ext);
sctp_addto_chunk(retval, sizeof(ext_param), &ext_param);
sctp_addto_param(retval, num_ext, extensions);
}
if (asoc->peer.prsctp_capable)
sctp_addto_chunk(retval, sizeof(prsctp_param), &prsctp_param);
if (sp->adaptation_ind) {
aiparam.param_hdr.type = SCTP_PARAM_ADAPTATION_LAYER_IND;
aiparam.param_hdr.length = htons(sizeof(aiparam));
aiparam.adaptation_ind = htonl(sp->adaptation_ind);
sctp_addto_chunk(retval, sizeof(aiparam), &aiparam);
}
if (asoc->peer.auth_capable) {
sctp_addto_chunk(retval, ntohs(auth_random->length),
auth_random);
if (auth_hmacs)
sctp_addto_chunk(retval, ntohs(auth_hmacs->length),
auth_hmacs);
if (auth_chunks)
sctp_addto_chunk(retval, ntohs(auth_chunks->length),
auth_chunks);
}
/* We need to remove the const qualifier at this point. */
retval->asoc = (struct sctp_association *) asoc;
nomem_chunk:
kfree(cookie);
nomem_cookie:
kfree(addrs.v);
return retval;
}
/* 3.3.11 Cookie Echo (COOKIE ECHO) (10):
*
* This chunk is used only during the initialization of an association.
* It is sent by the initiator of an association to its peer to complete
* the initialization process. This chunk MUST precede any DATA chunk
* sent within the association, but MAY be bundled with one or more DATA
* chunks in the same packet.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 10 |Chunk Flags | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* / Cookie /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Chunk Flags: 8 bit
*
* Set to zero on transmit and ignored on receipt.
*
* Length: 16 bits (unsigned integer)
*
* Set to the size of the chunk in bytes, including the 4 bytes of
* the chunk header and the size of the Cookie.
*
* Cookie: variable size
*
* This field must contain the exact cookie received in the
* State Cookie parameter from the previous INIT ACK.
*
* An implementation SHOULD make the cookie as small as possible
* to insure interoperability.
*/
struct sctp_chunk *sctp_make_cookie_echo(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
int cookie_len;
void *cookie;
cookie = asoc->peer.cookie;
cookie_len = asoc->peer.cookie_len;
/* Build a cookie echo chunk. */
retval = sctp_make_control(asoc, SCTP_CID_COOKIE_ECHO, 0,
cookie_len, GFP_ATOMIC);
if (!retval)
goto nodata;
retval->subh.cookie_hdr =
sctp_addto_chunk(retval, cookie_len, cookie);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [COOKIE ECHO back to where the INIT ACK came from.]
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* 3.3.12 Cookie Acknowledgement (COOKIE ACK) (11):
*
* This chunk is used only during the initialization of an
* association. It is used to acknowledge the receipt of a COOKIE
* ECHO chunk. This chunk MUST precede any DATA or SACK chunk sent
* within the association, but MAY be bundled with one or more DATA
* chunks or SACK chunk in the same SCTP packet.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 11 |Chunk Flags | Length = 4 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Chunk Flags: 8 bits
*
* Set to zero on transmit and ignored on receipt.
*/
struct sctp_chunk *sctp_make_cookie_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
retval = sctp_make_control(asoc, SCTP_CID_COOKIE_ACK, 0, 0, GFP_ATOMIC);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [COOKIE ACK back to where the COOKIE ECHO came from.]
*/
if (retval && chunk && chunk->transport)
retval->transport =
sctp_assoc_lookup_paddr(asoc,
&chunk->transport->ipaddr);
return retval;
}
/*
* Appendix A: Explicit Congestion Notification:
* CWR:
*
* RFC 2481 details a specific bit for a sender to send in the header of
* its next outbound TCP segment to indicate to its peer that it has
* reduced its congestion window. This is termed the CWR bit. For
* SCTP the same indication is made by including the CWR chunk.
* This chunk contains one data element, i.e. the TSN number that
* was sent in the ECNE chunk. This element represents the lowest
* TSN number in the datagram that was originally marked with the
* CE bit.
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Chunk Type=13 | Flags=00000000| Chunk Length = 8 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Lowest TSN Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Note: The CWR is considered a Control chunk.
*/
struct sctp_chunk *sctp_make_cwr(const struct sctp_association *asoc,
const __u32 lowest_tsn,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
struct sctp_cwrhdr cwr;
cwr.lowest_tsn = htonl(lowest_tsn);
retval = sctp_make_control(asoc, SCTP_CID_ECN_CWR, 0,
sizeof(cwr), GFP_ATOMIC);
if (!retval)
goto nodata;
retval->subh.ecn_cwr_hdr =
sctp_addto_chunk(retval, sizeof(cwr), &cwr);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [Report a reduced congestion window back to where the ECNE
* came from.]
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* Make an ECNE chunk. This is a congestion experienced report. */
struct sctp_chunk *sctp_make_ecne(const struct sctp_association *asoc,
const __u32 lowest_tsn)
{
struct sctp_chunk *retval;
struct sctp_ecnehdr ecne;
ecne.lowest_tsn = htonl(lowest_tsn);
retval = sctp_make_control(asoc, SCTP_CID_ECN_ECNE, 0,
sizeof(ecne), GFP_ATOMIC);
if (!retval)
goto nodata;
retval->subh.ecne_hdr =
sctp_addto_chunk(retval, sizeof(ecne), &ecne);
nodata:
return retval;
}
/* Make a DATA chunk for the given association from the provided
* parameters. However, do not populate the data payload.
*/
struct sctp_chunk *sctp_make_datafrag_empty(const struct sctp_association *asoc,
const struct sctp_sndrcvinfo *sinfo,
int len, __u8 flags, gfp_t gfp)
{
struct sctp_chunk *retval;
struct sctp_datahdr dp;
/* We assign the TSN as LATE as possible, not here when
* creating the chunk.
*/
memset(&dp, 0, sizeof(dp));
dp.ppid = sinfo->sinfo_ppid;
dp.stream = htons(sinfo->sinfo_stream);
/* Set the flags for an unordered send. */
if (sinfo->sinfo_flags & SCTP_UNORDERED)
flags |= SCTP_DATA_UNORDERED;
retval = sctp_make_data(asoc, flags, sizeof(dp) + len, gfp);
if (!retval)
return NULL;
retval->subh.data_hdr = sctp_addto_chunk(retval, sizeof(dp), &dp);
memcpy(&retval->sinfo, sinfo, sizeof(struct sctp_sndrcvinfo));
return retval;
}
/* Create a selective ackowledgement (SACK) for the given
* association. This reports on which TSN's we've seen to date,
* including duplicates and gaps.
*/
struct sctp_chunk *sctp_make_sack(struct sctp_association *asoc)
{
struct sctp_tsnmap *map = (struct sctp_tsnmap *)&asoc->peer.tsn_map;
struct sctp_gap_ack_block gabs[SCTP_MAX_GABS];
__u16 num_gabs, num_dup_tsns;
struct sctp_transport *trans;
struct sctp_chunk *retval;
struct sctp_sackhdr sack;
__u32 ctsn;
int len;
memset(gabs, 0, sizeof(gabs));
ctsn = sctp_tsnmap_get_ctsn(map);
pr_debug("%s: sackCTSNAck sent:0x%x\n", __func__, ctsn);
/* How much room is needed in the chunk? */
num_gabs = sctp_tsnmap_num_gabs(map, gabs);
num_dup_tsns = sctp_tsnmap_num_dups(map);
/* Initialize the SACK header. */
sack.cum_tsn_ack = htonl(ctsn);
sack.a_rwnd = htonl(asoc->a_rwnd);
sack.num_gap_ack_blocks = htons(num_gabs);
sack.num_dup_tsns = htons(num_dup_tsns);
len = sizeof(sack)
+ sizeof(struct sctp_gap_ack_block) * num_gabs
+ sizeof(__u32) * num_dup_tsns;
/* Create the chunk. */
retval = sctp_make_control(asoc, SCTP_CID_SACK, 0, len, GFP_ATOMIC);
if (!retval)
goto nodata;
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, etc.) to the same destination transport
* address from which it received the DATA or control chunk to
* which it is replying. This rule should also be followed if
* the endpoint is bundling DATA chunks together with the
* reply chunk.
*
* However, when acknowledging multiple DATA chunks received
* in packets from different source addresses in a single
* SACK, the SACK chunk may be transmitted to one of the
* destination transport addresses from which the DATA or
* control chunks being acknowledged were received.
*
* [BUG: We do not implement the following paragraph.
* Perhaps we should remember the last transport we used for a
* SACK and avoid that (if possible) if we have seen any
* duplicates. --piggy]
*
* When a receiver of a duplicate DATA chunk sends a SACK to a
* multi- homed endpoint it MAY be beneficial to vary the
* destination address and not use the source address of the
* DATA chunk. The reason being that receiving a duplicate
* from a multi-homed endpoint might indicate that the return
* path (as specified in the source address of the DATA chunk)
* for the SACK is broken.
*
* [Send to the address from which we last received a DATA chunk.]
*/
retval->transport = asoc->peer.last_data_from;
retval->subh.sack_hdr =
sctp_addto_chunk(retval, sizeof(sack), &sack);
/* Add the gap ack block information. */
if (num_gabs)
sctp_addto_chunk(retval, sizeof(__u32) * num_gabs,
gabs);
/* Add the duplicate TSN information. */
if (num_dup_tsns) {
asoc->stats.idupchunks += num_dup_tsns;
sctp_addto_chunk(retval, sizeof(__u32) * num_dup_tsns,
sctp_tsnmap_get_dups(map));
}
/* Once we have a sack generated, check to see what our sack
* generation is, if its 0, reset the transports to 0, and reset
* the association generation to 1
*
* The idea is that zero is never used as a valid generation for the
* association so no transport will match after a wrap event like this,
* Until the next sack
*/
if (++asoc->peer.sack_generation == 0) {
list_for_each_entry(trans, &asoc->peer.transport_addr_list,
transports)
trans->sack_generation = 0;
asoc->peer.sack_generation = 1;
}
nodata:
return retval;
}
/* Make a SHUTDOWN chunk. */
struct sctp_chunk *sctp_make_shutdown(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_shutdownhdr shut;
struct sctp_chunk *retval;
__u32 ctsn;
ctsn = sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map);
shut.cum_tsn_ack = htonl(ctsn);
retval = sctp_make_control(asoc, SCTP_CID_SHUTDOWN, 0,
sizeof(shut), GFP_ATOMIC);
if (!retval)
goto nodata;
retval->subh.shutdown_hdr =
sctp_addto_chunk(retval, sizeof(shut), &shut);
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
struct sctp_chunk *sctp_make_shutdown_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
retval = sctp_make_control(asoc, SCTP_CID_SHUTDOWN_ACK, 0, 0,
GFP_ATOMIC);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [ACK back to where the SHUTDOWN came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
struct sctp_chunk *sctp_make_shutdown_complete(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_chunk *retval;
__u8 flags = 0;
/* Set the T-bit if we have no association (vtag will be
* reflected)
*/
flags |= asoc ? 0 : SCTP_CHUNK_FLAG_T;
retval = sctp_make_control(asoc, SCTP_CID_SHUTDOWN_COMPLETE, flags,
0, GFP_ATOMIC);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [Report SHUTDOWN COMPLETE back to where the SHUTDOWN ACK
* came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
/* Create an ABORT. Note that we set the T bit if we have no
* association, except when responding to an INIT (sctpimpguide 2.41).
*/
struct sctp_chunk *sctp_make_abort(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
const size_t hint)
{
struct sctp_chunk *retval;
__u8 flags = 0;
/* Set the T-bit if we have no association and 'chunk' is not
* an INIT (vtag will be reflected).
*/
if (!asoc) {
if (chunk && chunk->chunk_hdr &&
chunk->chunk_hdr->type == SCTP_CID_INIT)
flags = 0;
else
flags = SCTP_CHUNK_FLAG_T;
}
retval = sctp_make_control(asoc, SCTP_CID_ABORT, flags, hint,
GFP_ATOMIC);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [ABORT back to where the offender came from.]
*/
if (retval && chunk)
retval->transport = chunk->transport;
return retval;
}
/* Helper to create ABORT with a NO_USER_DATA error. */
struct sctp_chunk *sctp_make_abort_no_data(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
__u32 tsn)
{
struct sctp_chunk *retval;
__be32 payload;
retval = sctp_make_abort(asoc, chunk,
sizeof(struct sctp_errhdr) + sizeof(tsn));
if (!retval)
goto no_mem;
/* Put the tsn back into network byte order. */
payload = htonl(tsn);
sctp_init_cause(retval, SCTP_ERROR_NO_DATA, sizeof(payload));
sctp_addto_chunk(retval, sizeof(payload), (const void *)&payload);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [ABORT back to where the offender came from.]
*/
if (chunk)
retval->transport = chunk->transport;
no_mem:
return retval;
}
/* Helper to create ABORT with a SCTP_ERROR_USER_ABORT error. */
struct sctp_chunk *sctp_make_abort_user(const struct sctp_association *asoc,
struct msghdr *msg,
size_t paylen)
{
struct sctp_chunk *retval;
void *payload = NULL;
int err;
retval = sctp_make_abort(asoc, NULL,
sizeof(struct sctp_errhdr) + paylen);
if (!retval)
goto err_chunk;
if (paylen) {
/* Put the msg_iov together into payload. */
payload = kmalloc(paylen, GFP_KERNEL);
if (!payload)
goto err_payload;
err = memcpy_from_msg(payload, msg, paylen);
if (err < 0)
goto err_copy;
}
sctp_init_cause(retval, SCTP_ERROR_USER_ABORT, paylen);
sctp_addto_chunk(retval, paylen, payload);
if (paylen)
kfree(payload);
return retval;
err_copy:
kfree(payload);
err_payload:
sctp_chunk_free(retval);
retval = NULL;
err_chunk:
return retval;
}
/* Append bytes to the end of a parameter. Will panic if chunk is not big
* enough.
*/
static void *sctp_addto_param(struct sctp_chunk *chunk, int len,
const void *data)
{
int chunklen = ntohs(chunk->chunk_hdr->length);
void *target;
target = skb_put(chunk->skb, len);
if (data)
memcpy(target, data, len);
else
memset(target, 0, len);
/* Adjust the chunk length field. */
chunk->chunk_hdr->length = htons(chunklen + len);
chunk->chunk_end = skb_tail_pointer(chunk->skb);
return target;
}
/* Make an ABORT chunk with a PROTOCOL VIOLATION cause code. */
struct sctp_chunk *sctp_make_abort_violation(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
const __u8 *payload,
const size_t paylen)
{
struct sctp_chunk *retval;
struct sctp_paramhdr phdr;
retval = sctp_make_abort(asoc, chunk, sizeof(struct sctp_errhdr) +
paylen + sizeof(phdr));
if (!retval)
goto end;
sctp_init_cause(retval, SCTP_ERROR_PROTO_VIOLATION, paylen +
sizeof(phdr));
phdr.type = htons(chunk->chunk_hdr->type);
phdr.length = chunk->chunk_hdr->length;
sctp_addto_chunk(retval, paylen, payload);
sctp_addto_param(retval, sizeof(phdr), &phdr);
end:
return retval;
}
struct sctp_chunk *sctp_make_violation_paramlen(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
struct sctp_paramhdr *param)
{
static const char error[] = "The following parameter had invalid length:";
size_t payload_len = sizeof(error) + sizeof(struct sctp_errhdr) +
sizeof(*param);
struct sctp_chunk *retval;
retval = sctp_make_abort(asoc, chunk, payload_len);
if (!retval)
goto nodata;
sctp_init_cause(retval, SCTP_ERROR_PROTO_VIOLATION,
sizeof(error) + sizeof(*param));
sctp_addto_chunk(retval, sizeof(error), error);
sctp_addto_param(retval, sizeof(*param), param);
nodata:
return retval;
}
struct sctp_chunk *sctp_make_violation_max_retrans(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
static const char error[] = "Association exceeded its max_retrans count";
size_t payload_len = sizeof(error) + sizeof(struct sctp_errhdr);
struct sctp_chunk *retval;
retval = sctp_make_abort(asoc, chunk, payload_len);
if (!retval)
goto nodata;
sctp_init_cause(retval, SCTP_ERROR_PROTO_VIOLATION, sizeof(error));
sctp_addto_chunk(retval, sizeof(error), error);
nodata:
return retval;
}
struct sctp_chunk *sctp_make_new_encap_port(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_new_encap_port_hdr nep;
struct sctp_chunk *retval;
retval = sctp_make_abort(asoc, chunk,
sizeof(struct sctp_errhdr) + sizeof(nep));
if (!retval)
goto nodata;
sctp_init_cause(retval, SCTP_ERROR_NEW_ENCAP_PORT, sizeof(nep));
nep.cur_port = SCTP_INPUT_CB(chunk->skb)->encap_port;
nep.new_port = chunk->transport->encap_port;
sctp_addto_chunk(retval, sizeof(nep), &nep);
nodata:
return retval;
}
/* Make a HEARTBEAT chunk. */
struct sctp_chunk *sctp_make_heartbeat(const struct sctp_association *asoc,
const struct sctp_transport *transport,
__u32 probe_size)
{
struct sctp_sender_hb_info hbinfo = {};
struct sctp_chunk *retval;
retval = sctp_make_control(asoc, SCTP_CID_HEARTBEAT, 0,
sizeof(hbinfo), GFP_ATOMIC);
if (!retval)
goto nodata;
hbinfo.param_hdr.type = SCTP_PARAM_HEARTBEAT_INFO;
hbinfo.param_hdr.length = htons(sizeof(hbinfo));
hbinfo.daddr = transport->ipaddr;
hbinfo.sent_at = jiffies;
hbinfo.hb_nonce = transport->hb_nonce;
hbinfo.probe_size = probe_size;
/* Cast away the 'const', as this is just telling the chunk
* what transport it belongs to.
*/
retval->transport = (struct sctp_transport *) transport;
retval->subh.hbs_hdr = sctp_addto_chunk(retval, sizeof(hbinfo),
&hbinfo);
retval->pmtu_probe = !!probe_size;
nodata:
return retval;
}
struct sctp_chunk *sctp_make_heartbeat_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
const void *payload,
const size_t paylen)
{
struct sctp_chunk *retval;
retval = sctp_make_control(asoc, SCTP_CID_HEARTBEAT_ACK, 0, paylen,
GFP_ATOMIC);
if (!retval)
goto nodata;
retval->subh.hbs_hdr = sctp_addto_chunk(retval, paylen, payload);
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it * received the DATA or control chunk
* to which it is replying.
*
* [HBACK back to where the HEARTBEAT came from.]
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* RFC4820 3. Padding Chunk (PAD)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0x84 | Flags=0 | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | |
* \ Padding Data /
* / \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct sctp_chunk *sctp_make_pad(const struct sctp_association *asoc, int len)
{
struct sctp_chunk *retval;
retval = sctp_make_control(asoc, SCTP_CID_PAD, 0, len, GFP_ATOMIC);
if (!retval)
return NULL;
skb_put_zero(retval->skb, len);
retval->chunk_hdr->length = htons(ntohs(retval->chunk_hdr->length) + len);
retval->chunk_end = skb_tail_pointer(retval->skb);
return retval;
}
/* Create an Operation Error chunk with the specified space reserved.
* This routine can be used for containing multiple causes in the chunk.
*/
static struct sctp_chunk *sctp_make_op_error_space(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
size_t size)
{
struct sctp_chunk *retval;
retval = sctp_make_control(asoc, SCTP_CID_ERROR, 0,
sizeof(struct sctp_errhdr) + size,
GFP_ATOMIC);
if (!retval)
goto nodata;
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, etc.) to the same destination transport
* address from which it received the DATA or control chunk
* to which it is replying.
*
*/
if (chunk)
retval->transport = chunk->transport;
nodata:
return retval;
}
/* Create an Operation Error chunk of a fixed size, specifically,
* min(asoc->pathmtu, SCTP_DEFAULT_MAXSEGMENT) - overheads.
* This is a helper function to allocate an error chunk for those
* invalid parameter codes in which we may not want to report all the
* errors, if the incoming chunk is large. If it can't fit in a single
* packet, we ignore it.
*/
static inline struct sctp_chunk *sctp_make_op_error_limited(
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
size_t size = SCTP_DEFAULT_MAXSEGMENT;
struct sctp_sock *sp = NULL;
if (asoc) {
size = min_t(size_t, size, asoc->pathmtu);
sp = sctp_sk(asoc->base.sk);
}
size = sctp_mtu_payload(sp, size, sizeof(struct sctp_errhdr));
return sctp_make_op_error_space(asoc, chunk, size);
}
/* Create an Operation Error chunk. */
struct sctp_chunk *sctp_make_op_error(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
__be16 cause_code, const void *payload,
size_t paylen, size_t reserve_tail)
{
struct sctp_chunk *retval;
retval = sctp_make_op_error_space(asoc, chunk, paylen + reserve_tail);
if (!retval)
goto nodata;
sctp_init_cause(retval, cause_code, paylen + reserve_tail);
sctp_addto_chunk(retval, paylen, payload);
if (reserve_tail)
sctp_addto_param(retval, reserve_tail, NULL);
nodata:
return retval;
}
struct sctp_chunk *sctp_make_auth(const struct sctp_association *asoc,
__u16 key_id)
{
struct sctp_authhdr auth_hdr;
struct sctp_hmac *hmac_desc;
struct sctp_chunk *retval;
/* Get the first hmac that the peer told us to use */
hmac_desc = sctp_auth_asoc_get_hmac(asoc);
if (unlikely(!hmac_desc))
return NULL;
retval = sctp_make_control(asoc, SCTP_CID_AUTH, 0,
hmac_desc->hmac_len + sizeof(auth_hdr),
GFP_ATOMIC);
if (!retval)
return NULL;
auth_hdr.hmac_id = htons(hmac_desc->hmac_id);
auth_hdr.shkey_id = htons(key_id);
retval->subh.auth_hdr = sctp_addto_chunk(retval, sizeof(auth_hdr),
&auth_hdr);
skb_put_zero(retval->skb, hmac_desc->hmac_len);
/* Adjust the chunk header to include the empty MAC */
retval->chunk_hdr->length =
htons(ntohs(retval->chunk_hdr->length) + hmac_desc->hmac_len);
retval->chunk_end = skb_tail_pointer(retval->skb);
return retval;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* Turn an skb into a chunk.
* FIXME: Eventually move the structure directly inside the skb->cb[].
*
* sctpimpguide-05.txt Section 2.8.2
* M1) Each time a new DATA chunk is transmitted
* set the 'TSN.Missing.Report' count for that TSN to 0. The
* 'TSN.Missing.Report' count will be used to determine missing chunks
* and when to fast retransmit.
*
*/
struct sctp_chunk *sctp_chunkify(struct sk_buff *skb,
const struct sctp_association *asoc,
struct sock *sk, gfp_t gfp)
{
struct sctp_chunk *retval;
retval = kmem_cache_zalloc(sctp_chunk_cachep, gfp);
if (!retval)
goto nodata;
if (!sk)
pr_debug("%s: chunkifying skb:%p w/o an sk\n", __func__, skb);
INIT_LIST_HEAD(&retval->list);
retval->skb = skb;
retval->asoc = (struct sctp_association *)asoc;
retval->singleton = 1;
retval->fast_retransmit = SCTP_CAN_FRTX;
/* Polish the bead hole. */
INIT_LIST_HEAD(&retval->transmitted_list);
INIT_LIST_HEAD(&retval->frag_list);
SCTP_DBG_OBJCNT_INC(chunk);
refcount_set(&retval->refcnt, 1);
nodata:
return retval;
}
/* Set chunk->source and dest based on the IP header in chunk->skb. */
void sctp_init_addrs(struct sctp_chunk *chunk, union sctp_addr *src,
union sctp_addr *dest)
{
memcpy(&chunk->source, src, sizeof(union sctp_addr));
memcpy(&chunk->dest, dest, sizeof(union sctp_addr));
}
/* Extract the source address from a chunk. */
const union sctp_addr *sctp_source(const struct sctp_chunk *chunk)
{
/* If we have a known transport, use that. */
if (chunk->transport) {
return &chunk->transport->ipaddr;
} else {
/* Otherwise, extract it from the IP header. */
return &chunk->source;
}
}
/* Create a new chunk, setting the type and flags headers from the
* arguments, reserving enough space for a 'paylen' byte payload.
*/
static struct sctp_chunk *_sctp_make_chunk(const struct sctp_association *asoc,
__u8 type, __u8 flags, int paylen,
gfp_t gfp)
{
struct sctp_chunkhdr *chunk_hdr;
struct sctp_chunk *retval;
struct sk_buff *skb;
struct sock *sk;
int chunklen;
chunklen = SCTP_PAD4(sizeof(*chunk_hdr) + paylen);
if (chunklen > SCTP_MAX_CHUNK_LEN)
goto nodata;
/* No need to allocate LL here, as this is only a chunk. */
skb = alloc_skb(chunklen, gfp);
if (!skb)
goto nodata;
/* Make room for the chunk header. */
chunk_hdr = (struct sctp_chunkhdr *)skb_put(skb, sizeof(*chunk_hdr));
chunk_hdr->type = type;
chunk_hdr->flags = flags;
chunk_hdr->length = htons(sizeof(*chunk_hdr));
sk = asoc ? asoc->base.sk : NULL;
retval = sctp_chunkify(skb, asoc, sk, gfp);
if (!retval) {
kfree_skb(skb);
goto nodata;
}
retval->chunk_hdr = chunk_hdr;
retval->chunk_end = ((__u8 *)chunk_hdr) + sizeof(*chunk_hdr);
/* Determine if the chunk needs to be authenticated */
if (sctp_auth_send_cid(type, asoc))
retval->auth = 1;
return retval;
nodata:
return NULL;
}
static struct sctp_chunk *sctp_make_data(const struct sctp_association *asoc,
__u8 flags, int paylen, gfp_t gfp)
{
return _sctp_make_chunk(asoc, SCTP_CID_DATA, flags, paylen, gfp);
}
struct sctp_chunk *sctp_make_idata(const struct sctp_association *asoc,
__u8 flags, int paylen, gfp_t gfp)
{
return _sctp_make_chunk(asoc, SCTP_CID_I_DATA, flags, paylen, gfp);
}
static struct sctp_chunk *sctp_make_control(const struct sctp_association *asoc,
__u8 type, __u8 flags, int paylen,
gfp_t gfp)
{
struct sctp_chunk *chunk;
chunk = _sctp_make_chunk(asoc, type, flags, paylen, gfp);
if (chunk)
sctp_control_set_owner_w(chunk);
return chunk;
}
/* Release the memory occupied by a chunk. */
static void sctp_chunk_destroy(struct sctp_chunk *chunk)
{
BUG_ON(!list_empty(&chunk->list));
list_del_init(&chunk->transmitted_list);
consume_skb(chunk->skb);
consume_skb(chunk->auth_chunk);
SCTP_DBG_OBJCNT_DEC(chunk);
kmem_cache_free(sctp_chunk_cachep, chunk);
}
/* Possibly, free the chunk. */
void sctp_chunk_free(struct sctp_chunk *chunk)
{
/* Release our reference on the message tracker. */
if (chunk->msg)
sctp_datamsg_put(chunk->msg);
sctp_chunk_put(chunk);
}
/* Grab a reference to the chunk. */
void sctp_chunk_hold(struct sctp_chunk *ch)
{
refcount_inc(&ch->refcnt);
}
/* Release a reference to the chunk. */
void sctp_chunk_put(struct sctp_chunk *ch)
{
if (refcount_dec_and_test(&ch->refcnt))
sctp_chunk_destroy(ch);
}
/* Append bytes to the end of a chunk. Will panic if chunk is not big
* enough.
*/
void *sctp_addto_chunk(struct sctp_chunk *chunk, int len, const void *data)
{
int chunklen = ntohs(chunk->chunk_hdr->length);
int padlen = SCTP_PAD4(chunklen) - chunklen;
void *target;
skb_put_zero(chunk->skb, padlen);
target = skb_put_data(chunk->skb, data, len);
/* Adjust the chunk length field. */
chunk->chunk_hdr->length = htons(chunklen + padlen + len);
chunk->chunk_end = skb_tail_pointer(chunk->skb);
return target;
}
/* Append bytes from user space to the end of a chunk. Will panic if
* chunk is not big enough.
* Returns a kernel err value.
*/
int sctp_user_addto_chunk(struct sctp_chunk *chunk, int len,
struct iov_iter *from)
{
void *target;
/* Make room in chunk for data. */
target = skb_put(chunk->skb, len);
/* Copy data (whole iovec) into chunk */
if (!copy_from_iter_full(target, len, from))
return -EFAULT;
/* Adjust the chunk length field. */
chunk->chunk_hdr->length =
htons(ntohs(chunk->chunk_hdr->length) + len);
chunk->chunk_end = skb_tail_pointer(chunk->skb);
return 0;
}
/* Helper function to assign a TSN if needed. This assumes that both
* the data_hdr and association have already been assigned.
*/
void sctp_chunk_assign_ssn(struct sctp_chunk *chunk)
{
struct sctp_stream *stream;
struct sctp_chunk *lchunk;
struct sctp_datamsg *msg;
__u16 ssn, sid;
if (chunk->has_ssn)
return;
/* All fragments will be on the same stream */
sid = ntohs(chunk->subh.data_hdr->stream);
stream = &chunk->asoc->stream;
/* Now assign the sequence number to the entire message.
* All fragments must have the same stream sequence number.
*/
msg = chunk->msg;
list_for_each_entry(lchunk, &msg->chunks, frag_list) {
if (lchunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
ssn = 0;
} else {
if (lchunk->chunk_hdr->flags & SCTP_DATA_LAST_FRAG)
ssn = sctp_ssn_next(stream, out, sid);
else
ssn = sctp_ssn_peek(stream, out, sid);
}
lchunk->subh.data_hdr->ssn = htons(ssn);
lchunk->has_ssn = 1;
}
}
/* Helper function to assign a TSN if needed. This assumes that both
* the data_hdr and association have already been assigned.
*/
void sctp_chunk_assign_tsn(struct sctp_chunk *chunk)
{
if (!chunk->has_tsn) {
/* This is the last possible instant to
* assign a TSN.
*/
chunk->subh.data_hdr->tsn =
htonl(sctp_association_get_next_tsn(chunk->asoc));
chunk->has_tsn = 1;
}
}
/* Create a CLOSED association to use with an incoming packet. */
struct sctp_association *sctp_make_temp_asoc(const struct sctp_endpoint *ep,
struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sctp_association *asoc;
enum sctp_scope scope;
struct sk_buff *skb;
/* Create the bare association. */
scope = sctp_scope(sctp_source(chunk));
asoc = sctp_association_new(ep, ep->base.sk, scope, gfp);
if (!asoc)
goto nodata;
asoc->temp = 1;
skb = chunk->skb;
/* Create an entry for the source address of the packet. */
SCTP_INPUT_CB(skb)->af->from_skb(&asoc->c.peer_addr, skb, 1);
nodata:
return asoc;
}
/* Build a cookie representing asoc.
* This INCLUDES the param header needed to put the cookie in the INIT ACK.
*/
static struct sctp_cookie_param *sctp_pack_cookie(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *init_chunk,
int *cookie_len, const __u8 *raw_addrs,
int addrs_len)
{
struct sctp_signed_cookie *cookie;
struct sctp_cookie_param *retval;
int headersize, bodysize;
/* Header size is static data prior to the actual cookie, including
* any padding.
*/
headersize = sizeof(struct sctp_paramhdr) +
(sizeof(struct sctp_signed_cookie) -
sizeof(struct sctp_cookie));
bodysize = sizeof(struct sctp_cookie)
+ ntohs(init_chunk->chunk_hdr->length) + addrs_len;
/* Pad out the cookie to a multiple to make the signature
* functions simpler to write.
*/
if (bodysize % SCTP_COOKIE_MULTIPLE)
bodysize += SCTP_COOKIE_MULTIPLE
- (bodysize % SCTP_COOKIE_MULTIPLE);
*cookie_len = headersize + bodysize;
/* Clear this memory since we are sending this data structure
* out on the network.
*/
retval = kzalloc(*cookie_len, GFP_ATOMIC);
if (!retval)
goto nodata;
cookie = (struct sctp_signed_cookie *) retval->body;
/* Set up the parameter header. */
retval->p.type = SCTP_PARAM_STATE_COOKIE;
retval->p.length = htons(*cookie_len);
/* Copy the cookie part of the association itself. */
cookie->c = asoc->c;
/* Save the raw address list length in the cookie. */
cookie->c.raw_addr_list_len = addrs_len;
/* Remember PR-SCTP capability. */
cookie->c.prsctp_capable = asoc->peer.prsctp_capable;
/* Save adaptation indication in the cookie. */
cookie->c.adaptation_ind = asoc->peer.adaptation_ind;
/* Set an expiration time for the cookie. */
cookie->c.expiration = ktime_add(asoc->cookie_life,
ktime_get_real());
/* Copy the peer's init packet. */
memcpy(cookie + 1, init_chunk->chunk_hdr,
ntohs(init_chunk->chunk_hdr->length));
/* Copy the raw local address list of the association. */
memcpy((__u8 *)(cookie + 1) +
ntohs(init_chunk->chunk_hdr->length), raw_addrs, addrs_len);
if (sctp_sk(ep->base.sk)->hmac) {
struct crypto_shash *tfm = sctp_sk(ep->base.sk)->hmac;
int err;
/* Sign the message. */
err = crypto_shash_setkey(tfm, ep->secret_key,
sizeof(ep->secret_key)) ?:
crypto_shash_tfm_digest(tfm, (u8 *)&cookie->c, bodysize,
cookie->signature);
if (err)
goto free_cookie;
}
return retval;
free_cookie:
kfree(retval);
nodata:
*cookie_len = 0;
return NULL;
}
/* Unpack the cookie from COOKIE ECHO chunk, recreating the association. */
struct sctp_association *sctp_unpack_cookie(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk, gfp_t gfp,
int *error, struct sctp_chunk **errp)
{
struct sctp_association *retval = NULL;
int headersize, bodysize, fixed_size;
struct sctp_signed_cookie *cookie;
struct sk_buff *skb = chunk->skb;
struct sctp_cookie *bear_cookie;
__u8 *digest = ep->digest;
enum sctp_scope scope;
unsigned int len;
ktime_t kt;
/* Header size is static data prior to the actual cookie, including
* any padding.
*/
headersize = sizeof(struct sctp_chunkhdr) +
(sizeof(struct sctp_signed_cookie) -
sizeof(struct sctp_cookie));
bodysize = ntohs(chunk->chunk_hdr->length) - headersize;
fixed_size = headersize + sizeof(struct sctp_cookie);
/* Verify that the chunk looks like it even has a cookie.
* There must be enough room for our cookie and our peer's
* INIT chunk.
*/
len = ntohs(chunk->chunk_hdr->length);
if (len < fixed_size + sizeof(struct sctp_chunkhdr))
goto malformed;
/* Verify that the cookie has been padded out. */
if (bodysize % SCTP_COOKIE_MULTIPLE)
goto malformed;
/* Process the cookie. */
cookie = chunk->subh.cookie_hdr;
bear_cookie = &cookie->c;
if (!sctp_sk(ep->base.sk)->hmac)
goto no_hmac;
/* Check the signature. */
{
struct crypto_shash *tfm = sctp_sk(ep->base.sk)->hmac;
int err;
err = crypto_shash_setkey(tfm, ep->secret_key,
sizeof(ep->secret_key)) ?:
crypto_shash_tfm_digest(tfm, (u8 *)bear_cookie, bodysize,
digest);
if (err) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
}
if (memcmp(digest, cookie->signature, SCTP_SIGNATURE_SIZE)) {
*error = -SCTP_IERROR_BAD_SIG;
goto fail;
}
no_hmac:
/* IG Section 2.35.2:
* 3) Compare the port numbers and the verification tag contained
* within the COOKIE ECHO chunk to the actual port numbers and the
* verification tag within the SCTP common header of the received
* packet. If these values do not match the packet MUST be silently
* discarded,
*/
if (ntohl(chunk->sctp_hdr->vtag) != bear_cookie->my_vtag) {
*error = -SCTP_IERROR_BAD_TAG;
goto fail;
}
if (chunk->sctp_hdr->source != bear_cookie->peer_addr.v4.sin_port ||
ntohs(chunk->sctp_hdr->dest) != bear_cookie->my_port) {
*error = -SCTP_IERROR_BAD_PORTS;
goto fail;
}
/* Check to see if the cookie is stale. If there is already
* an association, there is no need to check cookie's expiration
* for init collision case of lost COOKIE ACK.
* If skb has been timestamped, then use the stamp, otherwise
* use current time. This introduces a small possibility that
* a cookie may be considered expired, but this would only slow
* down the new association establishment instead of every packet.
*/
if (sock_flag(ep->base.sk, SOCK_TIMESTAMP))
kt = skb_get_ktime(skb);
else
kt = ktime_get_real();
if (!asoc && ktime_before(bear_cookie->expiration, kt)) {
suseconds_t usecs = ktime_to_us(ktime_sub(kt, bear_cookie->expiration));
__be32 n = htonl(usecs);
/*
* Section 3.3.10.3 Stale Cookie Error (3)
*
* Cause of error
* ---------------
* Stale Cookie Error: Indicates the receipt of a valid State
* Cookie that has expired.
*/
*errp = sctp_make_op_error(asoc, chunk,
SCTP_ERROR_STALE_COOKIE, &n,
sizeof(n), 0);
if (*errp)
*error = -SCTP_IERROR_STALE_COOKIE;
else
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
/* Make a new base association. */
scope = sctp_scope(sctp_source(chunk));
retval = sctp_association_new(ep, ep->base.sk, scope, gfp);
if (!retval) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
/* Set up our peer's port number. */
retval->peer.port = ntohs(chunk->sctp_hdr->source);
/* Populate the association from the cookie. */
memcpy(&retval->c, bear_cookie, sizeof(*bear_cookie));
if (sctp_assoc_set_bind_addr_from_cookie(retval, bear_cookie,
GFP_ATOMIC) < 0) {
*error = -SCTP_IERROR_NOMEM;
goto fail;
}
/* Also, add the destination address. */
if (list_empty(&retval->base.bind_addr.address_list)) {
sctp_add_bind_addr(&retval->base.bind_addr, &chunk->dest,
sizeof(chunk->dest), SCTP_ADDR_SRC,
GFP_ATOMIC);
}
retval->next_tsn = retval->c.initial_tsn;
retval->ctsn_ack_point = retval->next_tsn - 1;
retval->addip_serial = retval->c.initial_tsn;
retval->strreset_outseq = retval->c.initial_tsn;
retval->adv_peer_ack_point = retval->ctsn_ack_point;
retval->peer.prsctp_capable = retval->c.prsctp_capable;
retval->peer.adaptation_ind = retval->c.adaptation_ind;
/* The INIT stuff will be done by the side effects. */
return retval;
fail:
if (retval)
sctp_association_free(retval);
return NULL;
malformed:
/* Yikes! The packet is either corrupt or deliberately
* malformed.
*/
*error = -SCTP_IERROR_MALFORMED;
goto fail;
}
/********************************************************************
* 3rd Level Abstractions
********************************************************************/
struct __sctp_missing {
__be32 num_missing;
__be16 type;
} __packed;
/*
* Report a missing mandatory parameter.
*/
static int sctp_process_missing_param(const struct sctp_association *asoc,
enum sctp_param paramtype,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
struct __sctp_missing report;
__u16 len;
len = SCTP_PAD4(sizeof(report));
/* Make an ERROR chunk, preparing enough room for
* returning multiple unknown parameters.
*/
if (!*errp)
*errp = sctp_make_op_error_space(asoc, chunk, len);
if (*errp) {
report.num_missing = htonl(1);
report.type = paramtype;
sctp_init_cause(*errp, SCTP_ERROR_MISS_PARAM,
sizeof(report));
sctp_addto_chunk(*errp, sizeof(report), &report);
}
/* Stop processing this chunk. */
return 0;
}
/* Report an Invalid Mandatory Parameter. */
static int sctp_process_inv_mandatory(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
/* Invalid Mandatory Parameter Error has no payload. */
if (!*errp)
*errp = sctp_make_op_error_space(asoc, chunk, 0);
if (*errp)
sctp_init_cause(*errp, SCTP_ERROR_INV_PARAM, 0);
/* Stop processing this chunk. */
return 0;
}
static int sctp_process_inv_paramlength(const struct sctp_association *asoc,
struct sctp_paramhdr *param,
const struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
/* This is a fatal error. Any accumulated non-fatal errors are
* not reported.
*/
if (*errp)
sctp_chunk_free(*errp);
/* Create an error chunk and fill it in with our payload. */
*errp = sctp_make_violation_paramlen(asoc, chunk, param);
return 0;
}
/* Do not attempt to handle the HOST_NAME parm. However, do
* send back an indicator to the peer.
*/
static int sctp_process_hn_param(const struct sctp_association *asoc,
union sctp_params param,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
__u16 len = ntohs(param.p->length);
/* Processing of the HOST_NAME parameter will generate an
* ABORT. If we've accumulated any non-fatal errors, they
* would be unrecognized parameters and we should not include
* them in the ABORT.
*/
if (*errp)
sctp_chunk_free(*errp);
*errp = sctp_make_op_error(asoc, chunk, SCTP_ERROR_DNS_FAILED,
param.v, len, 0);
/* Stop processing this chunk. */
return 0;
}
static int sctp_verify_ext_param(struct net *net,
const struct sctp_endpoint *ep,
union sctp_params param)
{
__u16 num_ext = ntohs(param.p->length) - sizeof(struct sctp_paramhdr);
int have_asconf = 0;
int have_auth = 0;
int i;
for (i = 0; i < num_ext; i++) {
switch (param.ext->chunks[i]) {
case SCTP_CID_AUTH:
have_auth = 1;
break;
case SCTP_CID_ASCONF:
case SCTP_CID_ASCONF_ACK:
have_asconf = 1;
break;
}
}
/* ADD-IP Security: The draft requires us to ABORT or ignore the
* INIT/INIT-ACK if ADD-IP is listed, but AUTH is not. Do this
* only if ADD-IP is turned on and we are not backward-compatible
* mode.
*/
if (net->sctp.addip_noauth)
return 1;
if (ep->asconf_enable && !have_auth && have_asconf)
return 0;
return 1;
}
static void sctp_process_ext_param(struct sctp_association *asoc,
union sctp_params param)
{
__u16 num_ext = ntohs(param.p->length) - sizeof(struct sctp_paramhdr);
int i;
for (i = 0; i < num_ext; i++) {
switch (param.ext->chunks[i]) {
case SCTP_CID_RECONF:
if (asoc->ep->reconf_enable)
asoc->peer.reconf_capable = 1;
break;
case SCTP_CID_FWD_TSN:
if (asoc->ep->prsctp_enable)
asoc->peer.prsctp_capable = 1;
break;
case SCTP_CID_AUTH:
/* if the peer reports AUTH, assume that he
* supports AUTH.
*/
if (asoc->ep->auth_enable)
asoc->peer.auth_capable = 1;
break;
case SCTP_CID_ASCONF:
case SCTP_CID_ASCONF_ACK:
if (asoc->ep->asconf_enable)
asoc->peer.asconf_capable = 1;
break;
case SCTP_CID_I_DATA:
if (asoc->ep->intl_enable)
asoc->peer.intl_capable = 1;
break;
default:
break;
}
}
}
/* RFC 3.2.1 & the Implementers Guide 2.2.
*
* The Parameter Types are encoded such that the
* highest-order two bits specify the action that must be
* taken if the processing endpoint does not recognize the
* Parameter Type.
*
* 00 - Stop processing this parameter; do not process any further
* parameters within this chunk
*
* 01 - Stop processing this parameter, do not process any further
* parameters within this chunk, and report the unrecognized
* parameter in an 'Unrecognized Parameter' ERROR chunk.
*
* 10 - Skip this parameter and continue processing.
*
* 11 - Skip this parameter and continue processing but
* report the unrecognized parameter in an
* 'Unrecognized Parameter' ERROR chunk.
*
* Return value:
* SCTP_IERROR_NO_ERROR - continue with the chunk
* SCTP_IERROR_ERROR - stop and report an error.
* SCTP_IERROR_NOMEME - out of memory.
*/
static enum sctp_ierror sctp_process_unk_param(
const struct sctp_association *asoc,
union sctp_params param,
struct sctp_chunk *chunk,
struct sctp_chunk **errp)
{
int retval = SCTP_IERROR_NO_ERROR;
switch (param.p->type & SCTP_PARAM_ACTION_MASK) {
case SCTP_PARAM_ACTION_DISCARD:
retval = SCTP_IERROR_ERROR;
break;
case SCTP_PARAM_ACTION_SKIP:
break;
case SCTP_PARAM_ACTION_DISCARD_ERR:
retval = SCTP_IERROR_ERROR;
fallthrough;
case SCTP_PARAM_ACTION_SKIP_ERR:
/* Make an ERROR chunk, preparing enough room for
* returning multiple unknown parameters.
*/
if (!*errp) {
*errp = sctp_make_op_error_limited(asoc, chunk);
if (!*errp) {
/* If there is no memory for generating the
* ERROR report as specified, an ABORT will be
* triggered to the peer and the association
* won't be established.
*/
retval = SCTP_IERROR_NOMEM;
break;
}
}
if (!sctp_init_cause(*errp, SCTP_ERROR_UNKNOWN_PARAM,
ntohs(param.p->length)))
sctp_addto_chunk(*errp, ntohs(param.p->length),
param.v);
break;
default:
break;
}
return retval;
}
/* Verify variable length parameters
* Return values:
* SCTP_IERROR_ABORT - trigger an ABORT
* SCTP_IERROR_NOMEM - out of memory (abort)
* SCTP_IERROR_ERROR - stop processing, trigger an ERROR
* SCTP_IERROR_NO_ERROR - continue with the chunk
*/
static enum sctp_ierror sctp_verify_param(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
union sctp_params param,
enum sctp_cid cid,
struct sctp_chunk *chunk,
struct sctp_chunk **err_chunk)
{
struct sctp_hmac_algo_param *hmacs;
int retval = SCTP_IERROR_NO_ERROR;
__u16 n_elt, id = 0;
int i;
/* FIXME - This routine is not looking at each parameter per the
* chunk type, i.e., unrecognized parameters should be further
* identified based on the chunk id.
*/
switch (param.p->type) {
case SCTP_PARAM_IPV4_ADDRESS:
case SCTP_PARAM_IPV6_ADDRESS:
case SCTP_PARAM_COOKIE_PRESERVATIVE:
case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
case SCTP_PARAM_STATE_COOKIE:
case SCTP_PARAM_HEARTBEAT_INFO:
case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
case SCTP_PARAM_ECN_CAPABLE:
case SCTP_PARAM_ADAPTATION_LAYER_IND:
break;
case SCTP_PARAM_SUPPORTED_EXT:
if (!sctp_verify_ext_param(net, ep, param))
return SCTP_IERROR_ABORT;
break;
case SCTP_PARAM_SET_PRIMARY:
if (!ep->asconf_enable)
goto unhandled;
if (ntohs(param.p->length) < sizeof(struct sctp_addip_param) +
sizeof(struct sctp_paramhdr)) {
sctp_process_inv_paramlength(asoc, param.p,
chunk, err_chunk);
retval = SCTP_IERROR_ABORT;
}
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
/* This param has been Deprecated, send ABORT. */
sctp_process_hn_param(asoc, param, chunk, err_chunk);
retval = SCTP_IERROR_ABORT;
break;
case SCTP_PARAM_FWD_TSN_SUPPORT:
if (ep->prsctp_enable)
break;
goto unhandled;
case SCTP_PARAM_RANDOM:
if (!ep->auth_enable)
goto unhandled;
/* SCTP-AUTH: Secion 6.1
* If the random number is not 32 byte long the association
* MUST be aborted. The ABORT chunk SHOULD contain the error
* cause 'Protocol Violation'.
*/
if (SCTP_AUTH_RANDOM_LENGTH != ntohs(param.p->length) -
sizeof(struct sctp_paramhdr)) {
sctp_process_inv_paramlength(asoc, param.p,
chunk, err_chunk);
retval = SCTP_IERROR_ABORT;
}
break;
case SCTP_PARAM_CHUNKS:
if (!ep->auth_enable)
goto unhandled;
/* SCTP-AUTH: Section 3.2
* The CHUNKS parameter MUST be included once in the INIT or
* INIT-ACK chunk if the sender wants to receive authenticated
* chunks. Its maximum length is 260 bytes.
*/
if (260 < ntohs(param.p->length)) {
sctp_process_inv_paramlength(asoc, param.p,
chunk, err_chunk);
retval = SCTP_IERROR_ABORT;
}
break;
case SCTP_PARAM_HMAC_ALGO:
if (!ep->auth_enable)
goto unhandled;
hmacs = (struct sctp_hmac_algo_param *)param.p;
n_elt = (ntohs(param.p->length) -
sizeof(struct sctp_paramhdr)) >> 1;
/* SCTP-AUTH: Section 6.1
* The HMAC algorithm based on SHA-1 MUST be supported and
* included in the HMAC-ALGO parameter.
*/
for (i = 0; i < n_elt; i++) {
id = ntohs(hmacs->hmac_ids[i]);
if (id == SCTP_AUTH_HMAC_ID_SHA1)
break;
}
if (id != SCTP_AUTH_HMAC_ID_SHA1) {
sctp_process_inv_paramlength(asoc, param.p, chunk,
err_chunk);
retval = SCTP_IERROR_ABORT;
}
break;
unhandled:
default:
pr_debug("%s: unrecognized param:%d for chunk:%d\n",
__func__, ntohs(param.p->type), cid);
retval = sctp_process_unk_param(asoc, param, chunk, err_chunk);
break;
}
return retval;
}
/* Verify the INIT packet before we process it. */
int sctp_verify_init(struct net *net, const struct sctp_endpoint *ep,
const struct sctp_association *asoc, enum sctp_cid cid,
struct sctp_init_chunk *peer_init,
struct sctp_chunk *chunk, struct sctp_chunk **errp)
{
union sctp_params param;
bool has_cookie = false;
int result;
/* Check for missing mandatory parameters. Note: Initial TSN is
* also mandatory, but is not checked here since the valid range
* is 0..2**32-1. RFC4960, section 3.3.3.
*/
if (peer_init->init_hdr.num_outbound_streams == 0 ||
peer_init->init_hdr.num_inbound_streams == 0 ||
peer_init->init_hdr.init_tag == 0 ||
ntohl(peer_init->init_hdr.a_rwnd) < SCTP_DEFAULT_MINWINDOW)
return sctp_process_inv_mandatory(asoc, chunk, errp);
sctp_walk_params(param, peer_init) {
if (param.p->type == SCTP_PARAM_STATE_COOKIE)
has_cookie = true;
}
/* There is a possibility that a parameter length was bad and
* in that case we would have stoped walking the parameters.
* The current param.p would point at the bad one.
* Current consensus on the mailing list is to generate a PROTOCOL
* VIOLATION error. We build the ERROR chunk here and let the normal
* error handling code build and send the packet.
*/
if (param.v != (void *)chunk->chunk_end)
return sctp_process_inv_paramlength(asoc, param.p, chunk, errp);
/* The only missing mandatory param possible today is
* the state cookie for an INIT-ACK chunk.
*/
if ((SCTP_CID_INIT_ACK == cid) && !has_cookie)
return sctp_process_missing_param(asoc, SCTP_PARAM_STATE_COOKIE,
chunk, errp);
/* Verify all the variable length parameters */
sctp_walk_params(param, peer_init) {
result = sctp_verify_param(net, ep, asoc, param, cid,
chunk, errp);
switch (result) {
case SCTP_IERROR_ABORT:
case SCTP_IERROR_NOMEM:
return 0;
case SCTP_IERROR_ERROR:
return 1;
case SCTP_IERROR_NO_ERROR:
default:
break;
}
} /* for (loop through all parameters) */
return 1;
}
/* Unpack the parameters in an INIT packet into an association.
* Returns 0 on failure, else success.
* FIXME: This is an association method.
*/
int sctp_process_init(struct sctp_association *asoc, struct sctp_chunk *chunk,
const union sctp_addr *peer_addr,
struct sctp_init_chunk *peer_init, gfp_t gfp)
{
struct sctp_transport *transport;
struct list_head *pos, *temp;
union sctp_params param;
union sctp_addr addr;
struct sctp_af *af;
int src_match = 0;
/* We must include the address that the INIT packet came from.
* This is the only address that matters for an INIT packet.
* When processing a COOKIE ECHO, we retrieve the from address
* of the INIT from the cookie.
*/
/* This implementation defaults to making the first transport
* added as the primary transport. The source address seems to
* be a better choice than any of the embedded addresses.
*/
asoc->encap_port = SCTP_INPUT_CB(chunk->skb)->encap_port;
if (!sctp_assoc_add_peer(asoc, peer_addr, gfp, SCTP_ACTIVE))
goto nomem;
if (sctp_cmp_addr_exact(sctp_source(chunk), peer_addr))
src_match = 1;
/* Process the initialization parameters. */
sctp_walk_params(param, peer_init) {
if (!src_match &&
(param.p->type == SCTP_PARAM_IPV4_ADDRESS ||
param.p->type == SCTP_PARAM_IPV6_ADDRESS)) {
af = sctp_get_af_specific(param_type2af(param.p->type));
if (!af->from_addr_param(&addr, param.addr,
chunk->sctp_hdr->source, 0))
continue;
if (sctp_cmp_addr_exact(sctp_source(chunk), &addr))
src_match = 1;
}
if (!sctp_process_param(asoc, param, peer_addr, gfp))
goto clean_up;
}
/* source address of chunk may not match any valid address */
if (!src_match)
goto clean_up;
/* AUTH: After processing the parameters, make sure that we
* have all the required info to potentially do authentications.
*/
if (asoc->peer.auth_capable && (!asoc->peer.peer_random ||
!asoc->peer.peer_hmacs))
asoc->peer.auth_capable = 0;
/* In a non-backward compatible mode, if the peer claims
* support for ADD-IP but not AUTH, the ADD-IP spec states
* that we MUST ABORT the association. Section 6. The section
* also give us an option to silently ignore the packet, which
* is what we'll do here.
*/
if (!asoc->base.net->sctp.addip_noauth &&
(asoc->peer.asconf_capable && !asoc->peer.auth_capable)) {
asoc->peer.addip_disabled_mask |= (SCTP_PARAM_ADD_IP |
SCTP_PARAM_DEL_IP |
SCTP_PARAM_SET_PRIMARY);
asoc->peer.asconf_capable = 0;
goto clean_up;
}
/* Walk list of transports, removing transports in the UNKNOWN state. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
if (transport->state == SCTP_UNKNOWN) {
sctp_assoc_rm_peer(asoc, transport);
}
}
/* The fixed INIT headers are always in network byte
* order.
*/
asoc->peer.i.init_tag =
ntohl(peer_init->init_hdr.init_tag);
asoc->peer.i.a_rwnd =
ntohl(peer_init->init_hdr.a_rwnd);
asoc->peer.i.num_outbound_streams =
ntohs(peer_init->init_hdr.num_outbound_streams);
asoc->peer.i.num_inbound_streams =
ntohs(peer_init->init_hdr.num_inbound_streams);
asoc->peer.i.initial_tsn =
ntohl(peer_init->init_hdr.initial_tsn);
asoc->strreset_inseq = asoc->peer.i.initial_tsn;
/* Apply the upper bounds for output streams based on peer's
* number of inbound streams.
*/
if (asoc->c.sinit_num_ostreams >
ntohs(peer_init->init_hdr.num_inbound_streams)) {
asoc->c.sinit_num_ostreams =
ntohs(peer_init->init_hdr.num_inbound_streams);
}
if (asoc->c.sinit_max_instreams >
ntohs(peer_init->init_hdr.num_outbound_streams)) {
asoc->c.sinit_max_instreams =
ntohs(peer_init->init_hdr.num_outbound_streams);
}
/* Copy Initiation tag from INIT to VT_peer in cookie. */
asoc->c.peer_vtag = asoc->peer.i.init_tag;
/* Peer Rwnd : Current calculated value of the peer's rwnd. */
asoc->peer.rwnd = asoc->peer.i.a_rwnd;
/* RFC 2960 7.2.1 The initial value of ssthresh MAY be arbitrarily
* high (for example, implementations MAY use the size of the receiver
* advertised window).
*/
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
transport->ssthresh = asoc->peer.i.a_rwnd;
}
/* Set up the TSN tracking pieces. */
if (!sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, gfp))
goto clean_up;
/* RFC 2960 6.5 Stream Identifier and Stream Sequence Number
*
* The stream sequence number in all the streams shall start
* from 0 when the association is established. Also, when the
* stream sequence number reaches the value 65535 the next
* stream sequence number shall be set to 0.
*/
if (sctp_stream_init(&asoc->stream, asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams, gfp))
goto clean_up;
/* Update frag_point when stream_interleave may get changed. */
sctp_assoc_update_frag_point(asoc);
if (!asoc->temp && sctp_assoc_set_id(asoc, gfp))
goto clean_up;
/* ADDIP Section 4.1 ASCONF Chunk Procedures
*
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do the following:
* ...
* A2) A serial number should be assigned to the Chunk. The serial
* number should be a monotonically increasing number. All serial
* numbers are defined to be initialized at the start of the
* association to the same value as the Initial TSN.
*/
asoc->peer.addip_serial = asoc->peer.i.initial_tsn - 1;
return 1;
clean_up:
/* Release the transport structures. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
if (transport->state != SCTP_ACTIVE)
sctp_assoc_rm_peer(asoc, transport);
}
nomem:
return 0;
}
/* Update asoc with the option described in param.
*
* RFC2960 3.3.2.1 Optional/Variable Length Parameters in INIT
*
* asoc is the association to update.
* param is the variable length parameter to use for update.
* cid tells us if this is an INIT, INIT ACK or COOKIE ECHO.
* If the current packet is an INIT we want to minimize the amount of
* work we do. In particular, we should not build transport
* structures for the addresses.
*/
static int sctp_process_param(struct sctp_association *asoc,
union sctp_params param,
const union sctp_addr *peer_addr,
gfp_t gfp)
{
struct sctp_endpoint *ep = asoc->ep;
union sctp_addr_param *addr_param;
struct net *net = asoc->base.net;
struct sctp_transport *t;
enum sctp_scope scope;
union sctp_addr addr;
struct sctp_af *af;
int retval = 1, i;
u32 stale;
__u16 sat;
/* We maintain all INIT parameters in network byte order all the
* time. This allows us to not worry about whether the parameters
* came from a fresh INIT, and INIT ACK, or were stored in a cookie.
*/
switch (param.p->type) {
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 != asoc->base.sk->sk_family)
break;
goto do_addr_param;
case SCTP_PARAM_IPV4_ADDRESS:
/* v4 addresses are not allowed on v6-only socket */
if (ipv6_only_sock(asoc->base.sk))
break;
do_addr_param:
af = sctp_get_af_specific(param_type2af(param.p->type));
if (!af->from_addr_param(&addr, param.addr, htons(asoc->peer.port), 0))
break;
scope = sctp_scope(peer_addr);
if (sctp_in_scope(net, &addr, scope))
if (!sctp_assoc_add_peer(asoc, &addr, gfp, SCTP_UNCONFIRMED))
return 0;
break;
case SCTP_PARAM_COOKIE_PRESERVATIVE:
if (!net->sctp.cookie_preserve_enable)
break;
stale = ntohl(param.life->lifespan_increment);
/* Suggested Cookie Life span increment's unit is msec,
* (1/1000sec).
*/
asoc->cookie_life = ktime_add_ms(asoc->cookie_life, stale);
break;
case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
/* Turn off the default values first so we'll know which
* ones are really set by the peer.
*/
asoc->peer.ipv4_address = 0;
asoc->peer.ipv6_address = 0;
/* Assume that peer supports the address family
* by which it sends a packet.
*/
if (peer_addr->sa.sa_family == AF_INET6)
asoc->peer.ipv6_address = 1;
else if (peer_addr->sa.sa_family == AF_INET)
asoc->peer.ipv4_address = 1;
/* Cycle through address types; avoid divide by 0. */
sat = ntohs(param.p->length) - sizeof(struct sctp_paramhdr);
if (sat)
sat /= sizeof(__u16);
for (i = 0; i < sat; ++i) {
switch (param.sat->types[i]) {
case SCTP_PARAM_IPV4_ADDRESS:
asoc->peer.ipv4_address = 1;
break;
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 == asoc->base.sk->sk_family)
asoc->peer.ipv6_address = 1;
break;
default: /* Just ignore anything else. */
break;
}
}
break;
case SCTP_PARAM_STATE_COOKIE:
asoc->peer.cookie_len =
ntohs(param.p->length) - sizeof(struct sctp_paramhdr);
kfree(asoc->peer.cookie);
asoc->peer.cookie = kmemdup(param.cookie->body, asoc->peer.cookie_len, gfp);
if (!asoc->peer.cookie)
retval = 0;
break;
case SCTP_PARAM_HEARTBEAT_INFO:
/* Would be odd to receive, but it causes no problems. */
break;
case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
/* Rejected during verify stage. */
break;
case SCTP_PARAM_ECN_CAPABLE:
if (asoc->ep->ecn_enable) {
asoc->peer.ecn_capable = 1;
break;
}
/* Fall Through */
goto fall_through;
case SCTP_PARAM_ADAPTATION_LAYER_IND:
asoc->peer.adaptation_ind = ntohl(param.aind->adaptation_ind);
break;
case SCTP_PARAM_SET_PRIMARY:
if (!ep->asconf_enable)
goto fall_through;
addr_param = param.v + sizeof(struct sctp_addip_param);
af = sctp_get_af_specific(param_type2af(addr_param->p.type));
if (!af)
break;
if (!af->from_addr_param(&addr, addr_param,
htons(asoc->peer.port), 0))
break;
if (!af->addr_valid(&addr, NULL, NULL))
break;
t = sctp_assoc_lookup_paddr(asoc, &addr);
if (!t)
break;
sctp_assoc_set_primary(asoc, t);
break;
case SCTP_PARAM_SUPPORTED_EXT:
sctp_process_ext_param(asoc, param);
break;
case SCTP_PARAM_FWD_TSN_SUPPORT:
if (asoc->ep->prsctp_enable) {
asoc->peer.prsctp_capable = 1;
break;
}
/* Fall Through */
goto fall_through;
case SCTP_PARAM_RANDOM:
if (!ep->auth_enable)
goto fall_through;
/* Save peer's random parameter */
kfree(asoc->peer.peer_random);
asoc->peer.peer_random = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_random) {
retval = 0;
break;
}
break;
case SCTP_PARAM_HMAC_ALGO:
if (!ep->auth_enable)
goto fall_through;
/* Save peer's HMAC list */
kfree(asoc->peer.peer_hmacs);
asoc->peer.peer_hmacs = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_hmacs) {
retval = 0;
break;
}
/* Set the default HMAC the peer requested*/
sctp_auth_asoc_set_default_hmac(asoc, param.hmac_algo);
break;
case SCTP_PARAM_CHUNKS:
if (!ep->auth_enable)
goto fall_through;
kfree(asoc->peer.peer_chunks);
asoc->peer.peer_chunks = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_chunks)
retval = 0;
break;
fall_through:
default:
/* Any unrecognized parameters should have been caught
* and handled by sctp_verify_param() which should be
* called prior to this routine. Simply log the error
* here.
*/
pr_debug("%s: ignoring param:%d for association:%p.\n",
__func__, ntohs(param.p->type), asoc);
break;
}
return retval;
}
/* Select a new verification tag. */
__u32 sctp_generate_tag(const struct sctp_endpoint *ep)
{
/* I believe that this random number generator complies with RFC1750.
* A tag of 0 is reserved for special cases (e.g. INIT).
*/
__u32 x;
do {
get_random_bytes(&x, sizeof(__u32));
} while (x == 0);
return x;
}
/* Select an initial TSN to send during startup. */
__u32 sctp_generate_tsn(const struct sctp_endpoint *ep)
{
__u32 retval;
get_random_bytes(&retval, sizeof(__u32));
return retval;
}
/*
* ADDIP 3.1.1 Address Configuration Change Chunk (ASCONF)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0xC1 | Chunk Flags | Chunk Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Serial Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter #1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / .... /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter #N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Address Parameter and other parameter will not be wrapped in this function
*/
static struct sctp_chunk *sctp_make_asconf(struct sctp_association *asoc,
union sctp_addr *addr,
int vparam_len)
{
struct sctp_addiphdr asconf;
struct sctp_chunk *retval;
int length = sizeof(asconf) + vparam_len;
union sctp_addr_param addrparam;
int addrlen;
struct sctp_af *af = sctp_get_af_specific(addr->v4.sin_family);
addrlen = af->to_addr_param(addr, &addrparam);
if (!addrlen)
return NULL;
length += addrlen;
/* Create the chunk. */
retval = sctp_make_control(asoc, SCTP_CID_ASCONF, 0, length,
GFP_ATOMIC);
if (!retval)
return NULL;
asconf.serial = htonl(asoc->addip_serial++);
retval->subh.addip_hdr =
sctp_addto_chunk(retval, sizeof(asconf), &asconf);
retval->param_hdr.v =
sctp_addto_chunk(retval, addrlen, &addrparam);
return retval;
}
/* ADDIP
* 3.2.1 Add IP Address
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0xC001 | Length = Variable |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF-Request Correlation ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* 3.2.2 Delete IP Address
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0xC002 | Length = Variable |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF-Request Correlation ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc,
union sctp_addr *laddr,
struct sockaddr *addrs,
int addrcnt, __be16 flags)
{
union sctp_addr_param addr_param;
struct sctp_addip_param param;
int paramlen = sizeof(param);
struct sctp_chunk *retval;
int addr_param_len = 0;
union sctp_addr *addr;
int totallen = 0, i;
int del_pickup = 0;
struct sctp_af *af;
void *addr_buf;
/* Get total length of all the address parameters. */
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
addr_param_len = af->to_addr_param(addr, &addr_param);
totallen += paramlen;
totallen += addr_param_len;
addr_buf += af->sockaddr_len;
if (asoc->asconf_addr_del_pending && !del_pickup) {
/* reuse the parameter length from the same scope one */
totallen += paramlen;
totallen += addr_param_len;
del_pickup = 1;
pr_debug("%s: picked same-scope del_pending addr, "
"totallen for all addresses is %d\n",
__func__, totallen);
}
}
/* Create an asconf chunk with the required length. */
retval = sctp_make_asconf(asoc, laddr, totallen);
if (!retval)
return NULL;
/* Add the address parameters to the asconf chunk. */
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
addr_param_len = af->to_addr_param(addr, &addr_param);
param.param_hdr.type = flags;
param.param_hdr.length = htons(paramlen + addr_param_len);
param.crr_id = htonl(i);
sctp_addto_chunk(retval, paramlen, ¶m);
sctp_addto_chunk(retval, addr_param_len, &addr_param);
addr_buf += af->sockaddr_len;
}
if (flags == SCTP_PARAM_ADD_IP && del_pickup) {
addr = asoc->asconf_addr_del_pending;
af = sctp_get_af_specific(addr->v4.sin_family);
addr_param_len = af->to_addr_param(addr, &addr_param);
param.param_hdr.type = SCTP_PARAM_DEL_IP;
param.param_hdr.length = htons(paramlen + addr_param_len);
param.crr_id = htonl(i);
sctp_addto_chunk(retval, paramlen, ¶m);
sctp_addto_chunk(retval, addr_param_len, &addr_param);
}
return retval;
}
/* ADDIP
* 3.2.4 Set Primary IP Address
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type =0xC004 | Length = Variable |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF-Request Correlation ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address Parameter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Create an ASCONF chunk with Set Primary IP address parameter.
*/
struct sctp_chunk *sctp_make_asconf_set_prim(struct sctp_association *asoc,
union sctp_addr *addr)
{
struct sctp_af *af = sctp_get_af_specific(addr->v4.sin_family);
union sctp_addr_param addrparam;
struct sctp_addip_param param;
struct sctp_chunk *retval;
int len = sizeof(param);
int addrlen;
addrlen = af->to_addr_param(addr, &addrparam);
if (!addrlen)
return NULL;
len += addrlen;
/* Create the chunk and make asconf header. */
retval = sctp_make_asconf(asoc, addr, len);
if (!retval)
return NULL;
param.param_hdr.type = SCTP_PARAM_SET_PRIMARY;
param.param_hdr.length = htons(len);
param.crr_id = 0;
sctp_addto_chunk(retval, sizeof(param), ¶m);
sctp_addto_chunk(retval, addrlen, &addrparam);
return retval;
}
/* ADDIP 3.1.2 Address Configuration Acknowledgement Chunk (ASCONF-ACK)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 0x80 | Chunk Flags | Chunk Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Serial Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter Response#1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / .... /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ASCONF Parameter Response#N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Create an ASCONF_ACK chunk with enough space for the parameter responses.
*/
static struct sctp_chunk *sctp_make_asconf_ack(const struct sctp_association *asoc,
__u32 serial, int vparam_len)
{
struct sctp_addiphdr asconf;
struct sctp_chunk *retval;
int length = sizeof(asconf) + vparam_len;
/* Create the chunk. */
retval = sctp_make_control(asoc, SCTP_CID_ASCONF_ACK, 0, length,
GFP_ATOMIC);
if (!retval)
return NULL;
asconf.serial = htonl(serial);
retval->subh.addip_hdr =
sctp_addto_chunk(retval, sizeof(asconf), &asconf);
return retval;
}
/* Add response parameters to an ASCONF_ACK chunk. */
static void sctp_add_asconf_response(struct sctp_chunk *chunk, __be32 crr_id,
__be16 err_code,
struct sctp_addip_param *asconf_param)
{
struct sctp_addip_param ack_param;
struct sctp_errhdr err_param;
int asconf_param_len = 0;
int err_param_len = 0;
__be16 response_type;
if (SCTP_ERROR_NO_ERROR == err_code) {
response_type = SCTP_PARAM_SUCCESS_REPORT;
} else {
response_type = SCTP_PARAM_ERR_CAUSE;
err_param_len = sizeof(err_param);
if (asconf_param)
asconf_param_len =
ntohs(asconf_param->param_hdr.length);
}
/* Add Success Indication or Error Cause Indication parameter. */
ack_param.param_hdr.type = response_type;
ack_param.param_hdr.length = htons(sizeof(ack_param) +
err_param_len +
asconf_param_len);
ack_param.crr_id = crr_id;
sctp_addto_chunk(chunk, sizeof(ack_param), &ack_param);
if (SCTP_ERROR_NO_ERROR == err_code)
return;
/* Add Error Cause parameter. */
err_param.cause = err_code;
err_param.length = htons(err_param_len + asconf_param_len);
sctp_addto_chunk(chunk, err_param_len, &err_param);
/* Add the failed TLV copied from ASCONF chunk. */
if (asconf_param)
sctp_addto_chunk(chunk, asconf_param_len, asconf_param);
}
/* Process a asconf parameter. */
static __be16 sctp_process_asconf_param(struct sctp_association *asoc,
struct sctp_chunk *asconf,
struct sctp_addip_param *asconf_param)
{
union sctp_addr_param *addr_param;
struct sctp_transport *peer;
union sctp_addr addr;
struct sctp_af *af;
addr_param = (void *)asconf_param + sizeof(*asconf_param);
if (asconf_param->param_hdr.type != SCTP_PARAM_ADD_IP &&
asconf_param->param_hdr.type != SCTP_PARAM_DEL_IP &&
asconf_param->param_hdr.type != SCTP_PARAM_SET_PRIMARY)
return SCTP_ERROR_UNKNOWN_PARAM;
switch (addr_param->p.type) {
case SCTP_PARAM_IPV6_ADDRESS:
if (!asoc->peer.ipv6_address)
return SCTP_ERROR_DNS_FAILED;
break;
case SCTP_PARAM_IPV4_ADDRESS:
if (!asoc->peer.ipv4_address)
return SCTP_ERROR_DNS_FAILED;
break;
default:
return SCTP_ERROR_DNS_FAILED;
}
af = sctp_get_af_specific(param_type2af(addr_param->p.type));
if (unlikely(!af))
return SCTP_ERROR_DNS_FAILED;
if (!af->from_addr_param(&addr, addr_param, htons(asoc->peer.port), 0))
return SCTP_ERROR_DNS_FAILED;
/* ADDIP 4.2.1 This parameter MUST NOT contain a broadcast
* or multicast address.
* (note: wildcard is permitted and requires special handling so
* make sure we check for that)
*/
if (!af->is_any(&addr) && !af->addr_valid(&addr, NULL, asconf->skb))
return SCTP_ERROR_DNS_FAILED;
switch (asconf_param->param_hdr.type) {
case SCTP_PARAM_ADD_IP:
/* Section 4.2.1:
* If the address 0.0.0.0 or ::0 is provided, the source
* address of the packet MUST be added.
*/
if (af->is_any(&addr))
memcpy(&addr, &asconf->source, sizeof(addr));
if (security_sctp_bind_connect(asoc->ep->base.sk,
SCTP_PARAM_ADD_IP,
(struct sockaddr *)&addr,
af->sockaddr_len))
return SCTP_ERROR_REQ_REFUSED;
/* ADDIP 4.3 D9) If an endpoint receives an ADD IP address
* request and does not have the local resources to add this
* new address to the association, it MUST return an Error
* Cause TLV set to the new error code 'Operation Refused
* Due to Resource Shortage'.
*/
peer = sctp_assoc_add_peer(asoc, &addr, GFP_ATOMIC, SCTP_UNCONFIRMED);
if (!peer)
return SCTP_ERROR_RSRC_LOW;
/* Start the heartbeat timer. */
sctp_transport_reset_hb_timer(peer);
asoc->new_transport = peer;
break;
case SCTP_PARAM_DEL_IP:
/* ADDIP 4.3 D7) If a request is received to delete the
* last remaining IP address of a peer endpoint, the receiver
* MUST send an Error Cause TLV with the error cause set to the
* new error code 'Request to Delete Last Remaining IP Address'.
*/
if (asoc->peer.transport_count == 1)
return SCTP_ERROR_DEL_LAST_IP;
/* ADDIP 4.3 D8) If a request is received to delete an IP
* address which is also the source address of the IP packet
* which contained the ASCONF chunk, the receiver MUST reject
* this request. To reject the request the receiver MUST send
* an Error Cause TLV set to the new error code 'Request to
* Delete Source IP Address'
*/
if (sctp_cmp_addr_exact(&asconf->source, &addr))
return SCTP_ERROR_DEL_SRC_IP;
/* Section 4.2.2
* If the address 0.0.0.0 or ::0 is provided, all
* addresses of the peer except the source address of the
* packet MUST be deleted.
*/
if (af->is_any(&addr)) {
sctp_assoc_set_primary(asoc, asconf->transport);
sctp_assoc_del_nonprimary_peers(asoc,
asconf->transport);
return SCTP_ERROR_NO_ERROR;
}
/* If the address is not part of the association, the
* ASCONF-ACK with Error Cause Indication Parameter
* which including cause of Unresolvable Address should
* be sent.
*/
peer = sctp_assoc_lookup_paddr(asoc, &addr);
if (!peer)
return SCTP_ERROR_DNS_FAILED;
sctp_assoc_rm_peer(asoc, peer);
break;
case SCTP_PARAM_SET_PRIMARY:
/* ADDIP Section 4.2.4
* If the address 0.0.0.0 or ::0 is provided, the receiver
* MAY mark the source address of the packet as its
* primary.
*/
if (af->is_any(&addr))
memcpy(&addr, sctp_source(asconf), sizeof(addr));
if (security_sctp_bind_connect(asoc->ep->base.sk,
SCTP_PARAM_SET_PRIMARY,
(struct sockaddr *)&addr,
af->sockaddr_len))
return SCTP_ERROR_REQ_REFUSED;
peer = sctp_assoc_lookup_paddr(asoc, &addr);
if (!peer)
return SCTP_ERROR_DNS_FAILED;
sctp_assoc_set_primary(asoc, peer);
break;
}
return SCTP_ERROR_NO_ERROR;
}
/* Verify the ASCONF packet before we process it. */
bool sctp_verify_asconf(const struct sctp_association *asoc,
struct sctp_chunk *chunk, bool addr_param_needed,
struct sctp_paramhdr **errp)
{
struct sctp_addip_chunk *addip;
bool addr_param_seen = false;
union sctp_params param;
addip = (struct sctp_addip_chunk *)chunk->chunk_hdr;
sctp_walk_params(param, addip) {
size_t length = ntohs(param.p->length);
*errp = param.p;
switch (param.p->type) {
case SCTP_PARAM_ERR_CAUSE:
break;
case SCTP_PARAM_IPV4_ADDRESS:
if (length != sizeof(struct sctp_ipv4addr_param))
return false;
/* ensure there is only one addr param and it's in the
* beginning of addip_hdr params, or we reject it.
*/
if (param.v != (addip + 1))
return false;
addr_param_seen = true;
break;
case SCTP_PARAM_IPV6_ADDRESS:
if (length != sizeof(struct sctp_ipv6addr_param))
return false;
if (param.v != (addip + 1))
return false;
addr_param_seen = true;
break;
case SCTP_PARAM_ADD_IP:
case SCTP_PARAM_DEL_IP:
case SCTP_PARAM_SET_PRIMARY:
/* In ASCONF chunks, these need to be first. */
if (addr_param_needed && !addr_param_seen)
return false;
length = ntohs(param.addip->param_hdr.length);
if (length < sizeof(struct sctp_addip_param) +
sizeof(**errp))
return false;
break;
case SCTP_PARAM_SUCCESS_REPORT:
case SCTP_PARAM_ADAPTATION_LAYER_IND:
if (length != sizeof(struct sctp_addip_param))
return false;
break;
default:
/* This is unknown to us, reject! */
return false;
}
}
/* Remaining sanity checks. */
if (addr_param_needed && !addr_param_seen)
return false;
if (!addr_param_needed && addr_param_seen)
return false;
if (param.v != chunk->chunk_end)
return false;
return true;
}
/* Process an incoming ASCONF chunk with the next expected serial no. and
* return an ASCONF_ACK chunk to be sent in response.
*/
struct sctp_chunk *sctp_process_asconf(struct sctp_association *asoc,
struct sctp_chunk *asconf)
{
union sctp_addr_param *addr_param;
struct sctp_addip_chunk *addip;
struct sctp_chunk *asconf_ack;
bool all_param_pass = true;
struct sctp_addiphdr *hdr;
int length = 0, chunk_len;
union sctp_params param;
__be16 err_code;
__u32 serial;
addip = (struct sctp_addip_chunk *)asconf->chunk_hdr;
chunk_len = ntohs(asconf->chunk_hdr->length) -
sizeof(struct sctp_chunkhdr);
hdr = (struct sctp_addiphdr *)asconf->skb->data;
serial = ntohl(hdr->serial);
/* Skip the addiphdr and store a pointer to address parameter. */
length = sizeof(*hdr);
addr_param = (union sctp_addr_param *)(asconf->skb->data + length);
chunk_len -= length;
/* Skip the address parameter and store a pointer to the first
* asconf parameter.
*/
length = ntohs(addr_param->p.length);
chunk_len -= length;
/* create an ASCONF_ACK chunk.
* Based on the definitions of parameters, we know that the size of
* ASCONF_ACK parameters are less than or equal to the fourfold of ASCONF
* parameters.
*/
asconf_ack = sctp_make_asconf_ack(asoc, serial, chunk_len * 4);
if (!asconf_ack)
goto done;
/* Process the TLVs contained within the ASCONF chunk. */
sctp_walk_params(param, addip) {
/* Skip preceeding address parameters. */
if (param.p->type == SCTP_PARAM_IPV4_ADDRESS ||
param.p->type == SCTP_PARAM_IPV6_ADDRESS)
continue;
err_code = sctp_process_asconf_param(asoc, asconf,
param.addip);
/* ADDIP 4.1 A7)
* If an error response is received for a TLV parameter,
* all TLVs with no response before the failed TLV are
* considered successful if not reported. All TLVs after
* the failed response are considered unsuccessful unless
* a specific success indication is present for the parameter.
*/
if (err_code != SCTP_ERROR_NO_ERROR)
all_param_pass = false;
if (!all_param_pass)
sctp_add_asconf_response(asconf_ack, param.addip->crr_id,
err_code, param.addip);
/* ADDIP 4.3 D11) When an endpoint receiving an ASCONF to add
* an IP address sends an 'Out of Resource' in its response, it
* MUST also fail any subsequent add or delete requests bundled
* in the ASCONF.
*/
if (err_code == SCTP_ERROR_RSRC_LOW)
goto done;
}
done:
asoc->peer.addip_serial++;
/* If we are sending a new ASCONF_ACK hold a reference to it in assoc
* after freeing the reference to old asconf ack if any.
*/
if (asconf_ack) {
sctp_chunk_hold(asconf_ack);
list_add_tail(&asconf_ack->transmitted_list,
&asoc->asconf_ack_list);
}
return asconf_ack;
}
/* Process a asconf parameter that is successfully acked. */
static void sctp_asconf_param_success(struct sctp_association *asoc,
struct sctp_addip_param *asconf_param)
{
struct sctp_bind_addr *bp = &asoc->base.bind_addr;
union sctp_addr_param *addr_param;
struct sctp_sockaddr_entry *saddr;
struct sctp_transport *transport;
union sctp_addr addr;
struct sctp_af *af;
addr_param = (void *)asconf_param + sizeof(*asconf_param);
/* We have checked the packet before, so we do not check again. */
af = sctp_get_af_specific(param_type2af(addr_param->p.type));
if (!af->from_addr_param(&addr, addr_param, htons(bp->port), 0))
return;
switch (asconf_param->param_hdr.type) {
case SCTP_PARAM_ADD_IP:
/* This is always done in BH context with a socket lock
* held, so the list can not change.
*/
local_bh_disable();
list_for_each_entry(saddr, &bp->address_list, list) {
if (sctp_cmp_addr_exact(&saddr->a, &addr))
saddr->state = SCTP_ADDR_SRC;
}
local_bh_enable();
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
sctp_transport_dst_release(transport);
}
break;
case SCTP_PARAM_DEL_IP:
local_bh_disable();
sctp_del_bind_addr(bp, &addr);
if (asoc->asconf_addr_del_pending != NULL &&
sctp_cmp_addr_exact(asoc->asconf_addr_del_pending, &addr)) {
kfree(asoc->asconf_addr_del_pending);
asoc->asconf_addr_del_pending = NULL;
}
local_bh_enable();
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
sctp_transport_dst_release(transport);
}
break;
default:
break;
}
}
/* Get the corresponding ASCONF response error code from the ASCONF_ACK chunk
* for the given asconf parameter. If there is no response for this parameter,
* return the error code based on the third argument 'no_err'.
* ADDIP 4.1
* A7) If an error response is received for a TLV parameter, all TLVs with no
* response before the failed TLV are considered successful if not reported.
* All TLVs after the failed response are considered unsuccessful unless a
* specific success indication is present for the parameter.
*/
static __be16 sctp_get_asconf_response(struct sctp_chunk *asconf_ack,
struct sctp_addip_param *asconf_param,
int no_err)
{
struct sctp_addip_param *asconf_ack_param;
struct sctp_errhdr *err_param;
int asconf_ack_len;
__be16 err_code;
int length;
if (no_err)
err_code = SCTP_ERROR_NO_ERROR;
else
err_code = SCTP_ERROR_REQ_REFUSED;
asconf_ack_len = ntohs(asconf_ack->chunk_hdr->length) -
sizeof(struct sctp_chunkhdr);
/* Skip the addiphdr from the asconf_ack chunk and store a pointer to
* the first asconf_ack parameter.
*/
length = sizeof(struct sctp_addiphdr);
asconf_ack_param = (struct sctp_addip_param *)(asconf_ack->skb->data +
length);
asconf_ack_len -= length;
while (asconf_ack_len > 0) {
if (asconf_ack_param->crr_id == asconf_param->crr_id) {
switch (asconf_ack_param->param_hdr.type) {
case SCTP_PARAM_SUCCESS_REPORT:
return SCTP_ERROR_NO_ERROR;
case SCTP_PARAM_ERR_CAUSE:
length = sizeof(*asconf_ack_param);
err_param = (void *)asconf_ack_param + length;
asconf_ack_len -= length;
if (asconf_ack_len > 0)
return err_param->cause;
else
return SCTP_ERROR_INV_PARAM;
break;
default:
return SCTP_ERROR_INV_PARAM;
}
}
length = ntohs(asconf_ack_param->param_hdr.length);
asconf_ack_param = (void *)asconf_ack_param + length;
asconf_ack_len -= length;
}
return err_code;
}
/* Process an incoming ASCONF_ACK chunk against the cached last ASCONF chunk. */
int sctp_process_asconf_ack(struct sctp_association *asoc,
struct sctp_chunk *asconf_ack)
{
struct sctp_chunk *asconf = asoc->addip_last_asconf;
struct sctp_addip_param *asconf_param;
__be16 err_code = SCTP_ERROR_NO_ERROR;
union sctp_addr_param *addr_param;
int asconf_len = asconf->skb->len;
int all_param_pass = 0;
int length = 0;
int no_err = 1;
int retval = 0;
/* Skip the chunkhdr and addiphdr from the last asconf sent and store
* a pointer to address parameter.
*/
length = sizeof(struct sctp_addip_chunk);
addr_param = (union sctp_addr_param *)(asconf->skb->data + length);
asconf_len -= length;
/* Skip the address parameter in the last asconf sent and store a
* pointer to the first asconf parameter.
*/
length = ntohs(addr_param->p.length);
asconf_param = (void *)addr_param + length;
asconf_len -= length;
/* ADDIP 4.1
* A8) If there is no response(s) to specific TLV parameter(s), and no
* failures are indicated, then all request(s) are considered
* successful.
*/
if (asconf_ack->skb->len == sizeof(struct sctp_addiphdr))
all_param_pass = 1;
/* Process the TLVs contained in the last sent ASCONF chunk. */
while (asconf_len > 0) {
if (all_param_pass)
err_code = SCTP_ERROR_NO_ERROR;
else {
err_code = sctp_get_asconf_response(asconf_ack,
asconf_param,
no_err);
if (no_err && (SCTP_ERROR_NO_ERROR != err_code))
no_err = 0;
}
switch (err_code) {
case SCTP_ERROR_NO_ERROR:
sctp_asconf_param_success(asoc, asconf_param);
break;
case SCTP_ERROR_RSRC_LOW:
retval = 1;
break;
case SCTP_ERROR_UNKNOWN_PARAM:
/* Disable sending this type of asconf parameter in
* future.
*/
asoc->peer.addip_disabled_mask |=
asconf_param->param_hdr.type;
break;
case SCTP_ERROR_REQ_REFUSED:
case SCTP_ERROR_DEL_LAST_IP:
case SCTP_ERROR_DEL_SRC_IP:
default:
break;
}
/* Skip the processed asconf parameter and move to the next
* one.
*/
length = ntohs(asconf_param->param_hdr.length);
asconf_param = (void *)asconf_param + length;
asconf_len -= length;
}
if (no_err && asoc->src_out_of_asoc_ok) {
asoc->src_out_of_asoc_ok = 0;
sctp_transport_immediate_rtx(asoc->peer.primary_path);
}
/* Free the cached last sent asconf chunk. */
list_del_init(&asconf->transmitted_list);
sctp_chunk_free(asconf);
asoc->addip_last_asconf = NULL;
return retval;
}
/* Make a FWD TSN chunk. */
struct sctp_chunk *sctp_make_fwdtsn(const struct sctp_association *asoc,
__u32 new_cum_tsn, size_t nstreams,
struct sctp_fwdtsn_skip *skiplist)
{
struct sctp_chunk *retval = NULL;
struct sctp_fwdtsn_hdr ftsn_hdr;
struct sctp_fwdtsn_skip skip;
size_t hint;
int i;
hint = (nstreams + 1) * sizeof(__u32);
retval = sctp_make_control(asoc, SCTP_CID_FWD_TSN, 0, hint, GFP_ATOMIC);
if (!retval)
return NULL;
ftsn_hdr.new_cum_tsn = htonl(new_cum_tsn);
retval->subh.fwdtsn_hdr =
sctp_addto_chunk(retval, sizeof(ftsn_hdr), &ftsn_hdr);
for (i = 0; i < nstreams; i++) {
skip.stream = skiplist[i].stream;
skip.ssn = skiplist[i].ssn;
sctp_addto_chunk(retval, sizeof(skip), &skip);
}
return retval;
}
struct sctp_chunk *sctp_make_ifwdtsn(const struct sctp_association *asoc,
__u32 new_cum_tsn, size_t nstreams,
struct sctp_ifwdtsn_skip *skiplist)
{
struct sctp_chunk *retval = NULL;
struct sctp_ifwdtsn_hdr ftsn_hdr;
size_t hint;
hint = (nstreams + 1) * sizeof(__u32);
retval = sctp_make_control(asoc, SCTP_CID_I_FWD_TSN, 0, hint,
GFP_ATOMIC);
if (!retval)
return NULL;
ftsn_hdr.new_cum_tsn = htonl(new_cum_tsn);
retval->subh.ifwdtsn_hdr =
sctp_addto_chunk(retval, sizeof(ftsn_hdr), &ftsn_hdr);
sctp_addto_chunk(retval, nstreams * sizeof(skiplist[0]), skiplist);
return retval;
}
/* RE-CONFIG 3.1 (RE-CONFIG chunk)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type = 130 | Chunk Flags | Chunk Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / Re-configuration Parameter /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* \ \
* / Re-configuration Parameter (optional) /
* \ \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
static struct sctp_chunk *sctp_make_reconf(const struct sctp_association *asoc,
int length)
{
struct sctp_reconf_chunk *reconf;
struct sctp_chunk *retval;
retval = sctp_make_control(asoc, SCTP_CID_RECONF, 0, length,
GFP_ATOMIC);
if (!retval)
return NULL;
reconf = (struct sctp_reconf_chunk *)retval->chunk_hdr;
retval->param_hdr.v = (u8 *)(reconf + 1);
return retval;
}
/* RE-CONFIG 4.1 (STREAM OUT RESET)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Parameter Type = 13 | Parameter Length = 16 + 2 * N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Re-configuration Request Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Re-configuration Response Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Sender's Last Assigned TSN |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Stream Number 1 (optional) | Stream Number 2 (optional) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* / ...... /
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Stream Number N-1 (optional) | Stream Number N (optional) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* RE-CONFIG 4.2 (STREAM IN RESET)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Parameter Type = 14 | Parameter Length = 8 + 2 * N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Re-configuration Request Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Stream Number 1 (optional) | Stream Number 2 (optional) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* / ...... /
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Stream Number N-1 (optional) | Stream Number N (optional) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct sctp_chunk *sctp_make_strreset_req(
const struct sctp_association *asoc,
__u16 stream_num, __be16 *stream_list,
bool out, bool in)
{
__u16 stream_len = stream_num * sizeof(__u16);
struct sctp_strreset_outreq outreq;
struct sctp_strreset_inreq inreq;
struct sctp_chunk *retval;
__u16 outlen, inlen;
outlen = (sizeof(outreq) + stream_len) * out;
inlen = (sizeof(inreq) + stream_len) * in;
retval = sctp_make_reconf(asoc, SCTP_PAD4(outlen) + SCTP_PAD4(inlen));
if (!retval)
return NULL;
if (outlen) {
outreq.param_hdr.type = SCTP_PARAM_RESET_OUT_REQUEST;
outreq.param_hdr.length = htons(outlen);
outreq.request_seq = htonl(asoc->strreset_outseq);
outreq.response_seq = htonl(asoc->strreset_inseq - 1);
outreq.send_reset_at_tsn = htonl(asoc->next_tsn - 1);
sctp_addto_chunk(retval, sizeof(outreq), &outreq);
if (stream_len)
sctp_addto_chunk(retval, stream_len, stream_list);
}
if (inlen) {
inreq.param_hdr.type = SCTP_PARAM_RESET_IN_REQUEST;
inreq.param_hdr.length = htons(inlen);
inreq.request_seq = htonl(asoc->strreset_outseq + out);
sctp_addto_chunk(retval, sizeof(inreq), &inreq);
if (stream_len)
sctp_addto_chunk(retval, stream_len, stream_list);
}
return retval;
}
/* RE-CONFIG 4.3 (SSN/TSN RESET ALL)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Parameter Type = 15 | Parameter Length = 8 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Re-configuration Request Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct sctp_chunk *sctp_make_strreset_tsnreq(
const struct sctp_association *asoc)
{
struct sctp_strreset_tsnreq tsnreq;
__u16 length = sizeof(tsnreq);
struct sctp_chunk *retval;
retval = sctp_make_reconf(asoc, length);
if (!retval)
return NULL;
tsnreq.param_hdr.type = SCTP_PARAM_RESET_TSN_REQUEST;
tsnreq.param_hdr.length = htons(length);
tsnreq.request_seq = htonl(asoc->strreset_outseq);
sctp_addto_chunk(retval, sizeof(tsnreq), &tsnreq);
return retval;
}
/* RE-CONFIG 4.5/4.6 (ADD STREAM)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Parameter Type = 17 | Parameter Length = 12 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Re-configuration Request Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of new streams | Reserved |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct sctp_chunk *sctp_make_strreset_addstrm(
const struct sctp_association *asoc,
__u16 out, __u16 in)
{
struct sctp_strreset_addstrm addstrm;
__u16 size = sizeof(addstrm);
struct sctp_chunk *retval;
retval = sctp_make_reconf(asoc, (!!out + !!in) * size);
if (!retval)
return NULL;
if (out) {
addstrm.param_hdr.type = SCTP_PARAM_RESET_ADD_OUT_STREAMS;
addstrm.param_hdr.length = htons(size);
addstrm.number_of_streams = htons(out);
addstrm.request_seq = htonl(asoc->strreset_outseq);
addstrm.reserved = 0;
sctp_addto_chunk(retval, size, &addstrm);
}
if (in) {
addstrm.param_hdr.type = SCTP_PARAM_RESET_ADD_IN_STREAMS;
addstrm.param_hdr.length = htons(size);
addstrm.number_of_streams = htons(in);
addstrm.request_seq = htonl(asoc->strreset_outseq + !!out);
addstrm.reserved = 0;
sctp_addto_chunk(retval, size, &addstrm);
}
return retval;
}
/* RE-CONFIG 4.4 (RESP)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Parameter Type = 16 | Parameter Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Re-configuration Response Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Result |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct sctp_chunk *sctp_make_strreset_resp(const struct sctp_association *asoc,
__u32 result, __u32 sn)
{
struct sctp_strreset_resp resp;
__u16 length = sizeof(resp);
struct sctp_chunk *retval;
retval = sctp_make_reconf(asoc, length);
if (!retval)
return NULL;
resp.param_hdr.type = SCTP_PARAM_RESET_RESPONSE;
resp.param_hdr.length = htons(length);
resp.response_seq = htonl(sn);
resp.result = htonl(result);
sctp_addto_chunk(retval, sizeof(resp), &resp);
return retval;
}
/* RE-CONFIG 4.4 OPTIONAL (TSNRESP)
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Parameter Type = 16 | Parameter Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Re-configuration Response Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Result |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Sender's Next TSN (optional) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Receiver's Next TSN (optional) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct sctp_chunk *sctp_make_strreset_tsnresp(struct sctp_association *asoc,
__u32 result, __u32 sn,
__u32 sender_tsn,
__u32 receiver_tsn)
{
struct sctp_strreset_resptsn tsnresp;
__u16 length = sizeof(tsnresp);
struct sctp_chunk *retval;
retval = sctp_make_reconf(asoc, length);
if (!retval)
return NULL;
tsnresp.param_hdr.type = SCTP_PARAM_RESET_RESPONSE;
tsnresp.param_hdr.length = htons(length);
tsnresp.response_seq = htonl(sn);
tsnresp.result = htonl(result);
tsnresp.senders_next_tsn = htonl(sender_tsn);
tsnresp.receivers_next_tsn = htonl(receiver_tsn);
sctp_addto_chunk(retval, sizeof(tsnresp), &tsnresp);
return retval;
}
bool sctp_verify_reconf(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
struct sctp_paramhdr **errp)
{
struct sctp_reconf_chunk *hdr;
union sctp_params param;
__be16 last = 0;
__u16 cnt = 0;
hdr = (struct sctp_reconf_chunk *)chunk->chunk_hdr;
sctp_walk_params(param, hdr) {
__u16 length = ntohs(param.p->length);
*errp = param.p;
if (cnt++ > 2)
return false;
switch (param.p->type) {
case SCTP_PARAM_RESET_OUT_REQUEST:
if (length < sizeof(struct sctp_strreset_outreq) ||
(last && last != SCTP_PARAM_RESET_RESPONSE &&
last != SCTP_PARAM_RESET_IN_REQUEST))
return false;
break;
case SCTP_PARAM_RESET_IN_REQUEST:
if (length < sizeof(struct sctp_strreset_inreq) ||
(last && last != SCTP_PARAM_RESET_OUT_REQUEST))
return false;
break;
case SCTP_PARAM_RESET_RESPONSE:
if ((length != sizeof(struct sctp_strreset_resp) &&
length != sizeof(struct sctp_strreset_resptsn)) ||
(last && last != SCTP_PARAM_RESET_RESPONSE &&
last != SCTP_PARAM_RESET_OUT_REQUEST))
return false;
break;
case SCTP_PARAM_RESET_TSN_REQUEST:
if (length !=
sizeof(struct sctp_strreset_tsnreq) || last)
return false;
break;
case SCTP_PARAM_RESET_ADD_IN_STREAMS:
if (length != sizeof(struct sctp_strreset_addstrm) ||
(last && last != SCTP_PARAM_RESET_ADD_OUT_STREAMS))
return false;
break;
case SCTP_PARAM_RESET_ADD_OUT_STREAMS:
if (length != sizeof(struct sctp_strreset_addstrm) ||
(last && last != SCTP_PARAM_RESET_ADD_IN_STREAMS))
return false;
break;
default:
return false;
}
last = param.p->type;
}
return true;
}
| linux-master | net/sctp/sm_make_chunk.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2002, 2004
* Copyright (c) 2001 Nokia, Inc.
* Copyright (c) 2001 La Monte H.P. Yarroll
* Copyright (c) 2002-2003 Intel Corp.
*
* This file is part of the SCTP kernel implementation
*
* SCTP over IPv6.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Le Yanqun <[email protected]>
* Hui Huang <[email protected]>
* La Monte H.P. Yarroll <[email protected]>
* Sridhar Samudrala <[email protected]>
* Jon Grimm <[email protected]>
* Ardelle Fan <[email protected]>
*
* Based on:
* linux/net/ipv6/tcp_ipv6.c
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/netdevice.h>
#include <linux/init.h>
#include <linux/ipsec.h>
#include <linux/slab.h>
#include <linux/ipv6.h>
#include <linux/icmpv6.h>
#include <linux/random.h>
#include <linux/seq_file.h>
#include <net/protocol.h>
#include <net/ndisc.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/transp_v6.h>
#include <net/addrconf.h>
#include <net/ip6_route.h>
#include <net/inet_common.h>
#include <net/inet_ecn.h>
#include <net/sctp/sctp.h>
#include <net/udp_tunnel.h>
#include <linux/uaccess.h>
static inline int sctp_v6_addr_match_len(union sctp_addr *s1,
union sctp_addr *s2);
static void sctp_v6_to_addr(union sctp_addr *addr, struct in6_addr *saddr,
__be16 port);
static int sctp_v6_cmp_addr(const union sctp_addr *addr1,
const union sctp_addr *addr2);
/* Event handler for inet6 address addition/deletion events.
* The sctp_local_addr_list needs to be protocted by a spin lock since
* multiple notifiers (say IPv4 and IPv6) may be running at the same
* time and thus corrupt the list.
* The reader side is protected with RCU.
*/
static int sctp_inet6addr_event(struct notifier_block *this, unsigned long ev,
void *ptr)
{
struct inet6_ifaddr *ifa = (struct inet6_ifaddr *)ptr;
struct sctp_sockaddr_entry *addr = NULL;
struct sctp_sockaddr_entry *temp;
struct net *net = dev_net(ifa->idev->dev);
int found = 0;
switch (ev) {
case NETDEV_UP:
addr = kzalloc(sizeof(*addr), GFP_ATOMIC);
if (addr) {
addr->a.v6.sin6_family = AF_INET6;
addr->a.v6.sin6_addr = ifa->addr;
addr->a.v6.sin6_scope_id = ifa->idev->dev->ifindex;
addr->valid = 1;
spin_lock_bh(&net->sctp.local_addr_lock);
list_add_tail_rcu(&addr->list, &net->sctp.local_addr_list);
sctp_addr_wq_mgmt(net, addr, SCTP_ADDR_NEW);
spin_unlock_bh(&net->sctp.local_addr_lock);
}
break;
case NETDEV_DOWN:
spin_lock_bh(&net->sctp.local_addr_lock);
list_for_each_entry_safe(addr, temp,
&net->sctp.local_addr_list, list) {
if (addr->a.sa.sa_family == AF_INET6 &&
ipv6_addr_equal(&addr->a.v6.sin6_addr,
&ifa->addr) &&
addr->a.v6.sin6_scope_id == ifa->idev->dev->ifindex) {
sctp_addr_wq_mgmt(net, addr, SCTP_ADDR_DEL);
found = 1;
addr->valid = 0;
list_del_rcu(&addr->list);
break;
}
}
spin_unlock_bh(&net->sctp.local_addr_lock);
if (found)
kfree_rcu(addr, rcu);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block sctp_inet6addr_notifier = {
.notifier_call = sctp_inet6addr_event,
};
static void sctp_v6_err_handle(struct sctp_transport *t, struct sk_buff *skb,
__u8 type, __u8 code, __u32 info)
{
struct sctp_association *asoc = t->asoc;
struct sock *sk = asoc->base.sk;
struct ipv6_pinfo *np;
int err = 0;
switch (type) {
case ICMPV6_PKT_TOOBIG:
if (ip6_sk_accept_pmtu(sk))
sctp_icmp_frag_needed(sk, asoc, t, info);
return;
case ICMPV6_PARAMPROB:
if (ICMPV6_UNK_NEXTHDR == code) {
sctp_icmp_proto_unreachable(sk, asoc, t);
return;
}
break;
case NDISC_REDIRECT:
sctp_icmp_redirect(sk, t, skb);
return;
default:
break;
}
np = inet6_sk(sk);
icmpv6_err_convert(type, code, &err);
if (!sock_owned_by_user(sk) && np->recverr) {
sk->sk_err = err;
sk_error_report(sk);
} else {
WRITE_ONCE(sk->sk_err_soft, err);
}
}
/* ICMP error handler. */
static int sctp_v6_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
struct net *net = dev_net(skb->dev);
struct sctp_transport *transport;
struct sctp_association *asoc;
__u16 saveip, savesctp;
struct sock *sk;
/* Fix up skb to look at the embedded net header. */
saveip = skb->network_header;
savesctp = skb->transport_header;
skb_reset_network_header(skb);
skb_set_transport_header(skb, offset);
sk = sctp_err_lookup(net, AF_INET6, skb, sctp_hdr(skb), &asoc, &transport);
/* Put back, the original pointers. */
skb->network_header = saveip;
skb->transport_header = savesctp;
if (!sk) {
__ICMP6_INC_STATS(net, __in6_dev_get(skb->dev), ICMP6_MIB_INERRORS);
return -ENOENT;
}
sctp_v6_err_handle(transport, skb, type, code, ntohl(info));
sctp_err_finish(sk, transport);
return 0;
}
int sctp_udp_v6_err(struct sock *sk, struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
struct sctp_association *asoc;
struct sctp_transport *t;
struct icmp6hdr *hdr;
__u32 info = 0;
skb->transport_header += sizeof(struct udphdr);
sk = sctp_err_lookup(net, AF_INET6, skb, sctp_hdr(skb), &asoc, &t);
if (!sk) {
__ICMP6_INC_STATS(net, __in6_dev_get(skb->dev), ICMP6_MIB_INERRORS);
return -ENOENT;
}
skb->transport_header -= sizeof(struct udphdr);
hdr = (struct icmp6hdr *)(skb_network_header(skb) - sizeof(struct icmp6hdr));
if (hdr->icmp6_type == NDISC_REDIRECT) {
/* can't be handled without outer ip6hdr known, leave it to udpv6_err */
sctp_err_finish(sk, t);
return 0;
}
if (hdr->icmp6_type == ICMPV6_PKT_TOOBIG)
info = ntohl(hdr->icmp6_mtu);
sctp_v6_err_handle(t, skb, hdr->icmp6_type, hdr->icmp6_code, info);
sctp_err_finish(sk, t);
return 1;
}
static int sctp_v6_xmit(struct sk_buff *skb, struct sctp_transport *t)
{
struct dst_entry *dst = dst_clone(t->dst);
struct flowi6 *fl6 = &t->fl.u.ip6;
struct sock *sk = skb->sk;
struct ipv6_pinfo *np = inet6_sk(sk);
__u8 tclass = np->tclass;
__be32 label;
pr_debug("%s: skb:%p, len:%d, src:%pI6 dst:%pI6\n", __func__, skb,
skb->len, &fl6->saddr, &fl6->daddr);
if (t->dscp & SCTP_DSCP_SET_MASK)
tclass = t->dscp & SCTP_DSCP_VAL_MASK;
if (INET_ECN_is_capable(tclass))
IP6_ECN_flow_xmit(sk, fl6->flowlabel);
if (!(t->param_flags & SPP_PMTUD_ENABLE))
skb->ignore_df = 1;
SCTP_INC_STATS(sock_net(sk), SCTP_MIB_OUTSCTPPACKS);
if (!t->encap_port || !sctp_sk(sk)->udp_port) {
int res;
skb_dst_set(skb, dst);
rcu_read_lock();
res = ip6_xmit(sk, skb, fl6, sk->sk_mark,
rcu_dereference(np->opt),
tclass, sk->sk_priority);
rcu_read_unlock();
return res;
}
if (skb_is_gso(skb))
skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_TUNNEL_CSUM;
skb->encapsulation = 1;
skb_reset_inner_mac_header(skb);
skb_reset_inner_transport_header(skb);
skb_set_inner_ipproto(skb, IPPROTO_SCTP);
label = ip6_make_flowlabel(sock_net(sk), skb, fl6->flowlabel, true, fl6);
return udp_tunnel6_xmit_skb(dst, sk, skb, NULL, &fl6->saddr,
&fl6->daddr, tclass, ip6_dst_hoplimit(dst),
label, sctp_sk(sk)->udp_port, t->encap_port, false);
}
/* Returns the dst cache entry for the given source and destination ip
* addresses.
*/
static void sctp_v6_get_dst(struct sctp_transport *t, union sctp_addr *saddr,
struct flowi *fl, struct sock *sk)
{
struct sctp_association *asoc = t->asoc;
struct dst_entry *dst = NULL;
struct flowi _fl;
struct flowi6 *fl6 = &_fl.u.ip6;
struct sctp_bind_addr *bp;
struct ipv6_pinfo *np = inet6_sk(sk);
struct sctp_sockaddr_entry *laddr;
union sctp_addr *daddr = &t->ipaddr;
union sctp_addr dst_saddr;
struct in6_addr *final_p, final;
enum sctp_scope scope;
__u8 matchlen = 0;
memset(&_fl, 0, sizeof(_fl));
fl6->daddr = daddr->v6.sin6_addr;
fl6->fl6_dport = daddr->v6.sin6_port;
fl6->flowi6_proto = IPPROTO_SCTP;
if (ipv6_addr_type(&daddr->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL)
fl6->flowi6_oif = daddr->v6.sin6_scope_id;
else if (asoc)
fl6->flowi6_oif = asoc->base.sk->sk_bound_dev_if;
if (t->flowlabel & SCTP_FLOWLABEL_SET_MASK)
fl6->flowlabel = htonl(t->flowlabel & SCTP_FLOWLABEL_VAL_MASK);
if (np->sndflow && (fl6->flowlabel & IPV6_FLOWLABEL_MASK)) {
struct ip6_flowlabel *flowlabel;
flowlabel = fl6_sock_lookup(sk, fl6->flowlabel);
if (IS_ERR(flowlabel))
goto out;
fl6_sock_release(flowlabel);
}
pr_debug("%s: dst=%pI6 ", __func__, &fl6->daddr);
if (asoc)
fl6->fl6_sport = htons(asoc->base.bind_addr.port);
if (saddr) {
fl6->saddr = saddr->v6.sin6_addr;
if (!fl6->fl6_sport)
fl6->fl6_sport = saddr->v6.sin6_port;
pr_debug("src=%pI6 - ", &fl6->saddr);
}
rcu_read_lock();
final_p = fl6_update_dst(fl6, rcu_dereference(np->opt), &final);
rcu_read_unlock();
dst = ip6_dst_lookup_flow(sock_net(sk), sk, fl6, final_p);
if (!asoc || saddr) {
t->dst = dst;
memcpy(fl, &_fl, sizeof(_fl));
goto out;
}
bp = &asoc->base.bind_addr;
scope = sctp_scope(daddr);
/* ip6_dst_lookup has filled in the fl6->saddr for us. Check
* to see if we can use it.
*/
if (!IS_ERR(dst)) {
/* Walk through the bind address list and look for a bind
* address that matches the source address of the returned dst.
*/
sctp_v6_to_addr(&dst_saddr, &fl6->saddr, htons(bp->port));
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
if (!laddr->valid || laddr->state == SCTP_ADDR_DEL ||
(laddr->state != SCTP_ADDR_SRC &&
!asoc->src_out_of_asoc_ok))
continue;
/* Do not compare against v4 addrs */
if ((laddr->a.sa.sa_family == AF_INET6) &&
(sctp_v6_cmp_addr(&dst_saddr, &laddr->a))) {
rcu_read_unlock();
t->dst = dst;
memcpy(fl, &_fl, sizeof(_fl));
goto out;
}
}
rcu_read_unlock();
/* None of the bound addresses match the source address of the
* dst. So release it.
*/
dst_release(dst);
dst = NULL;
}
/* Walk through the bind address list and try to get the
* best source address for a given destination.
*/
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
struct dst_entry *bdst;
__u8 bmatchlen;
if (!laddr->valid ||
laddr->state != SCTP_ADDR_SRC ||
laddr->a.sa.sa_family != AF_INET6 ||
scope > sctp_scope(&laddr->a))
continue;
fl6->saddr = laddr->a.v6.sin6_addr;
fl6->fl6_sport = laddr->a.v6.sin6_port;
final_p = fl6_update_dst(fl6, rcu_dereference(np->opt), &final);
bdst = ip6_dst_lookup_flow(sock_net(sk), sk, fl6, final_p);
if (IS_ERR(bdst))
continue;
if (ipv6_chk_addr(dev_net(bdst->dev),
&laddr->a.v6.sin6_addr, bdst->dev, 1)) {
if (!IS_ERR_OR_NULL(dst))
dst_release(dst);
dst = bdst;
t->dst = dst;
memcpy(fl, &_fl, sizeof(_fl));
break;
}
bmatchlen = sctp_v6_addr_match_len(daddr, &laddr->a);
if (matchlen > bmatchlen) {
dst_release(bdst);
continue;
}
if (!IS_ERR_OR_NULL(dst))
dst_release(dst);
dst = bdst;
matchlen = bmatchlen;
t->dst = dst;
memcpy(fl, &_fl, sizeof(_fl));
}
rcu_read_unlock();
out:
if (!IS_ERR_OR_NULL(dst)) {
struct rt6_info *rt;
rt = (struct rt6_info *)dst;
t->dst_cookie = rt6_get_cookie(rt);
pr_debug("rt6_dst:%pI6/%d rt6_src:%pI6\n",
&rt->rt6i_dst.addr, rt->rt6i_dst.plen,
&fl->u.ip6.saddr);
} else {
t->dst = NULL;
pr_debug("no route\n");
}
}
/* Returns the number of consecutive initial bits that match in the 2 ipv6
* addresses.
*/
static inline int sctp_v6_addr_match_len(union sctp_addr *s1,
union sctp_addr *s2)
{
return ipv6_addr_diff(&s1->v6.sin6_addr, &s2->v6.sin6_addr);
}
/* Fills in the source address(saddr) based on the destination address(daddr)
* and asoc's bind address list.
*/
static void sctp_v6_get_saddr(struct sctp_sock *sk,
struct sctp_transport *t,
struct flowi *fl)
{
struct flowi6 *fl6 = &fl->u.ip6;
union sctp_addr *saddr = &t->saddr;
pr_debug("%s: asoc:%p dst:%p\n", __func__, t->asoc, t->dst);
if (t->dst) {
saddr->v6.sin6_family = AF_INET6;
saddr->v6.sin6_addr = fl6->saddr;
}
}
/* Make a copy of all potential local addresses. */
static void sctp_v6_copy_addrlist(struct list_head *addrlist,
struct net_device *dev)
{
struct inet6_dev *in6_dev;
struct inet6_ifaddr *ifp;
struct sctp_sockaddr_entry *addr;
rcu_read_lock();
if ((in6_dev = __in6_dev_get(dev)) == NULL) {
rcu_read_unlock();
return;
}
read_lock_bh(&in6_dev->lock);
list_for_each_entry(ifp, &in6_dev->addr_list, if_list) {
/* Add the address to the local list. */
addr = kzalloc(sizeof(*addr), GFP_ATOMIC);
if (addr) {
addr->a.v6.sin6_family = AF_INET6;
addr->a.v6.sin6_addr = ifp->addr;
addr->a.v6.sin6_scope_id = dev->ifindex;
addr->valid = 1;
INIT_LIST_HEAD(&addr->list);
list_add_tail(&addr->list, addrlist);
}
}
read_unlock_bh(&in6_dev->lock);
rcu_read_unlock();
}
/* Copy over any ip options */
static void sctp_v6_copy_ip_options(struct sock *sk, struct sock *newsk)
{
struct ipv6_pinfo *newnp, *np = inet6_sk(sk);
struct ipv6_txoptions *opt;
newnp = inet6_sk(newsk);
rcu_read_lock();
opt = rcu_dereference(np->opt);
if (opt) {
opt = ipv6_dup_options(newsk, opt);
if (!opt)
pr_err("%s: Failed to copy ip options\n", __func__);
}
RCU_INIT_POINTER(newnp->opt, opt);
rcu_read_unlock();
}
/* Account for the IP options */
static int sctp_v6_ip_options_len(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_txoptions *opt;
int len = 0;
rcu_read_lock();
opt = rcu_dereference(np->opt);
if (opt)
len = opt->opt_flen + opt->opt_nflen;
rcu_read_unlock();
return len;
}
/* Initialize a sockaddr_storage from in incoming skb. */
static void sctp_v6_from_skb(union sctp_addr *addr, struct sk_buff *skb,
int is_saddr)
{
/* Always called on head skb, so this is safe */
struct sctphdr *sh = sctp_hdr(skb);
struct sockaddr_in6 *sa = &addr->v6;
addr->v6.sin6_family = AF_INET6;
addr->v6.sin6_flowinfo = 0; /* FIXME */
addr->v6.sin6_scope_id = ((struct inet6_skb_parm *)skb->cb)->iif;
if (is_saddr) {
sa->sin6_port = sh->source;
sa->sin6_addr = ipv6_hdr(skb)->saddr;
} else {
sa->sin6_port = sh->dest;
sa->sin6_addr = ipv6_hdr(skb)->daddr;
}
}
/* Initialize an sctp_addr from a socket. */
static void sctp_v6_from_sk(union sctp_addr *addr, struct sock *sk)
{
addr->v6.sin6_family = AF_INET6;
addr->v6.sin6_port = 0;
addr->v6.sin6_addr = sk->sk_v6_rcv_saddr;
}
/* Initialize sk->sk_rcv_saddr from sctp_addr. */
static void sctp_v6_to_sk_saddr(union sctp_addr *addr, struct sock *sk)
{
if (addr->sa.sa_family == AF_INET) {
sk->sk_v6_rcv_saddr.s6_addr32[0] = 0;
sk->sk_v6_rcv_saddr.s6_addr32[1] = 0;
sk->sk_v6_rcv_saddr.s6_addr32[2] = htonl(0x0000ffff);
sk->sk_v6_rcv_saddr.s6_addr32[3] =
addr->v4.sin_addr.s_addr;
} else {
sk->sk_v6_rcv_saddr = addr->v6.sin6_addr;
}
}
/* Initialize sk->sk_daddr from sctp_addr. */
static void sctp_v6_to_sk_daddr(union sctp_addr *addr, struct sock *sk)
{
if (addr->sa.sa_family == AF_INET) {
sk->sk_v6_daddr.s6_addr32[0] = 0;
sk->sk_v6_daddr.s6_addr32[1] = 0;
sk->sk_v6_daddr.s6_addr32[2] = htonl(0x0000ffff);
sk->sk_v6_daddr.s6_addr32[3] = addr->v4.sin_addr.s_addr;
} else {
sk->sk_v6_daddr = addr->v6.sin6_addr;
}
}
/* Initialize a sctp_addr from an address parameter. */
static bool sctp_v6_from_addr_param(union sctp_addr *addr,
union sctp_addr_param *param,
__be16 port, int iif)
{
if (ntohs(param->v6.param_hdr.length) < sizeof(struct sctp_ipv6addr_param))
return false;
addr->v6.sin6_family = AF_INET6;
addr->v6.sin6_port = port;
addr->v6.sin6_flowinfo = 0; /* BUG */
addr->v6.sin6_addr = param->v6.addr;
addr->v6.sin6_scope_id = iif;
return true;
}
/* Initialize an address parameter from a sctp_addr and return the length
* of the address parameter.
*/
static int sctp_v6_to_addr_param(const union sctp_addr *addr,
union sctp_addr_param *param)
{
int length = sizeof(struct sctp_ipv6addr_param);
param->v6.param_hdr.type = SCTP_PARAM_IPV6_ADDRESS;
param->v6.param_hdr.length = htons(length);
param->v6.addr = addr->v6.sin6_addr;
return length;
}
/* Initialize a sctp_addr from struct in6_addr. */
static void sctp_v6_to_addr(union sctp_addr *addr, struct in6_addr *saddr,
__be16 port)
{
addr->sa.sa_family = AF_INET6;
addr->v6.sin6_port = port;
addr->v6.sin6_flowinfo = 0;
addr->v6.sin6_addr = *saddr;
addr->v6.sin6_scope_id = 0;
}
static int __sctp_v6_cmp_addr(const union sctp_addr *addr1,
const union sctp_addr *addr2)
{
if (addr1->sa.sa_family != addr2->sa.sa_family) {
if (addr1->sa.sa_family == AF_INET &&
addr2->sa.sa_family == AF_INET6 &&
ipv6_addr_v4mapped(&addr2->v6.sin6_addr) &&
addr2->v6.sin6_addr.s6_addr32[3] ==
addr1->v4.sin_addr.s_addr)
return 1;
if (addr2->sa.sa_family == AF_INET &&
addr1->sa.sa_family == AF_INET6 &&
ipv6_addr_v4mapped(&addr1->v6.sin6_addr) &&
addr1->v6.sin6_addr.s6_addr32[3] ==
addr2->v4.sin_addr.s_addr)
return 1;
return 0;
}
if (!ipv6_addr_equal(&addr1->v6.sin6_addr, &addr2->v6.sin6_addr))
return 0;
/* If this is a linklocal address, compare the scope_id. */
if ((ipv6_addr_type(&addr1->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL) &&
addr1->v6.sin6_scope_id && addr2->v6.sin6_scope_id &&
addr1->v6.sin6_scope_id != addr2->v6.sin6_scope_id)
return 0;
return 1;
}
/* Compare addresses exactly.
* v4-mapped-v6 is also in consideration.
*/
static int sctp_v6_cmp_addr(const union sctp_addr *addr1,
const union sctp_addr *addr2)
{
return __sctp_v6_cmp_addr(addr1, addr2) &&
addr1->v6.sin6_port == addr2->v6.sin6_port;
}
/* Initialize addr struct to INADDR_ANY. */
static void sctp_v6_inaddr_any(union sctp_addr *addr, __be16 port)
{
memset(addr, 0x00, sizeof(union sctp_addr));
addr->v6.sin6_family = AF_INET6;
addr->v6.sin6_port = port;
}
/* Is this a wildcard address? */
static int sctp_v6_is_any(const union sctp_addr *addr)
{
return ipv6_addr_any(&addr->v6.sin6_addr);
}
/* Should this be available for binding? */
static int sctp_v6_available(union sctp_addr *addr, struct sctp_sock *sp)
{
const struct in6_addr *in6 = (const struct in6_addr *)&addr->v6.sin6_addr;
struct sock *sk = &sp->inet.sk;
struct net *net = sock_net(sk);
struct net_device *dev = NULL;
int type;
type = ipv6_addr_type(in6);
if (IPV6_ADDR_ANY == type)
return 1;
if (type == IPV6_ADDR_MAPPED) {
if (sp && ipv6_only_sock(sctp_opt2sk(sp)))
return 0;
sctp_v6_map_v4(addr);
return sctp_get_af_specific(AF_INET)->available(addr, sp);
}
if (!(type & IPV6_ADDR_UNICAST))
return 0;
if (sk->sk_bound_dev_if) {
dev = dev_get_by_index_rcu(net, sk->sk_bound_dev_if);
if (!dev)
return 0;
}
return ipv6_can_nonlocal_bind(net, &sp->inet) ||
ipv6_chk_addr(net, in6, dev, 0);
}
/* This function checks if the address is a valid address to be used for
* SCTP.
*
* Output:
* Return 0 - If the address is a non-unicast or an illegal address.
* Return 1 - If the address is a unicast.
*/
static int sctp_v6_addr_valid(union sctp_addr *addr,
struct sctp_sock *sp,
const struct sk_buff *skb)
{
int ret = ipv6_addr_type(&addr->v6.sin6_addr);
/* Support v4-mapped-v6 address. */
if (ret == IPV6_ADDR_MAPPED) {
/* Note: This routine is used in input, so v4-mapped-v6
* are disallowed here when there is no sctp_sock.
*/
if (sp && ipv6_only_sock(sctp_opt2sk(sp)))
return 0;
sctp_v6_map_v4(addr);
return sctp_get_af_specific(AF_INET)->addr_valid(addr, sp, skb);
}
/* Is this a non-unicast address */
if (!(ret & IPV6_ADDR_UNICAST))
return 0;
return 1;
}
/* What is the scope of 'addr'? */
static enum sctp_scope sctp_v6_scope(union sctp_addr *addr)
{
enum sctp_scope retval;
int v6scope;
/* The IPv6 scope is really a set of bit fields.
* See IFA_* in <net/if_inet6.h>. Map to a generic SCTP scope.
*/
v6scope = ipv6_addr_scope(&addr->v6.sin6_addr);
switch (v6scope) {
case IFA_HOST:
retval = SCTP_SCOPE_LOOPBACK;
break;
case IFA_LINK:
retval = SCTP_SCOPE_LINK;
break;
case IFA_SITE:
retval = SCTP_SCOPE_PRIVATE;
break;
default:
retval = SCTP_SCOPE_GLOBAL;
break;
}
return retval;
}
/* Create and initialize a new sk for the socket to be returned by accept(). */
static struct sock *sctp_v6_create_accept_sk(struct sock *sk,
struct sctp_association *asoc,
bool kern)
{
struct sock *newsk;
struct ipv6_pinfo *newnp, *np = inet6_sk(sk);
struct sctp6_sock *newsctp6sk;
newsk = sk_alloc(sock_net(sk), PF_INET6, GFP_KERNEL, sk->sk_prot, kern);
if (!newsk)
goto out;
sock_init_data(NULL, newsk);
sctp_copy_sock(newsk, sk, asoc);
sock_reset_flag(sk, SOCK_ZAPPED);
newsctp6sk = (struct sctp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newsctp6sk->inet6;
sctp_sk(newsk)->v4mapped = sctp_sk(sk)->v4mapped;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newnp->ipv6_mc_list = NULL;
newnp->ipv6_ac_list = NULL;
newnp->ipv6_fl_list = NULL;
sctp_v6_copy_ip_options(sk, newsk);
/* Initialize sk's sport, dport, rcv_saddr and daddr for getsockname()
* and getpeername().
*/
sctp_v6_to_sk_daddr(&asoc->peer.primary_addr, newsk);
newsk->sk_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
if (newsk->sk_prot->init(newsk)) {
sk_common_release(newsk);
newsk = NULL;
}
out:
return newsk;
}
/* Format a sockaddr for return to user space. This makes sure the return is
* AF_INET or AF_INET6 depending on the SCTP_I_WANT_MAPPED_V4_ADDR option.
*/
static int sctp_v6_addr_to_user(struct sctp_sock *sp, union sctp_addr *addr)
{
if (sp->v4mapped) {
if (addr->sa.sa_family == AF_INET)
sctp_v4_map_v6(addr);
} else {
if (addr->sa.sa_family == AF_INET6 &&
ipv6_addr_v4mapped(&addr->v6.sin6_addr))
sctp_v6_map_v4(addr);
}
if (addr->sa.sa_family == AF_INET) {
memset(addr->v4.sin_zero, 0, sizeof(addr->v4.sin_zero));
return sizeof(struct sockaddr_in);
}
return sizeof(struct sockaddr_in6);
}
/* Where did this skb come from? */
static int sctp_v6_skb_iif(const struct sk_buff *skb)
{
return inet6_iif(skb);
}
static int sctp_v6_skb_sdif(const struct sk_buff *skb)
{
return inet6_sdif(skb);
}
/* Was this packet marked by Explicit Congestion Notification? */
static int sctp_v6_is_ce(const struct sk_buff *skb)
{
return *((__u32 *)(ipv6_hdr(skb))) & (__force __u32)htonl(1 << 20);
}
/* Dump the v6 addr to the seq file. */
static void sctp_v6_seq_dump_addr(struct seq_file *seq, union sctp_addr *addr)
{
seq_printf(seq, "%pI6 ", &addr->v6.sin6_addr);
}
static void sctp_v6_ecn_capable(struct sock *sk)
{
inet6_sk(sk)->tclass |= INET_ECN_ECT_0;
}
/* Initialize a PF_INET msgname from a ulpevent. */
static void sctp_inet6_event_msgname(struct sctp_ulpevent *event,
char *msgname, int *addrlen)
{
union sctp_addr *addr;
struct sctp_association *asoc;
union sctp_addr *paddr;
if (!msgname)
return;
addr = (union sctp_addr *)msgname;
asoc = event->asoc;
paddr = &asoc->peer.primary_addr;
if (paddr->sa.sa_family == AF_INET) {
addr->v4.sin_family = AF_INET;
addr->v4.sin_port = htons(asoc->peer.port);
addr->v4.sin_addr = paddr->v4.sin_addr;
} else {
addr->v6.sin6_family = AF_INET6;
addr->v6.sin6_flowinfo = 0;
if (ipv6_addr_type(&paddr->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL)
addr->v6.sin6_scope_id = paddr->v6.sin6_scope_id;
else
addr->v6.sin6_scope_id = 0;
addr->v6.sin6_port = htons(asoc->peer.port);
addr->v6.sin6_addr = paddr->v6.sin6_addr;
}
*addrlen = sctp_v6_addr_to_user(sctp_sk(asoc->base.sk), addr);
}
/* Initialize a msg_name from an inbound skb. */
static void sctp_inet6_skb_msgname(struct sk_buff *skb, char *msgname,
int *addr_len)
{
union sctp_addr *addr;
struct sctphdr *sh;
if (!msgname)
return;
addr = (union sctp_addr *)msgname;
sh = sctp_hdr(skb);
if (ip_hdr(skb)->version == 4) {
addr->v4.sin_family = AF_INET;
addr->v4.sin_port = sh->source;
addr->v4.sin_addr.s_addr = ip_hdr(skb)->saddr;
} else {
addr->v6.sin6_family = AF_INET6;
addr->v6.sin6_flowinfo = 0;
addr->v6.sin6_port = sh->source;
addr->v6.sin6_addr = ipv6_hdr(skb)->saddr;
if (ipv6_addr_type(&addr->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL)
addr->v6.sin6_scope_id = sctp_v6_skb_iif(skb);
else
addr->v6.sin6_scope_id = 0;
}
*addr_len = sctp_v6_addr_to_user(sctp_sk(skb->sk), addr);
}
/* Do we support this AF? */
static int sctp_inet6_af_supported(sa_family_t family, struct sctp_sock *sp)
{
switch (family) {
case AF_INET6:
return 1;
/* v4-mapped-v6 addresses */
case AF_INET:
if (!ipv6_only_sock(sctp_opt2sk(sp)))
return 1;
fallthrough;
default:
return 0;
}
}
/* Address matching with wildcards allowed. This extra level
* of indirection lets us choose whether a PF_INET6 should
* disallow any v4 addresses if we so choose.
*/
static int sctp_inet6_cmp_addr(const union sctp_addr *addr1,
const union sctp_addr *addr2,
struct sctp_sock *opt)
{
struct sock *sk = sctp_opt2sk(opt);
struct sctp_af *af1, *af2;
af1 = sctp_get_af_specific(addr1->sa.sa_family);
af2 = sctp_get_af_specific(addr2->sa.sa_family);
if (!af1 || !af2)
return 0;
/* If the socket is IPv6 only, v4 addrs will not match */
if (ipv6_only_sock(sk) && af1 != af2)
return 0;
/* Today, wildcard AF_INET/AF_INET6. */
if (sctp_is_any(sk, addr1) || sctp_is_any(sk, addr2))
return 1;
if (addr1->sa.sa_family == AF_INET && addr2->sa.sa_family == AF_INET)
return addr1->v4.sin_addr.s_addr == addr2->v4.sin_addr.s_addr;
return __sctp_v6_cmp_addr(addr1, addr2);
}
/* Verify that the provided sockaddr looks bindable. Common verification,
* has already been taken care of.
*/
static int sctp_inet6_bind_verify(struct sctp_sock *opt, union sctp_addr *addr)
{
struct sctp_af *af;
/* ASSERT: address family has already been verified. */
if (addr->sa.sa_family != AF_INET6)
af = sctp_get_af_specific(addr->sa.sa_family);
else {
int type = ipv6_addr_type(&addr->v6.sin6_addr);
struct net_device *dev;
if (type & IPV6_ADDR_LINKLOCAL) {
struct net *net;
if (!addr->v6.sin6_scope_id)
return 0;
net = sock_net(&opt->inet.sk);
rcu_read_lock();
dev = dev_get_by_index_rcu(net, addr->v6.sin6_scope_id);
if (!dev || !(ipv6_can_nonlocal_bind(net, &opt->inet) ||
ipv6_chk_addr(net, &addr->v6.sin6_addr,
dev, 0))) {
rcu_read_unlock();
return 0;
}
rcu_read_unlock();
}
af = opt->pf->af;
}
return af->available(addr, opt);
}
/* Verify that the provided sockaddr looks sendable. Common verification,
* has already been taken care of.
*/
static int sctp_inet6_send_verify(struct sctp_sock *opt, union sctp_addr *addr)
{
struct sctp_af *af = NULL;
/* ASSERT: address family has already been verified. */
if (addr->sa.sa_family != AF_INET6)
af = sctp_get_af_specific(addr->sa.sa_family);
else {
int type = ipv6_addr_type(&addr->v6.sin6_addr);
struct net_device *dev;
if (type & IPV6_ADDR_LINKLOCAL) {
if (!addr->v6.sin6_scope_id)
return 0;
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(&opt->inet.sk),
addr->v6.sin6_scope_id);
rcu_read_unlock();
if (!dev)
return 0;
}
af = opt->pf->af;
}
return af != NULL;
}
/* Fill in Supported Address Type information for INIT and INIT-ACK
* chunks. Note: In the future, we may want to look at sock options
* to determine whether a PF_INET6 socket really wants to have IPV4
* addresses.
* Returns number of addresses supported.
*/
static int sctp_inet6_supported_addrs(const struct sctp_sock *opt,
__be16 *types)
{
types[0] = SCTP_PARAM_IPV6_ADDRESS;
if (!opt || !ipv6_only_sock(sctp_opt2sk(opt))) {
types[1] = SCTP_PARAM_IPV4_ADDRESS;
return 2;
}
return 1;
}
/* Handle SCTP_I_WANT_MAPPED_V4_ADDR for getpeername() and getsockname() */
static int sctp_getname(struct socket *sock, struct sockaddr *uaddr,
int peer)
{
int rc;
rc = inet6_getname(sock, uaddr, peer);
if (rc < 0)
return rc;
rc = sctp_v6_addr_to_user(sctp_sk(sock->sk),
(union sctp_addr *)uaddr);
return rc;
}
static const struct proto_ops inet6_seqpacket_ops = {
.family = PF_INET6,
.owner = THIS_MODULE,
.release = inet6_release,
.bind = inet6_bind,
.connect = sctp_inet_connect,
.socketpair = sock_no_socketpair,
.accept = inet_accept,
.getname = sctp_getname,
.poll = sctp_poll,
.ioctl = inet6_ioctl,
.gettstamp = sock_gettstamp,
.listen = sctp_inet_listen,
.shutdown = inet_shutdown,
.setsockopt = sock_common_setsockopt,
.getsockopt = sock_common_getsockopt,
.sendmsg = inet_sendmsg,
.recvmsg = inet_recvmsg,
.mmap = sock_no_mmap,
#ifdef CONFIG_COMPAT
.compat_ioctl = inet6_compat_ioctl,
#endif
};
static struct inet_protosw sctpv6_seqpacket_protosw = {
.type = SOCK_SEQPACKET,
.protocol = IPPROTO_SCTP,
.prot = &sctpv6_prot,
.ops = &inet6_seqpacket_ops,
.flags = SCTP_PROTOSW_FLAG
};
static struct inet_protosw sctpv6_stream_protosw = {
.type = SOCK_STREAM,
.protocol = IPPROTO_SCTP,
.prot = &sctpv6_prot,
.ops = &inet6_seqpacket_ops,
.flags = SCTP_PROTOSW_FLAG,
};
static int sctp6_rcv(struct sk_buff *skb)
{
SCTP_INPUT_CB(skb)->encap_port = 0;
return sctp_rcv(skb) ? -1 : 0;
}
static const struct inet6_protocol sctpv6_protocol = {
.handler = sctp6_rcv,
.err_handler = sctp_v6_err,
.flags = INET6_PROTO_NOPOLICY | INET6_PROTO_FINAL,
};
static struct sctp_af sctp_af_inet6 = {
.sa_family = AF_INET6,
.sctp_xmit = sctp_v6_xmit,
.setsockopt = ipv6_setsockopt,
.getsockopt = ipv6_getsockopt,
.get_dst = sctp_v6_get_dst,
.get_saddr = sctp_v6_get_saddr,
.copy_addrlist = sctp_v6_copy_addrlist,
.from_skb = sctp_v6_from_skb,
.from_sk = sctp_v6_from_sk,
.from_addr_param = sctp_v6_from_addr_param,
.to_addr_param = sctp_v6_to_addr_param,
.cmp_addr = sctp_v6_cmp_addr,
.scope = sctp_v6_scope,
.addr_valid = sctp_v6_addr_valid,
.inaddr_any = sctp_v6_inaddr_any,
.is_any = sctp_v6_is_any,
.available = sctp_v6_available,
.skb_iif = sctp_v6_skb_iif,
.skb_sdif = sctp_v6_skb_sdif,
.is_ce = sctp_v6_is_ce,
.seq_dump_addr = sctp_v6_seq_dump_addr,
.ecn_capable = sctp_v6_ecn_capable,
.net_header_len = sizeof(struct ipv6hdr),
.sockaddr_len = sizeof(struct sockaddr_in6),
.ip_options_len = sctp_v6_ip_options_len,
};
static struct sctp_pf sctp_pf_inet6 = {
.event_msgname = sctp_inet6_event_msgname,
.skb_msgname = sctp_inet6_skb_msgname,
.af_supported = sctp_inet6_af_supported,
.cmp_addr = sctp_inet6_cmp_addr,
.bind_verify = sctp_inet6_bind_verify,
.send_verify = sctp_inet6_send_verify,
.supported_addrs = sctp_inet6_supported_addrs,
.create_accept_sk = sctp_v6_create_accept_sk,
.addr_to_user = sctp_v6_addr_to_user,
.to_sk_saddr = sctp_v6_to_sk_saddr,
.to_sk_daddr = sctp_v6_to_sk_daddr,
.copy_ip_options = sctp_v6_copy_ip_options,
.af = &sctp_af_inet6,
};
/* Initialize IPv6 support and register with socket layer. */
void sctp_v6_pf_init(void)
{
/* Register the SCTP specific PF_INET6 functions. */
sctp_register_pf(&sctp_pf_inet6, PF_INET6);
/* Register the SCTP specific AF_INET6 functions. */
sctp_register_af(&sctp_af_inet6);
}
void sctp_v6_pf_exit(void)
{
list_del(&sctp_af_inet6.list);
}
/* Initialize IPv6 support and register with socket layer. */
int sctp_v6_protosw_init(void)
{
int rc;
rc = proto_register(&sctpv6_prot, 1);
if (rc)
return rc;
/* Add SCTPv6(UDP and TCP style) to inetsw6 linked list. */
inet6_register_protosw(&sctpv6_seqpacket_protosw);
inet6_register_protosw(&sctpv6_stream_protosw);
return 0;
}
void sctp_v6_protosw_exit(void)
{
inet6_unregister_protosw(&sctpv6_seqpacket_protosw);
inet6_unregister_protosw(&sctpv6_stream_protosw);
proto_unregister(&sctpv6_prot);
}
/* Register with inet6 layer. */
int sctp_v6_add_protocol(void)
{
/* Register notifier for inet6 address additions/deletions. */
register_inet6addr_notifier(&sctp_inet6addr_notifier);
if (inet6_add_protocol(&sctpv6_protocol, IPPROTO_SCTP) < 0)
return -EAGAIN;
return 0;
}
/* Unregister with inet6 layer. */
void sctp_v6_del_protocol(void)
{
inet6_del_protocol(&sctpv6_protocol, IPPROTO_SCTP);
unregister_inet6addr_notifier(&sctp_inet6addr_notifier);
}
| linux-master | net/sctp/ipv6.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2003 Intel Corp.
* Copyright (c) 2001-2002 Nokia, Inc.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This file is part of the SCTP kernel implementation
*
* These functions interface with the sockets layer to implement the
* SCTP Extensions for the Sockets API.
*
* Note that the descriptions from the specification are USER level
* functions--this file is the functions which populate the struct proto
* for SCTP which is the BOTTOM of the sockets interface.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Narasimha Budihal <[email protected]>
* Karl Knutson <[email protected]>
* Jon Grimm <[email protected]>
* Xingang Guo <[email protected]>
* Daisy Chang <[email protected]>
* Sridhar Samudrala <[email protected]>
* Inaky Perez-Gonzalez <[email protected]>
* Ardelle Fan <[email protected]>
* Ryan Layer <[email protected]>
* Anup Pemmaiah <[email protected]>
* Kevin Gao <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <crypto/hash.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/sched/signal.h>
#include <linux/ip.h>
#include <linux/capability.h>
#include <linux/fcntl.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/file.h>
#include <linux/compat.h>
#include <linux/rhashtable.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/route.h>
#include <net/ipv6.h>
#include <net/inet_common.h>
#include <net/busy_poll.h>
#include <trace/events/sock.h>
#include <linux/socket.h> /* for sa_family_t */
#include <linux/export.h>
#include <net/sock.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/stream_sched.h>
/* Forward declarations for internal helper functions. */
static bool sctp_writeable(const struct sock *sk);
static void sctp_wfree(struct sk_buff *skb);
static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
size_t msg_len);
static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p);
static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p);
static int sctp_wait_for_accept(struct sock *sk, long timeo);
static void sctp_wait_for_close(struct sock *sk, long timeo);
static void sctp_destruct_sock(struct sock *sk);
static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
union sctp_addr *addr, int len);
static int sctp_bindx_add(struct sock *, struct sockaddr *, int);
static int sctp_bindx_rem(struct sock *, struct sockaddr *, int);
static int sctp_send_asconf_add_ip(struct sock *, struct sockaddr *, int);
static int sctp_send_asconf_del_ip(struct sock *, struct sockaddr *, int);
static int sctp_send_asconf(struct sctp_association *asoc,
struct sctp_chunk *chunk);
static int sctp_do_bind(struct sock *, union sctp_addr *, int);
static int sctp_autobind(struct sock *sk);
static int sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
struct sctp_association *assoc,
enum sctp_socket_type type);
static unsigned long sctp_memory_pressure;
static atomic_long_t sctp_memory_allocated;
static DEFINE_PER_CPU(int, sctp_memory_per_cpu_fw_alloc);
struct percpu_counter sctp_sockets_allocated;
static void sctp_enter_memory_pressure(struct sock *sk)
{
WRITE_ONCE(sctp_memory_pressure, 1);
}
/* Get the sndbuf space available at the time on the association. */
static inline int sctp_wspace(struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
return asoc->ep->sndbuf_policy ? sk->sk_sndbuf - asoc->sndbuf_used
: sk_stream_wspace(sk);
}
/* Increment the used sndbuf space count of the corresponding association by
* the size of the outgoing data chunk.
* Also, set the skb destructor for sndbuf accounting later.
*
* Since it is always 1-1 between chunk and skb, and also a new skb is always
* allocated for chunk bundling in sctp_packet_transmit(), we can use the
* destructor in the data chunk skb for the purpose of the sndbuf space
* tracking.
*/
static inline void sctp_set_owner_w(struct sctp_chunk *chunk)
{
struct sctp_association *asoc = chunk->asoc;
struct sock *sk = asoc->base.sk;
/* The sndbuf space is tracked per association. */
sctp_association_hold(asoc);
if (chunk->shkey)
sctp_auth_shkey_hold(chunk->shkey);
skb_set_owner_w(chunk->skb, sk);
chunk->skb->destructor = sctp_wfree;
/* Save the chunk pointer in skb for sctp_wfree to use later. */
skb_shinfo(chunk->skb)->destructor_arg = chunk;
refcount_add(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
asoc->sndbuf_used += chunk->skb->truesize + sizeof(struct sctp_chunk);
sk_wmem_queued_add(sk, chunk->skb->truesize + sizeof(struct sctp_chunk));
sk_mem_charge(sk, chunk->skb->truesize);
}
static void sctp_clear_owner_w(struct sctp_chunk *chunk)
{
skb_orphan(chunk->skb);
}
#define traverse_and_process() \
do { \
msg = chunk->msg; \
if (msg == prev_msg) \
continue; \
list_for_each_entry(c, &msg->chunks, frag_list) { \
if ((clear && asoc->base.sk == c->skb->sk) || \
(!clear && asoc->base.sk != c->skb->sk)) \
cb(c); \
} \
prev_msg = msg; \
} while (0)
static void sctp_for_each_tx_datachunk(struct sctp_association *asoc,
bool clear,
void (*cb)(struct sctp_chunk *))
{
struct sctp_datamsg *msg, *prev_msg = NULL;
struct sctp_outq *q = &asoc->outqueue;
struct sctp_chunk *chunk, *c;
struct sctp_transport *t;
list_for_each_entry(t, &asoc->peer.transport_addr_list, transports)
list_for_each_entry(chunk, &t->transmitted, transmitted_list)
traverse_and_process();
list_for_each_entry(chunk, &q->retransmit, transmitted_list)
traverse_and_process();
list_for_each_entry(chunk, &q->sacked, transmitted_list)
traverse_and_process();
list_for_each_entry(chunk, &q->abandoned, transmitted_list)
traverse_and_process();
list_for_each_entry(chunk, &q->out_chunk_list, list)
traverse_and_process();
}
static void sctp_for_each_rx_skb(struct sctp_association *asoc, struct sock *sk,
void (*cb)(struct sk_buff *, struct sock *))
{
struct sk_buff *skb, *tmp;
sctp_skb_for_each(skb, &asoc->ulpq.lobby, tmp)
cb(skb, sk);
sctp_skb_for_each(skb, &asoc->ulpq.reasm, tmp)
cb(skb, sk);
sctp_skb_for_each(skb, &asoc->ulpq.reasm_uo, tmp)
cb(skb, sk);
}
/* Verify that this is a valid address. */
static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr,
int len)
{
struct sctp_af *af;
/* Verify basic sockaddr. */
af = sctp_sockaddr_af(sctp_sk(sk), addr, len);
if (!af)
return -EINVAL;
/* Is this a valid SCTP address? */
if (!af->addr_valid(addr, sctp_sk(sk), NULL))
return -EINVAL;
if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr)))
return -EINVAL;
return 0;
}
/* Look up the association by its id. If this is not a UDP-style
* socket, the ID field is always ignored.
*/
struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id)
{
struct sctp_association *asoc = NULL;
/* If this is not a UDP-style socket, assoc id should be ignored. */
if (!sctp_style(sk, UDP)) {
/* Return NULL if the socket state is not ESTABLISHED. It
* could be a TCP-style listening socket or a socket which
* hasn't yet called connect() to establish an association.
*/
if (!sctp_sstate(sk, ESTABLISHED) && !sctp_sstate(sk, CLOSING))
return NULL;
/* Get the first and the only association from the list. */
if (!list_empty(&sctp_sk(sk)->ep->asocs))
asoc = list_entry(sctp_sk(sk)->ep->asocs.next,
struct sctp_association, asocs);
return asoc;
}
/* Otherwise this is a UDP-style socket. */
if (id <= SCTP_ALL_ASSOC)
return NULL;
spin_lock_bh(&sctp_assocs_id_lock);
asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id);
if (asoc && (asoc->base.sk != sk || asoc->base.dead))
asoc = NULL;
spin_unlock_bh(&sctp_assocs_id_lock);
return asoc;
}
/* Look up the transport from an address and an assoc id. If both address and
* id are specified, the associations matching the address and the id should be
* the same.
*/
static struct sctp_transport *sctp_addr_id2transport(struct sock *sk,
struct sockaddr_storage *addr,
sctp_assoc_t id)
{
struct sctp_association *addr_asoc = NULL, *id_asoc = NULL;
struct sctp_af *af = sctp_get_af_specific(addr->ss_family);
union sctp_addr *laddr = (union sctp_addr *)addr;
struct sctp_transport *transport;
if (!af || sctp_verify_addr(sk, laddr, af->sockaddr_len))
return NULL;
addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep,
laddr,
&transport);
if (!addr_asoc)
return NULL;
id_asoc = sctp_id2assoc(sk, id);
if (id_asoc && (id_asoc != addr_asoc))
return NULL;
sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
(union sctp_addr *)addr);
return transport;
}
/* API 3.1.2 bind() - UDP Style Syntax
* The syntax of bind() is,
*
* ret = bind(int sd, struct sockaddr *addr, int addrlen);
*
* sd - the socket descriptor returned by socket().
* addr - the address structure (struct sockaddr_in or struct
* sockaddr_in6 [RFC 2553]),
* addr_len - the size of the address structure.
*/
static int sctp_bind(struct sock *sk, struct sockaddr *addr, int addr_len)
{
int retval = 0;
lock_sock(sk);
pr_debug("%s: sk:%p, addr:%p, addr_len:%d\n", __func__, sk,
addr, addr_len);
/* Disallow binding twice. */
if (!sctp_sk(sk)->ep->base.bind_addr.port)
retval = sctp_do_bind(sk, (union sctp_addr *)addr,
addr_len);
else
retval = -EINVAL;
release_sock(sk);
return retval;
}
static int sctp_get_port_local(struct sock *, union sctp_addr *);
/* Verify this is a valid sockaddr. */
static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
union sctp_addr *addr, int len)
{
struct sctp_af *af;
/* Check minimum size. */
if (len < sizeof (struct sockaddr))
return NULL;
if (!opt->pf->af_supported(addr->sa.sa_family, opt))
return NULL;
if (addr->sa.sa_family == AF_INET6) {
if (len < SIN6_LEN_RFC2133)
return NULL;
/* V4 mapped address are really of AF_INET family */
if (ipv6_addr_v4mapped(&addr->v6.sin6_addr) &&
!opt->pf->af_supported(AF_INET, opt))
return NULL;
}
/* If we get this far, af is valid. */
af = sctp_get_af_specific(addr->sa.sa_family);
if (len < af->sockaddr_len)
return NULL;
return af;
}
static void sctp_auto_asconf_init(struct sctp_sock *sp)
{
struct net *net = sock_net(&sp->inet.sk);
if (net->sctp.default_auto_asconf) {
spin_lock_bh(&net->sctp.addr_wq_lock);
list_add_tail(&sp->auto_asconf_list, &net->sctp.auto_asconf_splist);
spin_unlock_bh(&net->sctp.addr_wq_lock);
sp->do_auto_asconf = 1;
}
}
/* Bind a local address either to an endpoint or to an association. */
static int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len)
{
struct net *net = sock_net(sk);
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_endpoint *ep = sp->ep;
struct sctp_bind_addr *bp = &ep->base.bind_addr;
struct sctp_af *af;
unsigned short snum;
int ret = 0;
/* Common sockaddr verification. */
af = sctp_sockaddr_af(sp, addr, len);
if (!af) {
pr_debug("%s: sk:%p, newaddr:%p, len:%d EINVAL\n",
__func__, sk, addr, len);
return -EINVAL;
}
snum = ntohs(addr->v4.sin_port);
pr_debug("%s: sk:%p, new addr:%pISc, port:%d, new port:%d, len:%d\n",
__func__, sk, &addr->sa, bp->port, snum, len);
/* PF specific bind() address verification. */
if (!sp->pf->bind_verify(sp, addr))
return -EADDRNOTAVAIL;
/* We must either be unbound, or bind to the same port.
* It's OK to allow 0 ports if we are already bound.
* We'll just inhert an already bound port in this case
*/
if (bp->port) {
if (!snum)
snum = bp->port;
else if (snum != bp->port) {
pr_debug("%s: new port %d doesn't match existing port "
"%d\n", __func__, snum, bp->port);
return -EINVAL;
}
}
if (snum && inet_port_requires_bind_service(net, snum) &&
!ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
return -EACCES;
/* See if the address matches any of the addresses we may have
* already bound before checking against other endpoints.
*/
if (sctp_bind_addr_match(bp, addr, sp))
return -EINVAL;
/* Make sure we are allowed to bind here.
* The function sctp_get_port_local() does duplicate address
* detection.
*/
addr->v4.sin_port = htons(snum);
if (sctp_get_port_local(sk, addr))
return -EADDRINUSE;
/* Refresh ephemeral port. */
if (!bp->port) {
bp->port = inet_sk(sk)->inet_num;
sctp_auto_asconf_init(sp);
}
/* Add the address to the bind address list.
* Use GFP_ATOMIC since BHs will be disabled.
*/
ret = sctp_add_bind_addr(bp, addr, af->sockaddr_len,
SCTP_ADDR_SRC, GFP_ATOMIC);
if (ret) {
sctp_put_port(sk);
return ret;
}
/* Copy back into socket for getsockname() use. */
inet_sk(sk)->inet_sport = htons(inet_sk(sk)->inet_num);
sp->pf->to_sk_saddr(addr, sk);
return ret;
}
/* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks
*
* R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged
* at any one time. If a sender, after sending an ASCONF chunk, decides
* it needs to transfer another ASCONF Chunk, it MUST wait until the
* ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a
* subsequent ASCONF. Note this restriction binds each side, so at any
* time two ASCONF may be in-transit on any given association (one sent
* from each endpoint).
*/
static int sctp_send_asconf(struct sctp_association *asoc,
struct sctp_chunk *chunk)
{
int retval = 0;
/* If there is an outstanding ASCONF chunk, queue it for later
* transmission.
*/
if (asoc->addip_last_asconf) {
list_add_tail(&chunk->list, &asoc->addip_chunk_list);
goto out;
}
/* Hold the chunk until an ASCONF_ACK is received. */
sctp_chunk_hold(chunk);
retval = sctp_primitive_ASCONF(asoc->base.net, asoc, chunk);
if (retval)
sctp_chunk_free(chunk);
else
asoc->addip_last_asconf = chunk;
out:
return retval;
}
/* Add a list of addresses as bind addresses to local endpoint or
* association.
*
* Basically run through each address specified in the addrs/addrcnt
* array/length pair, determine if it is IPv6 or IPv4 and call
* sctp_do_bind() on it.
*
* If any of them fails, then the operation will be reversed and the
* ones that were added will be removed.
*
* Only sctp_setsockopt_bindx() is supposed to call this function.
*/
static int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt)
{
int cnt;
int retval = 0;
void *addr_buf;
struct sockaddr *sa_addr;
struct sctp_af *af;
pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk,
addrs, addrcnt);
addr_buf = addrs;
for (cnt = 0; cnt < addrcnt; cnt++) {
/* The list may contain either IPv4 or IPv6 address;
* determine the address length for walking thru the list.
*/
sa_addr = addr_buf;
af = sctp_get_af_specific(sa_addr->sa_family);
if (!af) {
retval = -EINVAL;
goto err_bindx_add;
}
retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr,
af->sockaddr_len);
addr_buf += af->sockaddr_len;
err_bindx_add:
if (retval < 0) {
/* Failed. Cleanup the ones that have been added */
if (cnt > 0)
sctp_bindx_rem(sk, addrs, cnt);
return retval;
}
}
return retval;
}
/* Send an ASCONF chunk with Add IP address parameters to all the peers of the
* associations that are part of the endpoint indicating that a list of local
* addresses are added to the endpoint.
*
* If any of the addresses is already in the bind address list of the
* association, we do not send the chunk for that association. But it will not
* affect other associations.
*
* Only sctp_setsockopt_bindx() is supposed to call this function.
*/
static int sctp_send_asconf_add_ip(struct sock *sk,
struct sockaddr *addrs,
int addrcnt)
{
struct sctp_sock *sp;
struct sctp_endpoint *ep;
struct sctp_association *asoc;
struct sctp_bind_addr *bp;
struct sctp_chunk *chunk;
struct sctp_sockaddr_entry *laddr;
union sctp_addr *addr;
union sctp_addr saveaddr;
void *addr_buf;
struct sctp_af *af;
struct list_head *p;
int i;
int retval = 0;
sp = sctp_sk(sk);
ep = sp->ep;
if (!ep->asconf_enable)
return retval;
pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
__func__, sk, addrs, addrcnt);
list_for_each_entry(asoc, &ep->asocs, asocs) {
if (!asoc->peer.asconf_capable)
continue;
if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP)
continue;
if (!sctp_state(asoc, ESTABLISHED))
continue;
/* Check if any address in the packed array of addresses is
* in the bind address list of the association. If so,
* do not send the asconf chunk to its peer, but continue with
* other associations.
*/
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
if (!af) {
retval = -EINVAL;
goto out;
}
if (sctp_assoc_lookup_laddr(asoc, addr))
break;
addr_buf += af->sockaddr_len;
}
if (i < addrcnt)
continue;
/* Use the first valid address in bind addr list of
* association as Address Parameter of ASCONF CHUNK.
*/
bp = &asoc->base.bind_addr;
p = bp->address_list.next;
laddr = list_entry(p, struct sctp_sockaddr_entry, list);
chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs,
addrcnt, SCTP_PARAM_ADD_IP);
if (!chunk) {
retval = -ENOMEM;
goto out;
}
/* Add the new addresses to the bind address list with
* use_as_src set to 0.
*/
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
memcpy(&saveaddr, addr, af->sockaddr_len);
retval = sctp_add_bind_addr(bp, &saveaddr,
sizeof(saveaddr),
SCTP_ADDR_NEW, GFP_ATOMIC);
addr_buf += af->sockaddr_len;
}
if (asoc->src_out_of_asoc_ok) {
struct sctp_transport *trans;
list_for_each_entry(trans,
&asoc->peer.transport_addr_list, transports) {
trans->cwnd = min(4*asoc->pathmtu, max_t(__u32,
2*asoc->pathmtu, 4380));
trans->ssthresh = asoc->peer.i.a_rwnd;
trans->rto = asoc->rto_initial;
sctp_max_rto(asoc, trans);
trans->rtt = trans->srtt = trans->rttvar = 0;
/* Clear the source and route cache */
sctp_transport_route(trans, NULL,
sctp_sk(asoc->base.sk));
}
}
retval = sctp_send_asconf(asoc, chunk);
}
out:
return retval;
}
/* Remove a list of addresses from bind addresses list. Do not remove the
* last address.
*
* Basically run through each address specified in the addrs/addrcnt
* array/length pair, determine if it is IPv6 or IPv4 and call
* sctp_del_bind() on it.
*
* If any of them fails, then the operation will be reversed and the
* ones that were removed will be added back.
*
* At least one address has to be left; if only one address is
* available, the operation will return -EBUSY.
*
* Only sctp_setsockopt_bindx() is supposed to call this function.
*/
static int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_endpoint *ep = sp->ep;
int cnt;
struct sctp_bind_addr *bp = &ep->base.bind_addr;
int retval = 0;
void *addr_buf;
union sctp_addr *sa_addr;
struct sctp_af *af;
pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
__func__, sk, addrs, addrcnt);
addr_buf = addrs;
for (cnt = 0; cnt < addrcnt; cnt++) {
/* If the bind address list is empty or if there is only one
* bind address, there is nothing more to be removed (we need
* at least one address here).
*/
if (list_empty(&bp->address_list) ||
(sctp_list_single_entry(&bp->address_list))) {
retval = -EBUSY;
goto err_bindx_rem;
}
sa_addr = addr_buf;
af = sctp_get_af_specific(sa_addr->sa.sa_family);
if (!af) {
retval = -EINVAL;
goto err_bindx_rem;
}
if (!af->addr_valid(sa_addr, sp, NULL)) {
retval = -EADDRNOTAVAIL;
goto err_bindx_rem;
}
if (sa_addr->v4.sin_port &&
sa_addr->v4.sin_port != htons(bp->port)) {
retval = -EINVAL;
goto err_bindx_rem;
}
if (!sa_addr->v4.sin_port)
sa_addr->v4.sin_port = htons(bp->port);
/* FIXME - There is probably a need to check if sk->sk_saddr and
* sk->sk_rcv_addr are currently set to one of the addresses to
* be removed. This is something which needs to be looked into
* when we are fixing the outstanding issues with multi-homing
* socket routing and failover schemes. Refer to comments in
* sctp_do_bind(). -daisy
*/
retval = sctp_del_bind_addr(bp, sa_addr);
addr_buf += af->sockaddr_len;
err_bindx_rem:
if (retval < 0) {
/* Failed. Add the ones that has been removed back */
if (cnt > 0)
sctp_bindx_add(sk, addrs, cnt);
return retval;
}
}
return retval;
}
/* Send an ASCONF chunk with Delete IP address parameters to all the peers of
* the associations that are part of the endpoint indicating that a list of
* local addresses are removed from the endpoint.
*
* If any of the addresses is already in the bind address list of the
* association, we do not send the chunk for that association. But it will not
* affect other associations.
*
* Only sctp_setsockopt_bindx() is supposed to call this function.
*/
static int sctp_send_asconf_del_ip(struct sock *sk,
struct sockaddr *addrs,
int addrcnt)
{
struct sctp_sock *sp;
struct sctp_endpoint *ep;
struct sctp_association *asoc;
struct sctp_transport *transport;
struct sctp_bind_addr *bp;
struct sctp_chunk *chunk;
union sctp_addr *laddr;
void *addr_buf;
struct sctp_af *af;
struct sctp_sockaddr_entry *saddr;
int i;
int retval = 0;
int stored = 0;
chunk = NULL;
sp = sctp_sk(sk);
ep = sp->ep;
if (!ep->asconf_enable)
return retval;
pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
__func__, sk, addrs, addrcnt);
list_for_each_entry(asoc, &ep->asocs, asocs) {
if (!asoc->peer.asconf_capable)
continue;
if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP)
continue;
if (!sctp_state(asoc, ESTABLISHED))
continue;
/* Check if any address in the packed array of addresses is
* not present in the bind address list of the association.
* If so, do not send the asconf chunk to its peer, but
* continue with other associations.
*/
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
laddr = addr_buf;
af = sctp_get_af_specific(laddr->v4.sin_family);
if (!af) {
retval = -EINVAL;
goto out;
}
if (!sctp_assoc_lookup_laddr(asoc, laddr))
break;
addr_buf += af->sockaddr_len;
}
if (i < addrcnt)
continue;
/* Find one address in the association's bind address list
* that is not in the packed array of addresses. This is to
* make sure that we do not delete all the addresses in the
* association.
*/
bp = &asoc->base.bind_addr;
laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs,
addrcnt, sp);
if ((laddr == NULL) && (addrcnt == 1)) {
if (asoc->asconf_addr_del_pending)
continue;
asoc->asconf_addr_del_pending =
kzalloc(sizeof(union sctp_addr), GFP_ATOMIC);
if (asoc->asconf_addr_del_pending == NULL) {
retval = -ENOMEM;
goto out;
}
asoc->asconf_addr_del_pending->sa.sa_family =
addrs->sa_family;
asoc->asconf_addr_del_pending->v4.sin_port =
htons(bp->port);
if (addrs->sa_family == AF_INET) {
struct sockaddr_in *sin;
sin = (struct sockaddr_in *)addrs;
asoc->asconf_addr_del_pending->v4.sin_addr.s_addr = sin->sin_addr.s_addr;
} else if (addrs->sa_family == AF_INET6) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *)addrs;
asoc->asconf_addr_del_pending->v6.sin6_addr = sin6->sin6_addr;
}
pr_debug("%s: keep the last address asoc:%p %pISc at %p\n",
__func__, asoc, &asoc->asconf_addr_del_pending->sa,
asoc->asconf_addr_del_pending);
asoc->src_out_of_asoc_ok = 1;
stored = 1;
goto skip_mkasconf;
}
if (laddr == NULL)
return -EINVAL;
/* We do not need RCU protection throughout this loop
* because this is done under a socket lock from the
* setsockopt call.
*/
chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt,
SCTP_PARAM_DEL_IP);
if (!chunk) {
retval = -ENOMEM;
goto out;
}
skip_mkasconf:
/* Reset use_as_src flag for the addresses in the bind address
* list that are to be deleted.
*/
addr_buf = addrs;
for (i = 0; i < addrcnt; i++) {
laddr = addr_buf;
af = sctp_get_af_specific(laddr->v4.sin_family);
list_for_each_entry(saddr, &bp->address_list, list) {
if (sctp_cmp_addr_exact(&saddr->a, laddr))
saddr->state = SCTP_ADDR_DEL;
}
addr_buf += af->sockaddr_len;
}
/* Update the route and saddr entries for all the transports
* as some of the addresses in the bind address list are
* about to be deleted and cannot be used as source addresses.
*/
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
sctp_transport_route(transport, NULL,
sctp_sk(asoc->base.sk));
}
if (stored)
/* We don't need to transmit ASCONF */
continue;
retval = sctp_send_asconf(asoc, chunk);
}
out:
return retval;
}
/* set addr events to assocs in the endpoint. ep and addr_wq must be locked */
int sctp_asconf_mgmt(struct sctp_sock *sp, struct sctp_sockaddr_entry *addrw)
{
struct sock *sk = sctp_opt2sk(sp);
union sctp_addr *addr;
struct sctp_af *af;
/* It is safe to write port space in caller. */
addr = &addrw->a;
addr->v4.sin_port = htons(sp->ep->base.bind_addr.port);
af = sctp_get_af_specific(addr->sa.sa_family);
if (!af)
return -EINVAL;
if (sctp_verify_addr(sk, addr, af->sockaddr_len))
return -EINVAL;
if (addrw->state == SCTP_ADDR_NEW)
return sctp_send_asconf_add_ip(sk, (struct sockaddr *)addr, 1);
else
return sctp_send_asconf_del_ip(sk, (struct sockaddr *)addr, 1);
}
/* Helper for tunneling sctp_bindx() requests through sctp_setsockopt()
*
* API 8.1
* int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt,
* int flags);
*
* If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
* If the sd is an IPv6 socket, the addresses passed can either be IPv4
* or IPv6 addresses.
*
* A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
* Section 3.1.2 for this usage.
*
* addrs is a pointer to an array of one or more socket addresses. Each
* address is contained in its appropriate structure (i.e. struct
* sockaddr_in or struct sockaddr_in6) the family of the address type
* must be used to distinguish the address length (note that this
* representation is termed a "packed array" of addresses). The caller
* specifies the number of addresses in the array with addrcnt.
*
* On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns
* -1, and sets errno to the appropriate error code.
*
* For SCTP, the port given in each socket address must be the same, or
* sctp_bindx() will fail, setting errno to EINVAL.
*
* The flags parameter is formed from the bitwise OR of zero or more of
* the following currently defined flags:
*
* SCTP_BINDX_ADD_ADDR
*
* SCTP_BINDX_REM_ADDR
*
* SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the
* association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given
* addresses from the association. The two flags are mutually exclusive;
* if both are given, sctp_bindx() will fail with EINVAL. A caller may
* not remove all addresses from an association; sctp_bindx() will
* reject such an attempt with EINVAL.
*
* An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate
* additional addresses with an endpoint after calling bind(). Or use
* sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening
* socket is associated with so that no new association accepted will be
* associated with those addresses. If the endpoint supports dynamic
* address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a
* endpoint to send the appropriate message to the peer to change the
* peers address lists.
*
* Adding and removing addresses from a connected association is
* optional functionality. Implementations that do not support this
* functionality should return EOPNOTSUPP.
*
* Basically do nothing but copying the addresses from user to kernel
* land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk.
* This is used for tunneling the sctp_bindx() request through sctp_setsockopt()
* from userspace.
*
* On exit there is no need to do sockfd_put(), sys_setsockopt() does
* it.
*
* sk The sk of the socket
* addrs The pointer to the addresses
* addrssize Size of the addrs buffer
* op Operation to perform (add or remove, see the flags of
* sctp_bindx)
*
* Returns 0 if ok, <0 errno code on error.
*/
static int sctp_setsockopt_bindx(struct sock *sk, struct sockaddr *addrs,
int addrs_size, int op)
{
int err;
int addrcnt = 0;
int walk_size = 0;
struct sockaddr *sa_addr;
void *addr_buf = addrs;
struct sctp_af *af;
pr_debug("%s: sk:%p addrs:%p addrs_size:%d opt:%d\n",
__func__, sk, addr_buf, addrs_size, op);
if (unlikely(addrs_size <= 0))
return -EINVAL;
/* Walk through the addrs buffer and count the number of addresses. */
while (walk_size < addrs_size) {
if (walk_size + sizeof(sa_family_t) > addrs_size)
return -EINVAL;
sa_addr = addr_buf;
af = sctp_get_af_specific(sa_addr->sa_family);
/* If the address family is not supported or if this address
* causes the address buffer to overflow return EINVAL.
*/
if (!af || (walk_size + af->sockaddr_len) > addrs_size)
return -EINVAL;
addrcnt++;
addr_buf += af->sockaddr_len;
walk_size += af->sockaddr_len;
}
/* Do the work. */
switch (op) {
case SCTP_BINDX_ADD_ADDR:
/* Allow security module to validate bindx addresses. */
err = security_sctp_bind_connect(sk, SCTP_SOCKOPT_BINDX_ADD,
addrs, addrs_size);
if (err)
return err;
err = sctp_bindx_add(sk, addrs, addrcnt);
if (err)
return err;
return sctp_send_asconf_add_ip(sk, addrs, addrcnt);
case SCTP_BINDX_REM_ADDR:
err = sctp_bindx_rem(sk, addrs, addrcnt);
if (err)
return err;
return sctp_send_asconf_del_ip(sk, addrs, addrcnt);
default:
return -EINVAL;
}
}
static int sctp_bind_add(struct sock *sk, struct sockaddr *addrs,
int addrlen)
{
int err;
lock_sock(sk);
err = sctp_setsockopt_bindx(sk, addrs, addrlen, SCTP_BINDX_ADD_ADDR);
release_sock(sk);
return err;
}
static int sctp_connect_new_asoc(struct sctp_endpoint *ep,
const union sctp_addr *daddr,
const struct sctp_initmsg *init,
struct sctp_transport **tp)
{
struct sctp_association *asoc;
struct sock *sk = ep->base.sk;
struct net *net = sock_net(sk);
enum sctp_scope scope;
int err;
if (sctp_endpoint_is_peeled_off(ep, daddr))
return -EADDRNOTAVAIL;
if (!ep->base.bind_addr.port) {
if (sctp_autobind(sk))
return -EAGAIN;
} else {
if (inet_port_requires_bind_service(net, ep->base.bind_addr.port) &&
!ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
return -EACCES;
}
scope = sctp_scope(daddr);
asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
if (!asoc)
return -ENOMEM;
err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, GFP_KERNEL);
if (err < 0)
goto free;
*tp = sctp_assoc_add_peer(asoc, daddr, GFP_KERNEL, SCTP_UNKNOWN);
if (!*tp) {
err = -ENOMEM;
goto free;
}
if (!init)
return 0;
if (init->sinit_num_ostreams) {
__u16 outcnt = init->sinit_num_ostreams;
asoc->c.sinit_num_ostreams = outcnt;
/* outcnt has been changed, need to re-init stream */
err = sctp_stream_init(&asoc->stream, outcnt, 0, GFP_KERNEL);
if (err)
goto free;
}
if (init->sinit_max_instreams)
asoc->c.sinit_max_instreams = init->sinit_max_instreams;
if (init->sinit_max_attempts)
asoc->max_init_attempts = init->sinit_max_attempts;
if (init->sinit_max_init_timeo)
asoc->max_init_timeo =
msecs_to_jiffies(init->sinit_max_init_timeo);
return 0;
free:
sctp_association_free(asoc);
return err;
}
static int sctp_connect_add_peer(struct sctp_association *asoc,
union sctp_addr *daddr, int addr_len)
{
struct sctp_endpoint *ep = asoc->ep;
struct sctp_association *old;
struct sctp_transport *t;
int err;
err = sctp_verify_addr(ep->base.sk, daddr, addr_len);
if (err)
return err;
old = sctp_endpoint_lookup_assoc(ep, daddr, &t);
if (old && old != asoc)
return old->state >= SCTP_STATE_ESTABLISHED ? -EISCONN
: -EALREADY;
if (sctp_endpoint_is_peeled_off(ep, daddr))
return -EADDRNOTAVAIL;
t = sctp_assoc_add_peer(asoc, daddr, GFP_KERNEL, SCTP_UNKNOWN);
if (!t)
return -ENOMEM;
return 0;
}
/* __sctp_connect(struct sock* sk, struct sockaddr *kaddrs, int addrs_size)
*
* Common routine for handling connect() and sctp_connectx().
* Connect will come in with just a single address.
*/
static int __sctp_connect(struct sock *sk, struct sockaddr *kaddrs,
int addrs_size, int flags, sctp_assoc_t *assoc_id)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_endpoint *ep = sp->ep;
struct sctp_transport *transport;
struct sctp_association *asoc;
void *addr_buf = kaddrs;
union sctp_addr *daddr;
struct sctp_af *af;
int walk_size, err;
long timeo;
if (sctp_sstate(sk, ESTABLISHED) || sctp_sstate(sk, CLOSING) ||
(sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)))
return -EISCONN;
daddr = addr_buf;
af = sctp_get_af_specific(daddr->sa.sa_family);
if (!af || af->sockaddr_len > addrs_size)
return -EINVAL;
err = sctp_verify_addr(sk, daddr, af->sockaddr_len);
if (err)
return err;
asoc = sctp_endpoint_lookup_assoc(ep, daddr, &transport);
if (asoc)
return asoc->state >= SCTP_STATE_ESTABLISHED ? -EISCONN
: -EALREADY;
err = sctp_connect_new_asoc(ep, daddr, NULL, &transport);
if (err)
return err;
asoc = transport->asoc;
addr_buf += af->sockaddr_len;
walk_size = af->sockaddr_len;
while (walk_size < addrs_size) {
err = -EINVAL;
if (walk_size + sizeof(sa_family_t) > addrs_size)
goto out_free;
daddr = addr_buf;
af = sctp_get_af_specific(daddr->sa.sa_family);
if (!af || af->sockaddr_len + walk_size > addrs_size)
goto out_free;
if (asoc->peer.port != ntohs(daddr->v4.sin_port))
goto out_free;
err = sctp_connect_add_peer(asoc, daddr, af->sockaddr_len);
if (err)
goto out_free;
addr_buf += af->sockaddr_len;
walk_size += af->sockaddr_len;
}
/* In case the user of sctp_connectx() wants an association
* id back, assign one now.
*/
if (assoc_id) {
err = sctp_assoc_set_id(asoc, GFP_KERNEL);
if (err < 0)
goto out_free;
}
err = sctp_primitive_ASSOCIATE(sock_net(sk), asoc, NULL);
if (err < 0)
goto out_free;
/* Initialize sk's dport and daddr for getpeername() */
inet_sk(sk)->inet_dport = htons(asoc->peer.port);
sp->pf->to_sk_daddr(daddr, sk);
sk->sk_err = 0;
if (assoc_id)
*assoc_id = asoc->assoc_id;
timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
return sctp_wait_for_connect(asoc, &timeo);
out_free:
pr_debug("%s: took out_free path with asoc:%p kaddrs:%p err:%d\n",
__func__, asoc, kaddrs, err);
sctp_association_free(asoc);
return err;
}
/* Helper for tunneling sctp_connectx() requests through sctp_setsockopt()
*
* API 8.9
* int sctp_connectx(int sd, struct sockaddr *addrs, int addrcnt,
* sctp_assoc_t *asoc);
*
* If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
* If the sd is an IPv6 socket, the addresses passed can either be IPv4
* or IPv6 addresses.
*
* A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
* Section 3.1.2 for this usage.
*
* addrs is a pointer to an array of one or more socket addresses. Each
* address is contained in its appropriate structure (i.e. struct
* sockaddr_in or struct sockaddr_in6) the family of the address type
* must be used to distengish the address length (note that this
* representation is termed a "packed array" of addresses). The caller
* specifies the number of addresses in the array with addrcnt.
*
* On success, sctp_connectx() returns 0. It also sets the assoc_id to
* the association id of the new association. On failure, sctp_connectx()
* returns -1, and sets errno to the appropriate error code. The assoc_id
* is not touched by the kernel.
*
* For SCTP, the port given in each socket address must be the same, or
* sctp_connectx() will fail, setting errno to EINVAL.
*
* An application can use sctp_connectx to initiate an association with
* an endpoint that is multi-homed. Much like sctp_bindx() this call
* allows a caller to specify multiple addresses at which a peer can be
* reached. The way the SCTP stack uses the list of addresses to set up
* the association is implementation dependent. This function only
* specifies that the stack will try to make use of all the addresses in
* the list when needed.
*
* Note that the list of addresses passed in is only used for setting up
* the association. It does not necessarily equal the set of addresses
* the peer uses for the resulting association. If the caller wants to
* find out the set of peer addresses, it must use sctp_getpaddrs() to
* retrieve them after the association has been set up.
*
* Basically do nothing but copying the addresses from user to kernel
* land and invoking either sctp_connectx(). This is used for tunneling
* the sctp_connectx() request through sctp_setsockopt() from userspace.
*
* On exit there is no need to do sockfd_put(), sys_setsockopt() does
* it.
*
* sk The sk of the socket
* addrs The pointer to the addresses
* addrssize Size of the addrs buffer
*
* Returns >=0 if ok, <0 errno code on error.
*/
static int __sctp_setsockopt_connectx(struct sock *sk, struct sockaddr *kaddrs,
int addrs_size, sctp_assoc_t *assoc_id)
{
int err = 0, flags = 0;
pr_debug("%s: sk:%p addrs:%p addrs_size:%d\n",
__func__, sk, kaddrs, addrs_size);
/* make sure the 1st addr's sa_family is accessible later */
if (unlikely(addrs_size < sizeof(sa_family_t)))
return -EINVAL;
/* Allow security module to validate connectx addresses. */
err = security_sctp_bind_connect(sk, SCTP_SOCKOPT_CONNECTX,
(struct sockaddr *)kaddrs,
addrs_size);
if (err)
return err;
/* in-kernel sockets don't generally have a file allocated to them
* if all they do is call sock_create_kern().
*/
if (sk->sk_socket->file)
flags = sk->sk_socket->file->f_flags;
return __sctp_connect(sk, kaddrs, addrs_size, flags, assoc_id);
}
/*
* This is an older interface. It's kept for backward compatibility
* to the option that doesn't provide association id.
*/
static int sctp_setsockopt_connectx_old(struct sock *sk,
struct sockaddr *kaddrs,
int addrs_size)
{
return __sctp_setsockopt_connectx(sk, kaddrs, addrs_size, NULL);
}
/*
* New interface for the API. The since the API is done with a socket
* option, to make it simple we feed back the association id is as a return
* indication to the call. Error is always negative and association id is
* always positive.
*/
static int sctp_setsockopt_connectx(struct sock *sk,
struct sockaddr *kaddrs,
int addrs_size)
{
sctp_assoc_t assoc_id = 0;
int err = 0;
err = __sctp_setsockopt_connectx(sk, kaddrs, addrs_size, &assoc_id);
if (err)
return err;
else
return assoc_id;
}
/*
* New (hopefully final) interface for the API.
* We use the sctp_getaddrs_old structure so that use-space library
* can avoid any unnecessary allocations. The only different part
* is that we store the actual length of the address buffer into the
* addrs_num structure member. That way we can re-use the existing
* code.
*/
#ifdef CONFIG_COMPAT
struct compat_sctp_getaddrs_old {
sctp_assoc_t assoc_id;
s32 addr_num;
compat_uptr_t addrs; /* struct sockaddr * */
};
#endif
static int sctp_getsockopt_connectx3(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_getaddrs_old param;
sctp_assoc_t assoc_id = 0;
struct sockaddr *kaddrs;
int err = 0;
#ifdef CONFIG_COMPAT
if (in_compat_syscall()) {
struct compat_sctp_getaddrs_old param32;
if (len < sizeof(param32))
return -EINVAL;
if (copy_from_user(¶m32, optval, sizeof(param32)))
return -EFAULT;
param.assoc_id = param32.assoc_id;
param.addr_num = param32.addr_num;
param.addrs = compat_ptr(param32.addrs);
} else
#endif
{
if (len < sizeof(param))
return -EINVAL;
if (copy_from_user(¶m, optval, sizeof(param)))
return -EFAULT;
}
kaddrs = memdup_user(param.addrs, param.addr_num);
if (IS_ERR(kaddrs))
return PTR_ERR(kaddrs);
err = __sctp_setsockopt_connectx(sk, kaddrs, param.addr_num, &assoc_id);
kfree(kaddrs);
if (err == 0 || err == -EINPROGRESS) {
if (copy_to_user(optval, &assoc_id, sizeof(assoc_id)))
return -EFAULT;
if (put_user(sizeof(assoc_id), optlen))
return -EFAULT;
}
return err;
}
/* API 3.1.4 close() - UDP Style Syntax
* Applications use close() to perform graceful shutdown (as described in
* Section 10.1 of [SCTP]) on ALL the associations currently represented
* by a UDP-style socket.
*
* The syntax is
*
* ret = close(int sd);
*
* sd - the socket descriptor of the associations to be closed.
*
* To gracefully shutdown a specific association represented by the
* UDP-style socket, an application should use the sendmsg() call,
* passing no user data, but including the appropriate flag in the
* ancillary data (see Section xxxx).
*
* If sd in the close() call is a branched-off socket representing only
* one association, the shutdown is performed on that association only.
*
* 4.1.6 close() - TCP Style Syntax
*
* Applications use close() to gracefully close down an association.
*
* The syntax is:
*
* int close(int sd);
*
* sd - the socket descriptor of the association to be closed.
*
* After an application calls close() on a socket descriptor, no further
* socket operations will succeed on that descriptor.
*
* API 7.1.4 SO_LINGER
*
* An application using the TCP-style socket can use this option to
* perform the SCTP ABORT primitive. The linger option structure is:
*
* struct linger {
* int l_onoff; // option on/off
* int l_linger; // linger time
* };
*
* To enable the option, set l_onoff to 1. If the l_linger value is set
* to 0, calling close() is the same as the ABORT primitive. If the
* value is set to a negative value, the setsockopt() call will return
* an error. If the value is set to a positive value linger_time, the
* close() can be blocked for at most linger_time ms. If the graceful
* shutdown phase does not finish during this period, close() will
* return but the graceful shutdown phase continues in the system.
*/
static void sctp_close(struct sock *sk, long timeout)
{
struct net *net = sock_net(sk);
struct sctp_endpoint *ep;
struct sctp_association *asoc;
struct list_head *pos, *temp;
unsigned int data_was_unread;
pr_debug("%s: sk:%p, timeout:%ld\n", __func__, sk, timeout);
lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
sk->sk_shutdown = SHUTDOWN_MASK;
inet_sk_set_state(sk, SCTP_SS_CLOSING);
ep = sctp_sk(sk)->ep;
/* Clean up any skbs sitting on the receive queue. */
data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
/* Walk all associations on an endpoint. */
list_for_each_safe(pos, temp, &ep->asocs) {
asoc = list_entry(pos, struct sctp_association, asocs);
if (sctp_style(sk, TCP)) {
/* A closed association can still be in the list if
* it belongs to a TCP-style listening socket that is
* not yet accepted. If so, free it. If not, send an
* ABORT or SHUTDOWN based on the linger options.
*/
if (sctp_state(asoc, CLOSED)) {
sctp_association_free(asoc);
continue;
}
}
if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) ||
!skb_queue_empty(&asoc->ulpq.reasm) ||
!skb_queue_empty(&asoc->ulpq.reasm_uo) ||
(sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) {
struct sctp_chunk *chunk;
chunk = sctp_make_abort_user(asoc, NULL, 0);
sctp_primitive_ABORT(net, asoc, chunk);
} else
sctp_primitive_SHUTDOWN(net, asoc, NULL);
}
/* On a TCP-style socket, block for at most linger_time if set. */
if (sctp_style(sk, TCP) && timeout)
sctp_wait_for_close(sk, timeout);
/* This will run the backlog queue. */
release_sock(sk);
/* Supposedly, no process has access to the socket, but
* the net layers still may.
* Also, sctp_destroy_sock() needs to be called with addr_wq_lock
* held and that should be grabbed before socket lock.
*/
spin_lock_bh(&net->sctp.addr_wq_lock);
bh_lock_sock_nested(sk);
/* Hold the sock, since sk_common_release() will put sock_put()
* and we have just a little more cleanup.
*/
sock_hold(sk);
sk_common_release(sk);
bh_unlock_sock(sk);
spin_unlock_bh(&net->sctp.addr_wq_lock);
sock_put(sk);
SCTP_DBG_OBJCNT_DEC(sock);
}
/* Handle EPIPE error. */
static int sctp_error(struct sock *sk, int flags, int err)
{
if (err == -EPIPE)
err = sock_error(sk) ? : -EPIPE;
if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
return err;
}
/* API 3.1.3 sendmsg() - UDP Style Syntax
*
* An application uses sendmsg() and recvmsg() calls to transmit data to
* and receive data from its peer.
*
* ssize_t sendmsg(int socket, const struct msghdr *message,
* int flags);
*
* socket - the socket descriptor of the endpoint.
* message - pointer to the msghdr structure which contains a single
* user message and possibly some ancillary data.
*
* See Section 5 for complete description of the data
* structures.
*
* flags - flags sent or received with the user message, see Section
* 5 for complete description of the flags.
*
* Note: This function could use a rewrite especially when explicit
* connect support comes in.
*/
/* BUG: We do not implement the equivalent of sk_stream_wait_memory(). */
static int sctp_msghdr_parse(const struct msghdr *msg,
struct sctp_cmsgs *cmsgs);
static int sctp_sendmsg_parse(struct sock *sk, struct sctp_cmsgs *cmsgs,
struct sctp_sndrcvinfo *srinfo,
const struct msghdr *msg, size_t msg_len)
{
__u16 sflags;
int err;
if (sctp_sstate(sk, LISTENING) && sctp_style(sk, TCP))
return -EPIPE;
if (msg_len > sk->sk_sndbuf)
return -EMSGSIZE;
memset(cmsgs, 0, sizeof(*cmsgs));
err = sctp_msghdr_parse(msg, cmsgs);
if (err) {
pr_debug("%s: msghdr parse err:%x\n", __func__, err);
return err;
}
memset(srinfo, 0, sizeof(*srinfo));
if (cmsgs->srinfo) {
srinfo->sinfo_stream = cmsgs->srinfo->sinfo_stream;
srinfo->sinfo_flags = cmsgs->srinfo->sinfo_flags;
srinfo->sinfo_ppid = cmsgs->srinfo->sinfo_ppid;
srinfo->sinfo_context = cmsgs->srinfo->sinfo_context;
srinfo->sinfo_assoc_id = cmsgs->srinfo->sinfo_assoc_id;
srinfo->sinfo_timetolive = cmsgs->srinfo->sinfo_timetolive;
}
if (cmsgs->sinfo) {
srinfo->sinfo_stream = cmsgs->sinfo->snd_sid;
srinfo->sinfo_flags = cmsgs->sinfo->snd_flags;
srinfo->sinfo_ppid = cmsgs->sinfo->snd_ppid;
srinfo->sinfo_context = cmsgs->sinfo->snd_context;
srinfo->sinfo_assoc_id = cmsgs->sinfo->snd_assoc_id;
}
if (cmsgs->prinfo) {
srinfo->sinfo_timetolive = cmsgs->prinfo->pr_value;
SCTP_PR_SET_POLICY(srinfo->sinfo_flags,
cmsgs->prinfo->pr_policy);
}
sflags = srinfo->sinfo_flags;
if (!sflags && msg_len)
return 0;
if (sctp_style(sk, TCP) && (sflags & (SCTP_EOF | SCTP_ABORT)))
return -EINVAL;
if (((sflags & SCTP_EOF) && msg_len > 0) ||
(!(sflags & (SCTP_EOF | SCTP_ABORT)) && msg_len == 0))
return -EINVAL;
if ((sflags & SCTP_ADDR_OVER) && !msg->msg_name)
return -EINVAL;
return 0;
}
static int sctp_sendmsg_new_asoc(struct sock *sk, __u16 sflags,
struct sctp_cmsgs *cmsgs,
union sctp_addr *daddr,
struct sctp_transport **tp)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct sctp_association *asoc;
struct cmsghdr *cmsg;
__be32 flowinfo = 0;
struct sctp_af *af;
int err;
*tp = NULL;
if (sflags & (SCTP_EOF | SCTP_ABORT))
return -EINVAL;
if (sctp_style(sk, TCP) && (sctp_sstate(sk, ESTABLISHED) ||
sctp_sstate(sk, CLOSING)))
return -EADDRNOTAVAIL;
/* Label connection socket for first association 1-to-many
* style for client sequence socket()->sendmsg(). This
* needs to be done before sctp_assoc_add_peer() as that will
* set up the initial packet that needs to account for any
* security ip options (CIPSO/CALIPSO) added to the packet.
*/
af = sctp_get_af_specific(daddr->sa.sa_family);
if (!af)
return -EINVAL;
err = security_sctp_bind_connect(sk, SCTP_SENDMSG_CONNECT,
(struct sockaddr *)daddr,
af->sockaddr_len);
if (err < 0)
return err;
err = sctp_connect_new_asoc(ep, daddr, cmsgs->init, tp);
if (err)
return err;
asoc = (*tp)->asoc;
if (!cmsgs->addrs_msg)
return 0;
if (daddr->sa.sa_family == AF_INET6)
flowinfo = daddr->v6.sin6_flowinfo;
/* sendv addr list parse */
for_each_cmsghdr(cmsg, cmsgs->addrs_msg) {
union sctp_addr _daddr;
int dlen;
if (cmsg->cmsg_level != IPPROTO_SCTP ||
(cmsg->cmsg_type != SCTP_DSTADDRV4 &&
cmsg->cmsg_type != SCTP_DSTADDRV6))
continue;
daddr = &_daddr;
memset(daddr, 0, sizeof(*daddr));
dlen = cmsg->cmsg_len - sizeof(struct cmsghdr);
if (cmsg->cmsg_type == SCTP_DSTADDRV4) {
if (dlen < sizeof(struct in_addr)) {
err = -EINVAL;
goto free;
}
dlen = sizeof(struct in_addr);
daddr->v4.sin_family = AF_INET;
daddr->v4.sin_port = htons(asoc->peer.port);
memcpy(&daddr->v4.sin_addr, CMSG_DATA(cmsg), dlen);
} else {
if (dlen < sizeof(struct in6_addr)) {
err = -EINVAL;
goto free;
}
dlen = sizeof(struct in6_addr);
daddr->v6.sin6_flowinfo = flowinfo;
daddr->v6.sin6_family = AF_INET6;
daddr->v6.sin6_port = htons(asoc->peer.port);
memcpy(&daddr->v6.sin6_addr, CMSG_DATA(cmsg), dlen);
}
err = sctp_connect_add_peer(asoc, daddr, sizeof(*daddr));
if (err)
goto free;
}
return 0;
free:
sctp_association_free(asoc);
return err;
}
static int sctp_sendmsg_check_sflags(struct sctp_association *asoc,
__u16 sflags, struct msghdr *msg,
size_t msg_len)
{
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP))
return -EPIPE;
if ((sflags & SCTP_SENDALL) && sctp_style(sk, UDP) &&
!sctp_state(asoc, ESTABLISHED))
return 0;
if (sflags & SCTP_EOF) {
pr_debug("%s: shutting down association:%p\n", __func__, asoc);
sctp_primitive_SHUTDOWN(net, asoc, NULL);
return 0;
}
if (sflags & SCTP_ABORT) {
struct sctp_chunk *chunk;
chunk = sctp_make_abort_user(asoc, msg, msg_len);
if (!chunk)
return -ENOMEM;
pr_debug("%s: aborting association:%p\n", __func__, asoc);
sctp_primitive_ABORT(net, asoc, chunk);
iov_iter_revert(&msg->msg_iter, msg_len);
return 0;
}
return 1;
}
static int sctp_sendmsg_to_asoc(struct sctp_association *asoc,
struct msghdr *msg, size_t msg_len,
struct sctp_transport *transport,
struct sctp_sndrcvinfo *sinfo)
{
struct sock *sk = asoc->base.sk;
struct sctp_sock *sp = sctp_sk(sk);
struct net *net = sock_net(sk);
struct sctp_datamsg *datamsg;
bool wait_connect = false;
struct sctp_chunk *chunk;
long timeo;
int err;
if (sinfo->sinfo_stream >= asoc->stream.outcnt) {
err = -EINVAL;
goto err;
}
if (unlikely(!SCTP_SO(&asoc->stream, sinfo->sinfo_stream)->ext)) {
err = sctp_stream_init_ext(&asoc->stream, sinfo->sinfo_stream);
if (err)
goto err;
}
if (sp->disable_fragments && msg_len > asoc->frag_point) {
err = -EMSGSIZE;
goto err;
}
if (asoc->pmtu_pending) {
if (sp->param_flags & SPP_PMTUD_ENABLE)
sctp_assoc_sync_pmtu(asoc);
asoc->pmtu_pending = 0;
}
if (sctp_wspace(asoc) < (int)msg_len)
sctp_prsctp_prune(asoc, sinfo, msg_len - sctp_wspace(asoc));
if (sctp_wspace(asoc) <= 0 || !sk_wmem_schedule(sk, msg_len)) {
timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
err = sctp_wait_for_sndbuf(asoc, &timeo, msg_len);
if (err)
goto err;
if (unlikely(sinfo->sinfo_stream >= asoc->stream.outcnt)) {
err = -EINVAL;
goto err;
}
}
if (sctp_state(asoc, CLOSED)) {
err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
if (err)
goto err;
if (asoc->ep->intl_enable) {
timeo = sock_sndtimeo(sk, 0);
err = sctp_wait_for_connect(asoc, &timeo);
if (err) {
err = -ESRCH;
goto err;
}
} else {
wait_connect = true;
}
pr_debug("%s: we associated primitively\n", __func__);
}
datamsg = sctp_datamsg_from_user(asoc, sinfo, &msg->msg_iter);
if (IS_ERR(datamsg)) {
err = PTR_ERR(datamsg);
goto err;
}
asoc->force_delay = !!(msg->msg_flags & MSG_MORE);
list_for_each_entry(chunk, &datamsg->chunks, frag_list) {
sctp_chunk_hold(chunk);
sctp_set_owner_w(chunk);
chunk->transport = transport;
}
err = sctp_primitive_SEND(net, asoc, datamsg);
if (err) {
sctp_datamsg_free(datamsg);
goto err;
}
pr_debug("%s: we sent primitively\n", __func__);
sctp_datamsg_put(datamsg);
if (unlikely(wait_connect)) {
timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
sctp_wait_for_connect(asoc, &timeo);
}
err = msg_len;
err:
return err;
}
static union sctp_addr *sctp_sendmsg_get_daddr(struct sock *sk,
const struct msghdr *msg,
struct sctp_cmsgs *cmsgs)
{
union sctp_addr *daddr = NULL;
int err;
if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) {
int len = msg->msg_namelen;
if (len > sizeof(*daddr))
len = sizeof(*daddr);
daddr = (union sctp_addr *)msg->msg_name;
err = sctp_verify_addr(sk, daddr, len);
if (err)
return ERR_PTR(err);
}
return daddr;
}
static void sctp_sendmsg_update_sinfo(struct sctp_association *asoc,
struct sctp_sndrcvinfo *sinfo,
struct sctp_cmsgs *cmsgs)
{
if (!cmsgs->srinfo && !cmsgs->sinfo) {
sinfo->sinfo_stream = asoc->default_stream;
sinfo->sinfo_ppid = asoc->default_ppid;
sinfo->sinfo_context = asoc->default_context;
sinfo->sinfo_assoc_id = sctp_assoc2id(asoc);
if (!cmsgs->prinfo)
sinfo->sinfo_flags = asoc->default_flags;
}
if (!cmsgs->srinfo && !cmsgs->prinfo)
sinfo->sinfo_timetolive = asoc->default_timetolive;
if (cmsgs->authinfo) {
/* Reuse sinfo_tsn to indicate that authinfo was set and
* sinfo_ssn to save the keyid on tx path.
*/
sinfo->sinfo_tsn = 1;
sinfo->sinfo_ssn = cmsgs->authinfo->auth_keynumber;
}
}
static int sctp_sendmsg(struct sock *sk, struct msghdr *msg, size_t msg_len)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct sctp_transport *transport = NULL;
struct sctp_sndrcvinfo _sinfo, *sinfo;
struct sctp_association *asoc, *tmp;
struct sctp_cmsgs cmsgs;
union sctp_addr *daddr;
bool new = false;
__u16 sflags;
int err;
/* Parse and get snd_info */
err = sctp_sendmsg_parse(sk, &cmsgs, &_sinfo, msg, msg_len);
if (err)
goto out;
sinfo = &_sinfo;
sflags = sinfo->sinfo_flags;
/* Get daddr from msg */
daddr = sctp_sendmsg_get_daddr(sk, msg, &cmsgs);
if (IS_ERR(daddr)) {
err = PTR_ERR(daddr);
goto out;
}
lock_sock(sk);
/* SCTP_SENDALL process */
if ((sflags & SCTP_SENDALL) && sctp_style(sk, UDP)) {
list_for_each_entry_safe(asoc, tmp, &ep->asocs, asocs) {
err = sctp_sendmsg_check_sflags(asoc, sflags, msg,
msg_len);
if (err == 0)
continue;
if (err < 0)
goto out_unlock;
sctp_sendmsg_update_sinfo(asoc, sinfo, &cmsgs);
err = sctp_sendmsg_to_asoc(asoc, msg, msg_len,
NULL, sinfo);
if (err < 0)
goto out_unlock;
iov_iter_revert(&msg->msg_iter, err);
}
goto out_unlock;
}
/* Get and check or create asoc */
if (daddr) {
asoc = sctp_endpoint_lookup_assoc(ep, daddr, &transport);
if (asoc) {
err = sctp_sendmsg_check_sflags(asoc, sflags, msg,
msg_len);
if (err <= 0)
goto out_unlock;
} else {
err = sctp_sendmsg_new_asoc(sk, sflags, &cmsgs, daddr,
&transport);
if (err)
goto out_unlock;
asoc = transport->asoc;
new = true;
}
if (!sctp_style(sk, TCP) && !(sflags & SCTP_ADDR_OVER))
transport = NULL;
} else {
asoc = sctp_id2assoc(sk, sinfo->sinfo_assoc_id);
if (!asoc) {
err = -EPIPE;
goto out_unlock;
}
err = sctp_sendmsg_check_sflags(asoc, sflags, msg, msg_len);
if (err <= 0)
goto out_unlock;
}
/* Update snd_info with the asoc */
sctp_sendmsg_update_sinfo(asoc, sinfo, &cmsgs);
/* Send msg to the asoc */
err = sctp_sendmsg_to_asoc(asoc, msg, msg_len, transport, sinfo);
if (err < 0 && err != -ESRCH && new)
sctp_association_free(asoc);
out_unlock:
release_sock(sk);
out:
return sctp_error(sk, msg->msg_flags, err);
}
/* This is an extended version of skb_pull() that removes the data from the
* start of a skb even when data is spread across the list of skb's in the
* frag_list. len specifies the total amount of data that needs to be removed.
* when 'len' bytes could be removed from the skb, it returns 0.
* If 'len' exceeds the total skb length, it returns the no. of bytes that
* could not be removed.
*/
static int sctp_skb_pull(struct sk_buff *skb, int len)
{
struct sk_buff *list;
int skb_len = skb_headlen(skb);
int rlen;
if (len <= skb_len) {
__skb_pull(skb, len);
return 0;
}
len -= skb_len;
__skb_pull(skb, skb_len);
skb_walk_frags(skb, list) {
rlen = sctp_skb_pull(list, len);
skb->len -= (len-rlen);
skb->data_len -= (len-rlen);
if (!rlen)
return 0;
len = rlen;
}
return len;
}
/* API 3.1.3 recvmsg() - UDP Style Syntax
*
* ssize_t recvmsg(int socket, struct msghdr *message,
* int flags);
*
* socket - the socket descriptor of the endpoint.
* message - pointer to the msghdr structure which contains a single
* user message and possibly some ancillary data.
*
* See Section 5 for complete description of the data
* structures.
*
* flags - flags sent or received with the user message, see Section
* 5 for complete description of the flags.
*/
static int sctp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
int flags, int *addr_len)
{
struct sctp_ulpevent *event = NULL;
struct sctp_sock *sp = sctp_sk(sk);
struct sk_buff *skb, *head_skb;
int copied;
int err = 0;
int skb_len;
pr_debug("%s: sk:%p, msghdr:%p, len:%zd, flags:0x%x, addr_len:%p)\n",
__func__, sk, msg, len, flags, addr_len);
lock_sock(sk);
if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED) &&
!sctp_sstate(sk, CLOSING) && !sctp_sstate(sk, CLOSED)) {
err = -ENOTCONN;
goto out;
}
skb = sctp_skb_recv_datagram(sk, flags, &err);
if (!skb)
goto out;
/* Get the total length of the skb including any skb's in the
* frag_list.
*/
skb_len = skb->len;
copied = skb_len;
if (copied > len)
copied = len;
err = skb_copy_datagram_msg(skb, 0, msg, copied);
event = sctp_skb2event(skb);
if (err)
goto out_free;
if (event->chunk && event->chunk->head_skb)
head_skb = event->chunk->head_skb;
else
head_skb = skb;
sock_recv_cmsgs(msg, sk, head_skb);
if (sctp_ulpevent_is_notification(event)) {
msg->msg_flags |= MSG_NOTIFICATION;
sp->pf->event_msgname(event, msg->msg_name, addr_len);
} else {
sp->pf->skb_msgname(head_skb, msg->msg_name, addr_len);
}
/* Check if we allow SCTP_NXTINFO. */
if (sp->recvnxtinfo)
sctp_ulpevent_read_nxtinfo(event, msg, sk);
/* Check if we allow SCTP_RCVINFO. */
if (sp->recvrcvinfo)
sctp_ulpevent_read_rcvinfo(event, msg);
/* Check if we allow SCTP_SNDRCVINFO. */
if (sctp_ulpevent_type_enabled(sp->subscribe, SCTP_DATA_IO_EVENT))
sctp_ulpevent_read_sndrcvinfo(event, msg);
err = copied;
/* If skb's length exceeds the user's buffer, update the skb and
* push it back to the receive_queue so that the next call to
* recvmsg() will return the remaining data. Don't set MSG_EOR.
*/
if (skb_len > copied) {
msg->msg_flags &= ~MSG_EOR;
if (flags & MSG_PEEK)
goto out_free;
sctp_skb_pull(skb, copied);
skb_queue_head(&sk->sk_receive_queue, skb);
/* When only partial message is copied to the user, increase
* rwnd by that amount. If all the data in the skb is read,
* rwnd is updated when the event is freed.
*/
if (!sctp_ulpevent_is_notification(event))
sctp_assoc_rwnd_increase(event->asoc, copied);
goto out;
} else if ((event->msg_flags & MSG_NOTIFICATION) ||
(event->msg_flags & MSG_EOR))
msg->msg_flags |= MSG_EOR;
else
msg->msg_flags &= ~MSG_EOR;
out_free:
if (flags & MSG_PEEK) {
/* Release the skb reference acquired after peeking the skb in
* sctp_skb_recv_datagram().
*/
kfree_skb(skb);
} else {
/* Free the event which includes releasing the reference to
* the owner of the skb, freeing the skb and updating the
* rwnd.
*/
sctp_ulpevent_free(event);
}
out:
release_sock(sk);
return err;
}
/* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
*
* This option is a on/off flag. If enabled no SCTP message
* fragmentation will be performed. Instead if a message being sent
* exceeds the current PMTU size, the message will NOT be sent and
* instead a error will be indicated to the user.
*/
static int sctp_setsockopt_disable_fragments(struct sock *sk, int *val,
unsigned int optlen)
{
if (optlen < sizeof(int))
return -EINVAL;
sctp_sk(sk)->disable_fragments = (*val == 0) ? 0 : 1;
return 0;
}
static int sctp_setsockopt_events(struct sock *sk, __u8 *sn_type,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
int i;
if (optlen > sizeof(struct sctp_event_subscribe))
return -EINVAL;
for (i = 0; i < optlen; i++)
sctp_ulpevent_type_set(&sp->subscribe, SCTP_SN_TYPE_BASE + i,
sn_type[i]);
list_for_each_entry(asoc, &sp->ep->asocs, asocs)
asoc->subscribe = sctp_sk(sk)->subscribe;
/* At the time when a user app subscribes to SCTP_SENDER_DRY_EVENT,
* if there is no data to be sent or retransmit, the stack will
* immediately send up this notification.
*/
if (sctp_ulpevent_type_enabled(sp->subscribe, SCTP_SENDER_DRY_EVENT)) {
struct sctp_ulpevent *event;
asoc = sctp_id2assoc(sk, 0);
if (asoc && sctp_outq_is_empty(&asoc->outqueue)) {
event = sctp_ulpevent_make_sender_dry_event(asoc,
GFP_USER | __GFP_NOWARN);
if (!event)
return -ENOMEM;
asoc->stream.si->enqueue_event(&asoc->ulpq, event);
}
}
return 0;
}
/* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
*
* This socket option is applicable to the UDP-style socket only. When
* set it will cause associations that are idle for more than the
* specified number of seconds to automatically close. An association
* being idle is defined an association that has NOT sent or received
* user data. The special value of '0' indicates that no automatic
* close of any associations should be performed. The option expects an
* integer defining the number of seconds of idle time before an
* association is closed.
*/
static int sctp_setsockopt_autoclose(struct sock *sk, u32 *optval,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct net *net = sock_net(sk);
/* Applicable to UDP-style socket only */
if (sctp_style(sk, TCP))
return -EOPNOTSUPP;
if (optlen != sizeof(int))
return -EINVAL;
sp->autoclose = *optval;
if (sp->autoclose > net->sctp.max_autoclose)
sp->autoclose = net->sctp.max_autoclose;
return 0;
}
/* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
*
* Applications can enable or disable heartbeats for any peer address of
* an association, modify an address's heartbeat interval, force a
* heartbeat to be sent immediately, and adjust the address's maximum
* number of retransmissions sent before an address is considered
* unreachable. The following structure is used to access and modify an
* address's parameters:
*
* struct sctp_paddrparams {
* sctp_assoc_t spp_assoc_id;
* struct sockaddr_storage spp_address;
* uint32_t spp_hbinterval;
* uint16_t spp_pathmaxrxt;
* uint32_t spp_pathmtu;
* uint32_t spp_sackdelay;
* uint32_t spp_flags;
* uint32_t spp_ipv6_flowlabel;
* uint8_t spp_dscp;
* };
*
* spp_assoc_id - (one-to-many style socket) This is filled in the
* application, and identifies the association for
* this query.
* spp_address - This specifies which address is of interest.
* spp_hbinterval - This contains the value of the heartbeat interval,
* in milliseconds. If a value of zero
* is present in this field then no changes are to
* be made to this parameter.
* spp_pathmaxrxt - This contains the maximum number of
* retransmissions before this address shall be
* considered unreachable. If a value of zero
* is present in this field then no changes are to
* be made to this parameter.
* spp_pathmtu - When Path MTU discovery is disabled the value
* specified here will be the "fixed" path mtu.
* Note that if the spp_address field is empty
* then all associations on this address will
* have this fixed path mtu set upon them.
*
* spp_sackdelay - When delayed sack is enabled, this value specifies
* the number of milliseconds that sacks will be delayed
* for. This value will apply to all addresses of an
* association if the spp_address field is empty. Note
* also, that if delayed sack is enabled and this
* value is set to 0, no change is made to the last
* recorded delayed sack timer value.
*
* spp_flags - These flags are used to control various features
* on an association. The flag field may contain
* zero or more of the following options.
*
* SPP_HB_ENABLE - Enable heartbeats on the
* specified address. Note that if the address
* field is empty all addresses for the association
* have heartbeats enabled upon them.
*
* SPP_HB_DISABLE - Disable heartbeats on the
* speicifed address. Note that if the address
* field is empty all addresses for the association
* will have their heartbeats disabled. Note also
* that SPP_HB_ENABLE and SPP_HB_DISABLE are
* mutually exclusive, only one of these two should
* be specified. Enabling both fields will have
* undetermined results.
*
* SPP_HB_DEMAND - Request a user initiated heartbeat
* to be made immediately.
*
* SPP_HB_TIME_IS_ZERO - Specify's that the time for
* heartbeat delayis to be set to the value of 0
* milliseconds.
*
* SPP_PMTUD_ENABLE - This field will enable PMTU
* discovery upon the specified address. Note that
* if the address feild is empty then all addresses
* on the association are effected.
*
* SPP_PMTUD_DISABLE - This field will disable PMTU
* discovery upon the specified address. Note that
* if the address feild is empty then all addresses
* on the association are effected. Not also that
* SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
* exclusive. Enabling both will have undetermined
* results.
*
* SPP_SACKDELAY_ENABLE - Setting this flag turns
* on delayed sack. The time specified in spp_sackdelay
* is used to specify the sack delay for this address. Note
* that if spp_address is empty then all addresses will
* enable delayed sack and take on the sack delay
* value specified in spp_sackdelay.
* SPP_SACKDELAY_DISABLE - Setting this flag turns
* off delayed sack. If the spp_address field is blank then
* delayed sack is disabled for the entire association. Note
* also that this field is mutually exclusive to
* SPP_SACKDELAY_ENABLE, setting both will have undefined
* results.
*
* SPP_IPV6_FLOWLABEL: Setting this flag enables the
* setting of the IPV6 flow label value. The value is
* contained in the spp_ipv6_flowlabel field.
* Upon retrieval, this flag will be set to indicate that
* the spp_ipv6_flowlabel field has a valid value returned.
* If a specific destination address is set (in the
* spp_address field), then the value returned is that of
* the address. If just an association is specified (and
* no address), then the association's default flow label
* is returned. If neither an association nor a destination
* is specified, then the socket's default flow label is
* returned. For non-IPv6 sockets, this flag will be left
* cleared.
*
* SPP_DSCP: Setting this flag enables the setting of the
* Differentiated Services Code Point (DSCP) value
* associated with either the association or a specific
* address. The value is obtained in the spp_dscp field.
* Upon retrieval, this flag will be set to indicate that
* the spp_dscp field has a valid value returned. If a
* specific destination address is set when called (in the
* spp_address field), then that specific destination
* address's DSCP value is returned. If just an association
* is specified, then the association's default DSCP is
* returned. If neither an association nor a destination is
* specified, then the socket's default DSCP is returned.
*
* spp_ipv6_flowlabel
* - This field is used in conjunction with the
* SPP_IPV6_FLOWLABEL flag and contains the IPv6 flow label.
* The 20 least significant bits are used for the flow
* label. This setting has precedence over any IPv6-layer
* setting.
*
* spp_dscp - This field is used in conjunction with the SPP_DSCP flag
* and contains the DSCP. The 6 most significant bits are
* used for the DSCP. This setting has precedence over any
* IPv4- or IPv6- layer setting.
*/
static int sctp_apply_peer_addr_params(struct sctp_paddrparams *params,
struct sctp_transport *trans,
struct sctp_association *asoc,
struct sctp_sock *sp,
int hb_change,
int pmtud_change,
int sackdelay_change)
{
int error;
if (params->spp_flags & SPP_HB_DEMAND && trans) {
error = sctp_primitive_REQUESTHEARTBEAT(trans->asoc->base.net,
trans->asoc, trans);
if (error)
return error;
}
/* Note that unless the spp_flag is set to SPP_HB_ENABLE the value of
* this field is ignored. Note also that a value of zero indicates
* the current setting should be left unchanged.
*/
if (params->spp_flags & SPP_HB_ENABLE) {
/* Re-zero the interval if the SPP_HB_TIME_IS_ZERO is
* set. This lets us use 0 value when this flag
* is set.
*/
if (params->spp_flags & SPP_HB_TIME_IS_ZERO)
params->spp_hbinterval = 0;
if (params->spp_hbinterval ||
(params->spp_flags & SPP_HB_TIME_IS_ZERO)) {
if (trans) {
trans->hbinterval =
msecs_to_jiffies(params->spp_hbinterval);
} else if (asoc) {
asoc->hbinterval =
msecs_to_jiffies(params->spp_hbinterval);
} else {
sp->hbinterval = params->spp_hbinterval;
}
}
}
if (hb_change) {
if (trans) {
trans->param_flags =
(trans->param_flags & ~SPP_HB) | hb_change;
} else if (asoc) {
asoc->param_flags =
(asoc->param_flags & ~SPP_HB) | hb_change;
} else {
sp->param_flags =
(sp->param_flags & ~SPP_HB) | hb_change;
}
}
/* When Path MTU discovery is disabled the value specified here will
* be the "fixed" path mtu (i.e. the value of the spp_flags field must
* include the flag SPP_PMTUD_DISABLE for this field to have any
* effect).
*/
if ((params->spp_flags & SPP_PMTUD_DISABLE) && params->spp_pathmtu) {
if (trans) {
trans->pathmtu = params->spp_pathmtu;
sctp_assoc_sync_pmtu(asoc);
} else if (asoc) {
sctp_assoc_set_pmtu(asoc, params->spp_pathmtu);
} else {
sp->pathmtu = params->spp_pathmtu;
}
}
if (pmtud_change) {
if (trans) {
int update = (trans->param_flags & SPP_PMTUD_DISABLE) &&
(params->spp_flags & SPP_PMTUD_ENABLE);
trans->param_flags =
(trans->param_flags & ~SPP_PMTUD) | pmtud_change;
if (update) {
sctp_transport_pmtu(trans, sctp_opt2sk(sp));
sctp_assoc_sync_pmtu(asoc);
}
sctp_transport_pl_reset(trans);
} else if (asoc) {
asoc->param_flags =
(asoc->param_flags & ~SPP_PMTUD) | pmtud_change;
} else {
sp->param_flags =
(sp->param_flags & ~SPP_PMTUD) | pmtud_change;
}
}
/* Note that unless the spp_flag is set to SPP_SACKDELAY_ENABLE the
* value of this field is ignored. Note also that a value of zero
* indicates the current setting should be left unchanged.
*/
if ((params->spp_flags & SPP_SACKDELAY_ENABLE) && params->spp_sackdelay) {
if (trans) {
trans->sackdelay =
msecs_to_jiffies(params->spp_sackdelay);
} else if (asoc) {
asoc->sackdelay =
msecs_to_jiffies(params->spp_sackdelay);
} else {
sp->sackdelay = params->spp_sackdelay;
}
}
if (sackdelay_change) {
if (trans) {
trans->param_flags =
(trans->param_flags & ~SPP_SACKDELAY) |
sackdelay_change;
} else if (asoc) {
asoc->param_flags =
(asoc->param_flags & ~SPP_SACKDELAY) |
sackdelay_change;
} else {
sp->param_flags =
(sp->param_flags & ~SPP_SACKDELAY) |
sackdelay_change;
}
}
/* Note that a value of zero indicates the current setting should be
left unchanged.
*/
if (params->spp_pathmaxrxt) {
if (trans) {
trans->pathmaxrxt = params->spp_pathmaxrxt;
} else if (asoc) {
asoc->pathmaxrxt = params->spp_pathmaxrxt;
} else {
sp->pathmaxrxt = params->spp_pathmaxrxt;
}
}
if (params->spp_flags & SPP_IPV6_FLOWLABEL) {
if (trans) {
if (trans->ipaddr.sa.sa_family == AF_INET6) {
trans->flowlabel = params->spp_ipv6_flowlabel &
SCTP_FLOWLABEL_VAL_MASK;
trans->flowlabel |= SCTP_FLOWLABEL_SET_MASK;
}
} else if (asoc) {
struct sctp_transport *t;
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
if (t->ipaddr.sa.sa_family != AF_INET6)
continue;
t->flowlabel = params->spp_ipv6_flowlabel &
SCTP_FLOWLABEL_VAL_MASK;
t->flowlabel |= SCTP_FLOWLABEL_SET_MASK;
}
asoc->flowlabel = params->spp_ipv6_flowlabel &
SCTP_FLOWLABEL_VAL_MASK;
asoc->flowlabel |= SCTP_FLOWLABEL_SET_MASK;
} else if (sctp_opt2sk(sp)->sk_family == AF_INET6) {
sp->flowlabel = params->spp_ipv6_flowlabel &
SCTP_FLOWLABEL_VAL_MASK;
sp->flowlabel |= SCTP_FLOWLABEL_SET_MASK;
}
}
if (params->spp_flags & SPP_DSCP) {
if (trans) {
trans->dscp = params->spp_dscp & SCTP_DSCP_VAL_MASK;
trans->dscp |= SCTP_DSCP_SET_MASK;
} else if (asoc) {
struct sctp_transport *t;
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
t->dscp = params->spp_dscp &
SCTP_DSCP_VAL_MASK;
t->dscp |= SCTP_DSCP_SET_MASK;
}
asoc->dscp = params->spp_dscp & SCTP_DSCP_VAL_MASK;
asoc->dscp |= SCTP_DSCP_SET_MASK;
} else {
sp->dscp = params->spp_dscp & SCTP_DSCP_VAL_MASK;
sp->dscp |= SCTP_DSCP_SET_MASK;
}
}
return 0;
}
static int sctp_setsockopt_peer_addr_params(struct sock *sk,
struct sctp_paddrparams *params,
unsigned int optlen)
{
struct sctp_transport *trans = NULL;
struct sctp_association *asoc = NULL;
struct sctp_sock *sp = sctp_sk(sk);
int error;
int hb_change, pmtud_change, sackdelay_change;
if (optlen == ALIGN(offsetof(struct sctp_paddrparams,
spp_ipv6_flowlabel), 4)) {
if (params->spp_flags & (SPP_DSCP | SPP_IPV6_FLOWLABEL))
return -EINVAL;
} else if (optlen != sizeof(*params)) {
return -EINVAL;
}
/* Validate flags and value parameters. */
hb_change = params->spp_flags & SPP_HB;
pmtud_change = params->spp_flags & SPP_PMTUD;
sackdelay_change = params->spp_flags & SPP_SACKDELAY;
if (hb_change == SPP_HB ||
pmtud_change == SPP_PMTUD ||
sackdelay_change == SPP_SACKDELAY ||
params->spp_sackdelay > 500 ||
(params->spp_pathmtu &&
params->spp_pathmtu < SCTP_DEFAULT_MINSEGMENT))
return -EINVAL;
/* If an address other than INADDR_ANY is specified, and
* no transport is found, then the request is invalid.
*/
if (!sctp_is_any(sk, (union sctp_addr *)¶ms->spp_address)) {
trans = sctp_addr_id2transport(sk, ¶ms->spp_address,
params->spp_assoc_id);
if (!trans)
return -EINVAL;
}
/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
* socket is a one to many style socket, and an association
* was not found, then the id was invalid.
*/
asoc = sctp_id2assoc(sk, params->spp_assoc_id);
if (!asoc && params->spp_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
/* Heartbeat demand can only be sent on a transport or
* association, but not a socket.
*/
if (params->spp_flags & SPP_HB_DEMAND && !trans && !asoc)
return -EINVAL;
/* Process parameters. */
error = sctp_apply_peer_addr_params(params, trans, asoc, sp,
hb_change, pmtud_change,
sackdelay_change);
if (error)
return error;
/* If changes are for association, also apply parameters to each
* transport.
*/
if (!trans && asoc) {
list_for_each_entry(trans, &asoc->peer.transport_addr_list,
transports) {
sctp_apply_peer_addr_params(params, trans, asoc, sp,
hb_change, pmtud_change,
sackdelay_change);
}
}
return 0;
}
static inline __u32 sctp_spp_sackdelay_enable(__u32 param_flags)
{
return (param_flags & ~SPP_SACKDELAY) | SPP_SACKDELAY_ENABLE;
}
static inline __u32 sctp_spp_sackdelay_disable(__u32 param_flags)
{
return (param_flags & ~SPP_SACKDELAY) | SPP_SACKDELAY_DISABLE;
}
static void sctp_apply_asoc_delayed_ack(struct sctp_sack_info *params,
struct sctp_association *asoc)
{
struct sctp_transport *trans;
if (params->sack_delay) {
asoc->sackdelay = msecs_to_jiffies(params->sack_delay);
asoc->param_flags =
sctp_spp_sackdelay_enable(asoc->param_flags);
}
if (params->sack_freq == 1) {
asoc->param_flags =
sctp_spp_sackdelay_disable(asoc->param_flags);
} else if (params->sack_freq > 1) {
asoc->sackfreq = params->sack_freq;
asoc->param_flags =
sctp_spp_sackdelay_enable(asoc->param_flags);
}
list_for_each_entry(trans, &asoc->peer.transport_addr_list,
transports) {
if (params->sack_delay) {
trans->sackdelay = msecs_to_jiffies(params->sack_delay);
trans->param_flags =
sctp_spp_sackdelay_enable(trans->param_flags);
}
if (params->sack_freq == 1) {
trans->param_flags =
sctp_spp_sackdelay_disable(trans->param_flags);
} else if (params->sack_freq > 1) {
trans->sackfreq = params->sack_freq;
trans->param_flags =
sctp_spp_sackdelay_enable(trans->param_flags);
}
}
}
/*
* 7.1.23. Get or set delayed ack timer (SCTP_DELAYED_SACK)
*
* This option will effect the way delayed acks are performed. This
* option allows you to get or set the delayed ack time, in
* milliseconds. It also allows changing the delayed ack frequency.
* Changing the frequency to 1 disables the delayed sack algorithm. If
* the assoc_id is 0, then this sets or gets the endpoints default
* values. If the assoc_id field is non-zero, then the set or get
* effects the specified association for the one to many model (the
* assoc_id field is ignored by the one to one model). Note that if
* sack_delay or sack_freq are 0 when setting this option, then the
* current values will remain unchanged.
*
* struct sctp_sack_info {
* sctp_assoc_t sack_assoc_id;
* uint32_t sack_delay;
* uint32_t sack_freq;
* };
*
* sack_assoc_id - This parameter, indicates which association the user
* is performing an action upon. Note that if this field's value is
* zero then the endpoints default value is changed (effecting future
* associations only).
*
* sack_delay - This parameter contains the number of milliseconds that
* the user is requesting the delayed ACK timer be set to. Note that
* this value is defined in the standard to be between 200 and 500
* milliseconds.
*
* sack_freq - This parameter contains the number of packets that must
* be received before a sack is sent without waiting for the delay
* timer to expire. The default value for this is 2, setting this
* value to 1 will disable the delayed sack algorithm.
*/
static int __sctp_setsockopt_delayed_ack(struct sock *sk,
struct sctp_sack_info *params)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
/* Validate value parameter. */
if (params->sack_delay > 500)
return -EINVAL;
/* Get association, if sack_assoc_id != SCTP_FUTURE_ASSOC and the
* socket is a one to many style socket, and an association
* was not found, then the id was invalid.
*/
asoc = sctp_id2assoc(sk, params->sack_assoc_id);
if (!asoc && params->sack_assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
sctp_apply_asoc_delayed_ack(params, asoc);
return 0;
}
if (sctp_style(sk, TCP))
params->sack_assoc_id = SCTP_FUTURE_ASSOC;
if (params->sack_assoc_id == SCTP_FUTURE_ASSOC ||
params->sack_assoc_id == SCTP_ALL_ASSOC) {
if (params->sack_delay) {
sp->sackdelay = params->sack_delay;
sp->param_flags =
sctp_spp_sackdelay_enable(sp->param_flags);
}
if (params->sack_freq == 1) {
sp->param_flags =
sctp_spp_sackdelay_disable(sp->param_flags);
} else if (params->sack_freq > 1) {
sp->sackfreq = params->sack_freq;
sp->param_flags =
sctp_spp_sackdelay_enable(sp->param_flags);
}
}
if (params->sack_assoc_id == SCTP_CURRENT_ASSOC ||
params->sack_assoc_id == SCTP_ALL_ASSOC)
list_for_each_entry(asoc, &sp->ep->asocs, asocs)
sctp_apply_asoc_delayed_ack(params, asoc);
return 0;
}
static int sctp_setsockopt_delayed_ack(struct sock *sk,
struct sctp_sack_info *params,
unsigned int optlen)
{
if (optlen == sizeof(struct sctp_assoc_value)) {
struct sctp_assoc_value *v = (struct sctp_assoc_value *)params;
struct sctp_sack_info p;
pr_warn_ratelimited(DEPRECATED
"%s (pid %d) "
"Use of struct sctp_assoc_value in delayed_ack socket option.\n"
"Use struct sctp_sack_info instead\n",
current->comm, task_pid_nr(current));
p.sack_assoc_id = v->assoc_id;
p.sack_delay = v->assoc_value;
p.sack_freq = v->assoc_value ? 0 : 1;
return __sctp_setsockopt_delayed_ack(sk, &p);
}
if (optlen != sizeof(struct sctp_sack_info))
return -EINVAL;
if (params->sack_delay == 0 && params->sack_freq == 0)
return 0;
return __sctp_setsockopt_delayed_ack(sk, params);
}
/* 7.1.3 Initialization Parameters (SCTP_INITMSG)
*
* Applications can specify protocol parameters for the default association
* initialization. The option name argument to setsockopt() and getsockopt()
* is SCTP_INITMSG.
*
* Setting initialization parameters is effective only on an unconnected
* socket (for UDP-style sockets only future associations are effected
* by the change). With TCP-style sockets, this option is inherited by
* sockets derived from a listener socket.
*/
static int sctp_setsockopt_initmsg(struct sock *sk, struct sctp_initmsg *sinit,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
if (optlen != sizeof(struct sctp_initmsg))
return -EINVAL;
if (sinit->sinit_num_ostreams)
sp->initmsg.sinit_num_ostreams = sinit->sinit_num_ostreams;
if (sinit->sinit_max_instreams)
sp->initmsg.sinit_max_instreams = sinit->sinit_max_instreams;
if (sinit->sinit_max_attempts)
sp->initmsg.sinit_max_attempts = sinit->sinit_max_attempts;
if (sinit->sinit_max_init_timeo)
sp->initmsg.sinit_max_init_timeo = sinit->sinit_max_init_timeo;
return 0;
}
/*
* 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
*
* Applications that wish to use the sendto() system call may wish to
* specify a default set of parameters that would normally be supplied
* through the inclusion of ancillary data. This socket option allows
* such an application to set the default sctp_sndrcvinfo structure.
* The application that wishes to use this socket option simply passes
* in to this call the sctp_sndrcvinfo structure defined in Section
* 5.2.2) The input parameters accepted by this call include
* sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
* sinfo_timetolive. The user must provide the sinfo_assoc_id field in
* to this call if the caller is using the UDP model.
*/
static int sctp_setsockopt_default_send_param(struct sock *sk,
struct sctp_sndrcvinfo *info,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
if (optlen != sizeof(*info))
return -EINVAL;
if (info->sinfo_flags &
~(SCTP_UNORDERED | SCTP_ADDR_OVER |
SCTP_ABORT | SCTP_EOF))
return -EINVAL;
asoc = sctp_id2assoc(sk, info->sinfo_assoc_id);
if (!asoc && info->sinfo_assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
asoc->default_stream = info->sinfo_stream;
asoc->default_flags = info->sinfo_flags;
asoc->default_ppid = info->sinfo_ppid;
asoc->default_context = info->sinfo_context;
asoc->default_timetolive = info->sinfo_timetolive;
return 0;
}
if (sctp_style(sk, TCP))
info->sinfo_assoc_id = SCTP_FUTURE_ASSOC;
if (info->sinfo_assoc_id == SCTP_FUTURE_ASSOC ||
info->sinfo_assoc_id == SCTP_ALL_ASSOC) {
sp->default_stream = info->sinfo_stream;
sp->default_flags = info->sinfo_flags;
sp->default_ppid = info->sinfo_ppid;
sp->default_context = info->sinfo_context;
sp->default_timetolive = info->sinfo_timetolive;
}
if (info->sinfo_assoc_id == SCTP_CURRENT_ASSOC ||
info->sinfo_assoc_id == SCTP_ALL_ASSOC) {
list_for_each_entry(asoc, &sp->ep->asocs, asocs) {
asoc->default_stream = info->sinfo_stream;
asoc->default_flags = info->sinfo_flags;
asoc->default_ppid = info->sinfo_ppid;
asoc->default_context = info->sinfo_context;
asoc->default_timetolive = info->sinfo_timetolive;
}
}
return 0;
}
/* RFC6458, Section 8.1.31. Set/get Default Send Parameters
* (SCTP_DEFAULT_SNDINFO)
*/
static int sctp_setsockopt_default_sndinfo(struct sock *sk,
struct sctp_sndinfo *info,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
if (optlen != sizeof(*info))
return -EINVAL;
if (info->snd_flags &
~(SCTP_UNORDERED | SCTP_ADDR_OVER |
SCTP_ABORT | SCTP_EOF))
return -EINVAL;
asoc = sctp_id2assoc(sk, info->snd_assoc_id);
if (!asoc && info->snd_assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
asoc->default_stream = info->snd_sid;
asoc->default_flags = info->snd_flags;
asoc->default_ppid = info->snd_ppid;
asoc->default_context = info->snd_context;
return 0;
}
if (sctp_style(sk, TCP))
info->snd_assoc_id = SCTP_FUTURE_ASSOC;
if (info->snd_assoc_id == SCTP_FUTURE_ASSOC ||
info->snd_assoc_id == SCTP_ALL_ASSOC) {
sp->default_stream = info->snd_sid;
sp->default_flags = info->snd_flags;
sp->default_ppid = info->snd_ppid;
sp->default_context = info->snd_context;
}
if (info->snd_assoc_id == SCTP_CURRENT_ASSOC ||
info->snd_assoc_id == SCTP_ALL_ASSOC) {
list_for_each_entry(asoc, &sp->ep->asocs, asocs) {
asoc->default_stream = info->snd_sid;
asoc->default_flags = info->snd_flags;
asoc->default_ppid = info->snd_ppid;
asoc->default_context = info->snd_context;
}
}
return 0;
}
/* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
*
* Requests that the local SCTP stack use the enclosed peer address as
* the association primary. The enclosed address must be one of the
* association peer's addresses.
*/
static int sctp_setsockopt_primary_addr(struct sock *sk, struct sctp_prim *prim,
unsigned int optlen)
{
struct sctp_transport *trans;
struct sctp_af *af;
int err;
if (optlen != sizeof(struct sctp_prim))
return -EINVAL;
/* Allow security module to validate address but need address len. */
af = sctp_get_af_specific(prim->ssp_addr.ss_family);
if (!af)
return -EINVAL;
err = security_sctp_bind_connect(sk, SCTP_PRIMARY_ADDR,
(struct sockaddr *)&prim->ssp_addr,
af->sockaddr_len);
if (err)
return err;
trans = sctp_addr_id2transport(sk, &prim->ssp_addr, prim->ssp_assoc_id);
if (!trans)
return -EINVAL;
sctp_assoc_set_primary(trans->asoc, trans);
return 0;
}
/*
* 7.1.5 SCTP_NODELAY
*
* Turn on/off any Nagle-like algorithm. This means that packets are
* generally sent as soon as possible and no unnecessary delays are
* introduced, at the cost of more packets in the network. Expects an
* integer boolean flag.
*/
static int sctp_setsockopt_nodelay(struct sock *sk, int *val,
unsigned int optlen)
{
if (optlen < sizeof(int))
return -EINVAL;
sctp_sk(sk)->nodelay = (*val == 0) ? 0 : 1;
return 0;
}
/*
*
* 7.1.1 SCTP_RTOINFO
*
* The protocol parameters used to initialize and bound retransmission
* timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
* and modify these parameters.
* All parameters are time values, in milliseconds. A value of 0, when
* modifying the parameters, indicates that the current value should not
* be changed.
*
*/
static int sctp_setsockopt_rtoinfo(struct sock *sk,
struct sctp_rtoinfo *rtoinfo,
unsigned int optlen)
{
struct sctp_association *asoc;
unsigned long rto_min, rto_max;
struct sctp_sock *sp = sctp_sk(sk);
if (optlen != sizeof (struct sctp_rtoinfo))
return -EINVAL;
asoc = sctp_id2assoc(sk, rtoinfo->srto_assoc_id);
/* Set the values to the specific association */
if (!asoc && rtoinfo->srto_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
rto_max = rtoinfo->srto_max;
rto_min = rtoinfo->srto_min;
if (rto_max)
rto_max = asoc ? msecs_to_jiffies(rto_max) : rto_max;
else
rto_max = asoc ? asoc->rto_max : sp->rtoinfo.srto_max;
if (rto_min)
rto_min = asoc ? msecs_to_jiffies(rto_min) : rto_min;
else
rto_min = asoc ? asoc->rto_min : sp->rtoinfo.srto_min;
if (rto_min > rto_max)
return -EINVAL;
if (asoc) {
if (rtoinfo->srto_initial != 0)
asoc->rto_initial =
msecs_to_jiffies(rtoinfo->srto_initial);
asoc->rto_max = rto_max;
asoc->rto_min = rto_min;
} else {
/* If there is no association or the association-id = 0
* set the values to the endpoint.
*/
if (rtoinfo->srto_initial != 0)
sp->rtoinfo.srto_initial = rtoinfo->srto_initial;
sp->rtoinfo.srto_max = rto_max;
sp->rtoinfo.srto_min = rto_min;
}
return 0;
}
/*
*
* 7.1.2 SCTP_ASSOCINFO
*
* This option is used to tune the maximum retransmission attempts
* of the association.
* Returns an error if the new association retransmission value is
* greater than the sum of the retransmission value of the peer.
* See [SCTP] for more information.
*
*/
static int sctp_setsockopt_associnfo(struct sock *sk,
struct sctp_assocparams *assocparams,
unsigned int optlen)
{
struct sctp_association *asoc;
if (optlen != sizeof(struct sctp_assocparams))
return -EINVAL;
asoc = sctp_id2assoc(sk, assocparams->sasoc_assoc_id);
if (!asoc && assocparams->sasoc_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
/* Set the values to the specific association */
if (asoc) {
if (assocparams->sasoc_asocmaxrxt != 0) {
__u32 path_sum = 0;
int paths = 0;
struct sctp_transport *peer_addr;
list_for_each_entry(peer_addr, &asoc->peer.transport_addr_list,
transports) {
path_sum += peer_addr->pathmaxrxt;
paths++;
}
/* Only validate asocmaxrxt if we have more than
* one path/transport. We do this because path
* retransmissions are only counted when we have more
* then one path.
*/
if (paths > 1 &&
assocparams->sasoc_asocmaxrxt > path_sum)
return -EINVAL;
asoc->max_retrans = assocparams->sasoc_asocmaxrxt;
}
if (assocparams->sasoc_cookie_life != 0)
asoc->cookie_life =
ms_to_ktime(assocparams->sasoc_cookie_life);
} else {
/* Set the values to the endpoint */
struct sctp_sock *sp = sctp_sk(sk);
if (assocparams->sasoc_asocmaxrxt != 0)
sp->assocparams.sasoc_asocmaxrxt =
assocparams->sasoc_asocmaxrxt;
if (assocparams->sasoc_cookie_life != 0)
sp->assocparams.sasoc_cookie_life =
assocparams->sasoc_cookie_life;
}
return 0;
}
/*
* 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
*
* This socket option is a boolean flag which turns on or off mapped V4
* addresses. If this option is turned on and the socket is type
* PF_INET6, then IPv4 addresses will be mapped to V6 representation.
* If this option is turned off, then no mapping will be done of V4
* addresses and a user will receive both PF_INET6 and PF_INET type
* addresses on the socket.
*/
static int sctp_setsockopt_mappedv4(struct sock *sk, int *val,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
if (optlen < sizeof(int))
return -EINVAL;
if (*val)
sp->v4mapped = 1;
else
sp->v4mapped = 0;
return 0;
}
/*
* 8.1.16. Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
* This option will get or set the maximum size to put in any outgoing
* SCTP DATA chunk. If a message is larger than this size it will be
* fragmented by SCTP into the specified size. Note that the underlying
* SCTP implementation may fragment into smaller sized chunks when the
* PMTU of the underlying association is smaller than the value set by
* the user. The default value for this option is '0' which indicates
* the user is NOT limiting fragmentation and only the PMTU will effect
* SCTP's choice of DATA chunk size. Note also that values set larger
* than the maximum size of an IP datagram will effectively let SCTP
* control fragmentation (i.e. the same as setting this option to 0).
*
* The following structure is used to access and modify this parameter:
*
* struct sctp_assoc_value {
* sctp_assoc_t assoc_id;
* uint32_t assoc_value;
* };
*
* assoc_id: This parameter is ignored for one-to-one style sockets.
* For one-to-many style sockets this parameter indicates which
* association the user is performing an action upon. Note that if
* this field's value is zero then the endpoints default value is
* changed (effecting future associations only).
* assoc_value: This parameter specifies the maximum size in bytes.
*/
static int sctp_setsockopt_maxseg(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
sctp_assoc_t assoc_id;
int val;
if (optlen == sizeof(int)) {
pr_warn_ratelimited(DEPRECATED
"%s (pid %d) "
"Use of int in maxseg socket option.\n"
"Use struct sctp_assoc_value instead\n",
current->comm, task_pid_nr(current));
assoc_id = SCTP_FUTURE_ASSOC;
val = *(int *)params;
} else if (optlen == sizeof(struct sctp_assoc_value)) {
assoc_id = params->assoc_id;
val = params->assoc_value;
} else {
return -EINVAL;
}
asoc = sctp_id2assoc(sk, assoc_id);
if (!asoc && assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (val) {
int min_len, max_len;
__u16 datasize = asoc ? sctp_datachk_len(&asoc->stream) :
sizeof(struct sctp_data_chunk);
min_len = sctp_min_frag_point(sp, datasize);
max_len = SCTP_MAX_CHUNK_LEN - datasize;
if (val < min_len || val > max_len)
return -EINVAL;
}
if (asoc) {
asoc->user_frag = val;
sctp_assoc_update_frag_point(asoc);
} else {
sp->user_frag = val;
}
return 0;
}
/*
* 7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR)
*
* Requests that the peer mark the enclosed address as the association
* primary. The enclosed address must be one of the association's
* locally bound addresses. The following structure is used to make a
* set primary request:
*/
static int sctp_setsockopt_peer_primary_addr(struct sock *sk,
struct sctp_setpeerprim *prim,
unsigned int optlen)
{
struct sctp_sock *sp;
struct sctp_association *asoc = NULL;
struct sctp_chunk *chunk;
struct sctp_af *af;
int err;
sp = sctp_sk(sk);
if (!sp->ep->asconf_enable)
return -EPERM;
if (optlen != sizeof(struct sctp_setpeerprim))
return -EINVAL;
asoc = sctp_id2assoc(sk, prim->sspp_assoc_id);
if (!asoc)
return -EINVAL;
if (!asoc->peer.asconf_capable)
return -EPERM;
if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY)
return -EPERM;
if (!sctp_state(asoc, ESTABLISHED))
return -ENOTCONN;
af = sctp_get_af_specific(prim->sspp_addr.ss_family);
if (!af)
return -EINVAL;
if (!af->addr_valid((union sctp_addr *)&prim->sspp_addr, sp, NULL))
return -EADDRNOTAVAIL;
if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim->sspp_addr))
return -EADDRNOTAVAIL;
/* Allow security module to validate address. */
err = security_sctp_bind_connect(sk, SCTP_SET_PEER_PRIMARY_ADDR,
(struct sockaddr *)&prim->sspp_addr,
af->sockaddr_len);
if (err)
return err;
/* Create an ASCONF chunk with SET_PRIMARY parameter */
chunk = sctp_make_asconf_set_prim(asoc,
(union sctp_addr *)&prim->sspp_addr);
if (!chunk)
return -ENOMEM;
err = sctp_send_asconf(asoc, chunk);
pr_debug("%s: we set peer primary addr primitively\n", __func__);
return err;
}
static int sctp_setsockopt_adaptation_layer(struct sock *sk,
struct sctp_setadaptation *adapt,
unsigned int optlen)
{
if (optlen != sizeof(struct sctp_setadaptation))
return -EINVAL;
sctp_sk(sk)->adaptation_ind = adapt->ssb_adaptation_ind;
return 0;
}
/*
* 7.1.29. Set or Get the default context (SCTP_CONTEXT)
*
* The context field in the sctp_sndrcvinfo structure is normally only
* used when a failed message is retrieved holding the value that was
* sent down on the actual send call. This option allows the setting of
* a default context on an association basis that will be received on
* reading messages from the peer. This is especially helpful in the
* one-2-many model for an application to keep some reference to an
* internal state machine that is processing messages on the
* association. Note that the setting of this value only effects
* received messages from the peer and does not effect the value that is
* saved with outbound messages.
*/
static int sctp_setsockopt_context(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
if (optlen != sizeof(struct sctp_assoc_value))
return -EINVAL;
asoc = sctp_id2assoc(sk, params->assoc_id);
if (!asoc && params->assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
asoc->default_rcv_context = params->assoc_value;
return 0;
}
if (sctp_style(sk, TCP))
params->assoc_id = SCTP_FUTURE_ASSOC;
if (params->assoc_id == SCTP_FUTURE_ASSOC ||
params->assoc_id == SCTP_ALL_ASSOC)
sp->default_rcv_context = params->assoc_value;
if (params->assoc_id == SCTP_CURRENT_ASSOC ||
params->assoc_id == SCTP_ALL_ASSOC)
list_for_each_entry(asoc, &sp->ep->asocs, asocs)
asoc->default_rcv_context = params->assoc_value;
return 0;
}
/*
* 7.1.24. Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
*
* This options will at a minimum specify if the implementation is doing
* fragmented interleave. Fragmented interleave, for a one to many
* socket, is when subsequent calls to receive a message may return
* parts of messages from different associations. Some implementations
* may allow you to turn this value on or off. If so, when turned off,
* no fragment interleave will occur (which will cause a head of line
* blocking amongst multiple associations sharing the same one to many
* socket). When this option is turned on, then each receive call may
* come from a different association (thus the user must receive data
* with the extended calls (e.g. sctp_recvmsg) to keep track of which
* association each receive belongs to.
*
* This option takes a boolean value. A non-zero value indicates that
* fragmented interleave is on. A value of zero indicates that
* fragmented interleave is off.
*
* Note that it is important that an implementation that allows this
* option to be turned on, have it off by default. Otherwise an unaware
* application using the one to many model may become confused and act
* incorrectly.
*/
static int sctp_setsockopt_fragment_interleave(struct sock *sk, int *val,
unsigned int optlen)
{
if (optlen != sizeof(int))
return -EINVAL;
sctp_sk(sk)->frag_interleave = !!*val;
if (!sctp_sk(sk)->frag_interleave)
sctp_sk(sk)->ep->intl_enable = 0;
return 0;
}
/*
* 8.1.21. Set or Get the SCTP Partial Delivery Point
* (SCTP_PARTIAL_DELIVERY_POINT)
*
* This option will set or get the SCTP partial delivery point. This
* point is the size of a message where the partial delivery API will be
* invoked to help free up rwnd space for the peer. Setting this to a
* lower value will cause partial deliveries to happen more often. The
* calls argument is an integer that sets or gets the partial delivery
* point. Note also that the call will fail if the user attempts to set
* this value larger than the socket receive buffer size.
*
* Note that any single message having a length smaller than or equal to
* the SCTP partial delivery point will be delivered in one single read
* call as long as the user provided buffer is large enough to hold the
* message.
*/
static int sctp_setsockopt_partial_delivery_point(struct sock *sk, u32 *val,
unsigned int optlen)
{
if (optlen != sizeof(u32))
return -EINVAL;
/* Note: We double the receive buffer from what the user sets
* it to be, also initial rwnd is based on rcvbuf/2.
*/
if (*val > (sk->sk_rcvbuf >> 1))
return -EINVAL;
sctp_sk(sk)->pd_point = *val;
return 0; /* is this the right error code? */
}
/*
* 7.1.28. Set or Get the maximum burst (SCTP_MAX_BURST)
*
* This option will allow a user to change the maximum burst of packets
* that can be emitted by this association. Note that the default value
* is 4, and some implementations may restrict this setting so that it
* can only be lowered.
*
* NOTE: This text doesn't seem right. Do this on a socket basis with
* future associations inheriting the socket value.
*/
static int sctp_setsockopt_maxburst(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
sctp_assoc_t assoc_id;
u32 assoc_value;
if (optlen == sizeof(int)) {
pr_warn_ratelimited(DEPRECATED
"%s (pid %d) "
"Use of int in max_burst socket option deprecated.\n"
"Use struct sctp_assoc_value instead\n",
current->comm, task_pid_nr(current));
assoc_id = SCTP_FUTURE_ASSOC;
assoc_value = *((int *)params);
} else if (optlen == sizeof(struct sctp_assoc_value)) {
assoc_id = params->assoc_id;
assoc_value = params->assoc_value;
} else
return -EINVAL;
asoc = sctp_id2assoc(sk, assoc_id);
if (!asoc && assoc_id > SCTP_ALL_ASSOC && sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
asoc->max_burst = assoc_value;
return 0;
}
if (sctp_style(sk, TCP))
assoc_id = SCTP_FUTURE_ASSOC;
if (assoc_id == SCTP_FUTURE_ASSOC || assoc_id == SCTP_ALL_ASSOC)
sp->max_burst = assoc_value;
if (assoc_id == SCTP_CURRENT_ASSOC || assoc_id == SCTP_ALL_ASSOC)
list_for_each_entry(asoc, &sp->ep->asocs, asocs)
asoc->max_burst = assoc_value;
return 0;
}
/*
* 7.1.18. Add a chunk that must be authenticated (SCTP_AUTH_CHUNK)
*
* This set option adds a chunk type that the user is requesting to be
* received only in an authenticated way. Changes to the list of chunks
* will only effect future associations on the socket.
*/
static int sctp_setsockopt_auth_chunk(struct sock *sk,
struct sctp_authchunk *val,
unsigned int optlen)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
if (!ep->auth_enable)
return -EACCES;
if (optlen != sizeof(struct sctp_authchunk))
return -EINVAL;
switch (val->sauth_chunk) {
case SCTP_CID_INIT:
case SCTP_CID_INIT_ACK:
case SCTP_CID_SHUTDOWN_COMPLETE:
case SCTP_CID_AUTH:
return -EINVAL;
}
/* add this chunk id to the endpoint */
return sctp_auth_ep_add_chunkid(ep, val->sauth_chunk);
}
/*
* 7.1.19. Get or set the list of supported HMAC Identifiers (SCTP_HMAC_IDENT)
*
* This option gets or sets the list of HMAC algorithms that the local
* endpoint requires the peer to use.
*/
static int sctp_setsockopt_hmac_ident(struct sock *sk,
struct sctp_hmacalgo *hmacs,
unsigned int optlen)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
u32 idents;
if (!ep->auth_enable)
return -EACCES;
if (optlen < sizeof(struct sctp_hmacalgo))
return -EINVAL;
optlen = min_t(unsigned int, optlen, sizeof(struct sctp_hmacalgo) +
SCTP_AUTH_NUM_HMACS * sizeof(u16));
idents = hmacs->shmac_num_idents;
if (idents == 0 || idents > SCTP_AUTH_NUM_HMACS ||
(idents * sizeof(u16)) > (optlen - sizeof(struct sctp_hmacalgo)))
return -EINVAL;
return sctp_auth_ep_set_hmacs(ep, hmacs);
}
/*
* 7.1.20. Set a shared key (SCTP_AUTH_KEY)
*
* This option will set a shared secret key which is used to build an
* association shared key.
*/
static int sctp_setsockopt_auth_key(struct sock *sk,
struct sctp_authkey *authkey,
unsigned int optlen)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct sctp_association *asoc;
int ret = -EINVAL;
if (optlen <= sizeof(struct sctp_authkey))
return -EINVAL;
/* authkey->sca_keylength is u16, so optlen can't be bigger than
* this.
*/
optlen = min_t(unsigned int, optlen, USHRT_MAX + sizeof(*authkey));
if (authkey->sca_keylength > optlen - sizeof(*authkey))
goto out;
asoc = sctp_id2assoc(sk, authkey->sca_assoc_id);
if (!asoc && authkey->sca_assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
goto out;
if (asoc) {
ret = sctp_auth_set_key(ep, asoc, authkey);
goto out;
}
if (sctp_style(sk, TCP))
authkey->sca_assoc_id = SCTP_FUTURE_ASSOC;
if (authkey->sca_assoc_id == SCTP_FUTURE_ASSOC ||
authkey->sca_assoc_id == SCTP_ALL_ASSOC) {
ret = sctp_auth_set_key(ep, asoc, authkey);
if (ret)
goto out;
}
ret = 0;
if (authkey->sca_assoc_id == SCTP_CURRENT_ASSOC ||
authkey->sca_assoc_id == SCTP_ALL_ASSOC) {
list_for_each_entry(asoc, &ep->asocs, asocs) {
int res = sctp_auth_set_key(ep, asoc, authkey);
if (res && !ret)
ret = res;
}
}
out:
memzero_explicit(authkey, optlen);
return ret;
}
/*
* 7.1.21. Get or set the active shared key (SCTP_AUTH_ACTIVE_KEY)
*
* This option will get or set the active shared key to be used to build
* the association shared key.
*/
static int sctp_setsockopt_active_key(struct sock *sk,
struct sctp_authkeyid *val,
unsigned int optlen)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct sctp_association *asoc;
int ret = 0;
if (optlen != sizeof(struct sctp_authkeyid))
return -EINVAL;
asoc = sctp_id2assoc(sk, val->scact_assoc_id);
if (!asoc && val->scact_assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc)
return sctp_auth_set_active_key(ep, asoc, val->scact_keynumber);
if (sctp_style(sk, TCP))
val->scact_assoc_id = SCTP_FUTURE_ASSOC;
if (val->scact_assoc_id == SCTP_FUTURE_ASSOC ||
val->scact_assoc_id == SCTP_ALL_ASSOC) {
ret = sctp_auth_set_active_key(ep, asoc, val->scact_keynumber);
if (ret)
return ret;
}
if (val->scact_assoc_id == SCTP_CURRENT_ASSOC ||
val->scact_assoc_id == SCTP_ALL_ASSOC) {
list_for_each_entry(asoc, &ep->asocs, asocs) {
int res = sctp_auth_set_active_key(ep, asoc,
val->scact_keynumber);
if (res && !ret)
ret = res;
}
}
return ret;
}
/*
* 7.1.22. Delete a shared key (SCTP_AUTH_DELETE_KEY)
*
* This set option will delete a shared secret key from use.
*/
static int sctp_setsockopt_del_key(struct sock *sk,
struct sctp_authkeyid *val,
unsigned int optlen)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct sctp_association *asoc;
int ret = 0;
if (optlen != sizeof(struct sctp_authkeyid))
return -EINVAL;
asoc = sctp_id2assoc(sk, val->scact_assoc_id);
if (!asoc && val->scact_assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc)
return sctp_auth_del_key_id(ep, asoc, val->scact_keynumber);
if (sctp_style(sk, TCP))
val->scact_assoc_id = SCTP_FUTURE_ASSOC;
if (val->scact_assoc_id == SCTP_FUTURE_ASSOC ||
val->scact_assoc_id == SCTP_ALL_ASSOC) {
ret = sctp_auth_del_key_id(ep, asoc, val->scact_keynumber);
if (ret)
return ret;
}
if (val->scact_assoc_id == SCTP_CURRENT_ASSOC ||
val->scact_assoc_id == SCTP_ALL_ASSOC) {
list_for_each_entry(asoc, &ep->asocs, asocs) {
int res = sctp_auth_del_key_id(ep, asoc,
val->scact_keynumber);
if (res && !ret)
ret = res;
}
}
return ret;
}
/*
* 8.3.4 Deactivate a Shared Key (SCTP_AUTH_DEACTIVATE_KEY)
*
* This set option will deactivate a shared secret key.
*/
static int sctp_setsockopt_deactivate_key(struct sock *sk,
struct sctp_authkeyid *val,
unsigned int optlen)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct sctp_association *asoc;
int ret = 0;
if (optlen != sizeof(struct sctp_authkeyid))
return -EINVAL;
asoc = sctp_id2assoc(sk, val->scact_assoc_id);
if (!asoc && val->scact_assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc)
return sctp_auth_deact_key_id(ep, asoc, val->scact_keynumber);
if (sctp_style(sk, TCP))
val->scact_assoc_id = SCTP_FUTURE_ASSOC;
if (val->scact_assoc_id == SCTP_FUTURE_ASSOC ||
val->scact_assoc_id == SCTP_ALL_ASSOC) {
ret = sctp_auth_deact_key_id(ep, asoc, val->scact_keynumber);
if (ret)
return ret;
}
if (val->scact_assoc_id == SCTP_CURRENT_ASSOC ||
val->scact_assoc_id == SCTP_ALL_ASSOC) {
list_for_each_entry(asoc, &ep->asocs, asocs) {
int res = sctp_auth_deact_key_id(ep, asoc,
val->scact_keynumber);
if (res && !ret)
ret = res;
}
}
return ret;
}
/*
* 8.1.23 SCTP_AUTO_ASCONF
*
* This option will enable or disable the use of the automatic generation of
* ASCONF chunks to add and delete addresses to an existing association. Note
* that this option has two caveats namely: a) it only affects sockets that
* are bound to all addresses available to the SCTP stack, and b) the system
* administrator may have an overriding control that turns the ASCONF feature
* off no matter what setting the socket option may have.
* This option expects an integer boolean flag, where a non-zero value turns on
* the option, and a zero value turns off the option.
* Note. In this implementation, socket operation overrides default parameter
* being set by sysctl as well as FreeBSD implementation
*/
static int sctp_setsockopt_auto_asconf(struct sock *sk, int *val,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
if (optlen < sizeof(int))
return -EINVAL;
if (!sctp_is_ep_boundall(sk) && *val)
return -EINVAL;
if ((*val && sp->do_auto_asconf) || (!*val && !sp->do_auto_asconf))
return 0;
spin_lock_bh(&sock_net(sk)->sctp.addr_wq_lock);
if (*val == 0 && sp->do_auto_asconf) {
list_del(&sp->auto_asconf_list);
sp->do_auto_asconf = 0;
} else if (*val && !sp->do_auto_asconf) {
list_add_tail(&sp->auto_asconf_list,
&sock_net(sk)->sctp.auto_asconf_splist);
sp->do_auto_asconf = 1;
}
spin_unlock_bh(&sock_net(sk)->sctp.addr_wq_lock);
return 0;
}
/*
* SCTP_PEER_ADDR_THLDS
*
* This option allows us to alter the partially failed threshold for one or all
* transports in an association. See Section 6.1 of:
* http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
*/
static int sctp_setsockopt_paddr_thresholds(struct sock *sk,
struct sctp_paddrthlds_v2 *val,
unsigned int optlen, bool v2)
{
struct sctp_transport *trans;
struct sctp_association *asoc;
int len;
len = v2 ? sizeof(*val) : sizeof(struct sctp_paddrthlds);
if (optlen < len)
return -EINVAL;
if (v2 && val->spt_pathpfthld > val->spt_pathcpthld)
return -EINVAL;
if (!sctp_is_any(sk, (const union sctp_addr *)&val->spt_address)) {
trans = sctp_addr_id2transport(sk, &val->spt_address,
val->spt_assoc_id);
if (!trans)
return -ENOENT;
if (val->spt_pathmaxrxt)
trans->pathmaxrxt = val->spt_pathmaxrxt;
if (v2)
trans->ps_retrans = val->spt_pathcpthld;
trans->pf_retrans = val->spt_pathpfthld;
return 0;
}
asoc = sctp_id2assoc(sk, val->spt_assoc_id);
if (!asoc && val->spt_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
list_for_each_entry(trans, &asoc->peer.transport_addr_list,
transports) {
if (val->spt_pathmaxrxt)
trans->pathmaxrxt = val->spt_pathmaxrxt;
if (v2)
trans->ps_retrans = val->spt_pathcpthld;
trans->pf_retrans = val->spt_pathpfthld;
}
if (val->spt_pathmaxrxt)
asoc->pathmaxrxt = val->spt_pathmaxrxt;
if (v2)
asoc->ps_retrans = val->spt_pathcpthld;
asoc->pf_retrans = val->spt_pathpfthld;
} else {
struct sctp_sock *sp = sctp_sk(sk);
if (val->spt_pathmaxrxt)
sp->pathmaxrxt = val->spt_pathmaxrxt;
if (v2)
sp->ps_retrans = val->spt_pathcpthld;
sp->pf_retrans = val->spt_pathpfthld;
}
return 0;
}
static int sctp_setsockopt_recvrcvinfo(struct sock *sk, int *val,
unsigned int optlen)
{
if (optlen < sizeof(int))
return -EINVAL;
sctp_sk(sk)->recvrcvinfo = (*val == 0) ? 0 : 1;
return 0;
}
static int sctp_setsockopt_recvnxtinfo(struct sock *sk, int *val,
unsigned int optlen)
{
if (optlen < sizeof(int))
return -EINVAL;
sctp_sk(sk)->recvnxtinfo = (*val == 0) ? 0 : 1;
return 0;
}
static int sctp_setsockopt_pr_supported(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_association *asoc;
if (optlen != sizeof(*params))
return -EINVAL;
asoc = sctp_id2assoc(sk, params->assoc_id);
if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
sctp_sk(sk)->ep->prsctp_enable = !!params->assoc_value;
return 0;
}
static int sctp_setsockopt_default_prinfo(struct sock *sk,
struct sctp_default_prinfo *info,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
int retval = -EINVAL;
if (optlen != sizeof(*info))
goto out;
if (info->pr_policy & ~SCTP_PR_SCTP_MASK)
goto out;
if (info->pr_policy == SCTP_PR_SCTP_NONE)
info->pr_value = 0;
asoc = sctp_id2assoc(sk, info->pr_assoc_id);
if (!asoc && info->pr_assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
goto out;
retval = 0;
if (asoc) {
SCTP_PR_SET_POLICY(asoc->default_flags, info->pr_policy);
asoc->default_timetolive = info->pr_value;
goto out;
}
if (sctp_style(sk, TCP))
info->pr_assoc_id = SCTP_FUTURE_ASSOC;
if (info->pr_assoc_id == SCTP_FUTURE_ASSOC ||
info->pr_assoc_id == SCTP_ALL_ASSOC) {
SCTP_PR_SET_POLICY(sp->default_flags, info->pr_policy);
sp->default_timetolive = info->pr_value;
}
if (info->pr_assoc_id == SCTP_CURRENT_ASSOC ||
info->pr_assoc_id == SCTP_ALL_ASSOC) {
list_for_each_entry(asoc, &sp->ep->asocs, asocs) {
SCTP_PR_SET_POLICY(asoc->default_flags,
info->pr_policy);
asoc->default_timetolive = info->pr_value;
}
}
out:
return retval;
}
static int sctp_setsockopt_reconfig_supported(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_association *asoc;
int retval = -EINVAL;
if (optlen != sizeof(*params))
goto out;
asoc = sctp_id2assoc(sk, params->assoc_id);
if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
goto out;
sctp_sk(sk)->ep->reconf_enable = !!params->assoc_value;
retval = 0;
out:
return retval;
}
static int sctp_setsockopt_enable_strreset(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct sctp_association *asoc;
int retval = -EINVAL;
if (optlen != sizeof(*params))
goto out;
if (params->assoc_value & (~SCTP_ENABLE_STRRESET_MASK))
goto out;
asoc = sctp_id2assoc(sk, params->assoc_id);
if (!asoc && params->assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
goto out;
retval = 0;
if (asoc) {
asoc->strreset_enable = params->assoc_value;
goto out;
}
if (sctp_style(sk, TCP))
params->assoc_id = SCTP_FUTURE_ASSOC;
if (params->assoc_id == SCTP_FUTURE_ASSOC ||
params->assoc_id == SCTP_ALL_ASSOC)
ep->strreset_enable = params->assoc_value;
if (params->assoc_id == SCTP_CURRENT_ASSOC ||
params->assoc_id == SCTP_ALL_ASSOC)
list_for_each_entry(asoc, &ep->asocs, asocs)
asoc->strreset_enable = params->assoc_value;
out:
return retval;
}
static int sctp_setsockopt_reset_streams(struct sock *sk,
struct sctp_reset_streams *params,
unsigned int optlen)
{
struct sctp_association *asoc;
if (optlen < sizeof(*params))
return -EINVAL;
/* srs_number_streams is u16, so optlen can't be bigger than this. */
optlen = min_t(unsigned int, optlen, USHRT_MAX +
sizeof(__u16) * sizeof(*params));
if (params->srs_number_streams * sizeof(__u16) >
optlen - sizeof(*params))
return -EINVAL;
asoc = sctp_id2assoc(sk, params->srs_assoc_id);
if (!asoc)
return -EINVAL;
return sctp_send_reset_streams(asoc, params);
}
static int sctp_setsockopt_reset_assoc(struct sock *sk, sctp_assoc_t *associd,
unsigned int optlen)
{
struct sctp_association *asoc;
if (optlen != sizeof(*associd))
return -EINVAL;
asoc = sctp_id2assoc(sk, *associd);
if (!asoc)
return -EINVAL;
return sctp_send_reset_assoc(asoc);
}
static int sctp_setsockopt_add_streams(struct sock *sk,
struct sctp_add_streams *params,
unsigned int optlen)
{
struct sctp_association *asoc;
if (optlen != sizeof(*params))
return -EINVAL;
asoc = sctp_id2assoc(sk, params->sas_assoc_id);
if (!asoc)
return -EINVAL;
return sctp_send_add_streams(asoc, params);
}
static int sctp_setsockopt_scheduler(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
int retval = 0;
if (optlen < sizeof(*params))
return -EINVAL;
if (params->assoc_value > SCTP_SS_MAX)
return -EINVAL;
asoc = sctp_id2assoc(sk, params->assoc_id);
if (!asoc && params->assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc)
return sctp_sched_set_sched(asoc, params->assoc_value);
if (sctp_style(sk, TCP))
params->assoc_id = SCTP_FUTURE_ASSOC;
if (params->assoc_id == SCTP_FUTURE_ASSOC ||
params->assoc_id == SCTP_ALL_ASSOC)
sp->default_ss = params->assoc_value;
if (params->assoc_id == SCTP_CURRENT_ASSOC ||
params->assoc_id == SCTP_ALL_ASSOC) {
list_for_each_entry(asoc, &sp->ep->asocs, asocs) {
int ret = sctp_sched_set_sched(asoc,
params->assoc_value);
if (ret && !retval)
retval = ret;
}
}
return retval;
}
static int sctp_setsockopt_scheduler_value(struct sock *sk,
struct sctp_stream_value *params,
unsigned int optlen)
{
struct sctp_association *asoc;
int retval = -EINVAL;
if (optlen < sizeof(*params))
goto out;
asoc = sctp_id2assoc(sk, params->assoc_id);
if (!asoc && params->assoc_id != SCTP_CURRENT_ASSOC &&
sctp_style(sk, UDP))
goto out;
if (asoc) {
retval = sctp_sched_set_value(asoc, params->stream_id,
params->stream_value, GFP_KERNEL);
goto out;
}
retval = 0;
list_for_each_entry(asoc, &sctp_sk(sk)->ep->asocs, asocs) {
int ret = sctp_sched_set_value(asoc, params->stream_id,
params->stream_value,
GFP_KERNEL);
if (ret && !retval) /* try to return the 1st error. */
retval = ret;
}
out:
return retval;
}
static int sctp_setsockopt_interleaving_supported(struct sock *sk,
struct sctp_assoc_value *p,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
if (optlen < sizeof(*p))
return -EINVAL;
asoc = sctp_id2assoc(sk, p->assoc_id);
if (!asoc && p->assoc_id != SCTP_FUTURE_ASSOC && sctp_style(sk, UDP))
return -EINVAL;
if (!sock_net(sk)->sctp.intl_enable || !sp->frag_interleave) {
return -EPERM;
}
sp->ep->intl_enable = !!p->assoc_value;
return 0;
}
static int sctp_setsockopt_reuse_port(struct sock *sk, int *val,
unsigned int optlen)
{
if (!sctp_style(sk, TCP))
return -EOPNOTSUPP;
if (sctp_sk(sk)->ep->base.bind_addr.port)
return -EFAULT;
if (optlen < sizeof(int))
return -EINVAL;
sctp_sk(sk)->reuse = !!*val;
return 0;
}
static int sctp_assoc_ulpevent_type_set(struct sctp_event *param,
struct sctp_association *asoc)
{
struct sctp_ulpevent *event;
sctp_ulpevent_type_set(&asoc->subscribe, param->se_type, param->se_on);
if (param->se_type == SCTP_SENDER_DRY_EVENT && param->se_on) {
if (sctp_outq_is_empty(&asoc->outqueue)) {
event = sctp_ulpevent_make_sender_dry_event(asoc,
GFP_USER | __GFP_NOWARN);
if (!event)
return -ENOMEM;
asoc->stream.si->enqueue_event(&asoc->ulpq, event);
}
}
return 0;
}
static int sctp_setsockopt_event(struct sock *sk, struct sctp_event *param,
unsigned int optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
int retval = 0;
if (optlen < sizeof(*param))
return -EINVAL;
if (param->se_type < SCTP_SN_TYPE_BASE ||
param->se_type > SCTP_SN_TYPE_MAX)
return -EINVAL;
asoc = sctp_id2assoc(sk, param->se_assoc_id);
if (!asoc && param->se_assoc_id > SCTP_ALL_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc)
return sctp_assoc_ulpevent_type_set(param, asoc);
if (sctp_style(sk, TCP))
param->se_assoc_id = SCTP_FUTURE_ASSOC;
if (param->se_assoc_id == SCTP_FUTURE_ASSOC ||
param->se_assoc_id == SCTP_ALL_ASSOC)
sctp_ulpevent_type_set(&sp->subscribe,
param->se_type, param->se_on);
if (param->se_assoc_id == SCTP_CURRENT_ASSOC ||
param->se_assoc_id == SCTP_ALL_ASSOC) {
list_for_each_entry(asoc, &sp->ep->asocs, asocs) {
int ret = sctp_assoc_ulpevent_type_set(param, asoc);
if (ret && !retval)
retval = ret;
}
}
return retval;
}
static int sctp_setsockopt_asconf_supported(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_association *asoc;
struct sctp_endpoint *ep;
int retval = -EINVAL;
if (optlen != sizeof(*params))
goto out;
asoc = sctp_id2assoc(sk, params->assoc_id);
if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
goto out;
ep = sctp_sk(sk)->ep;
ep->asconf_enable = !!params->assoc_value;
if (ep->asconf_enable && ep->auth_enable) {
sctp_auth_ep_add_chunkid(ep, SCTP_CID_ASCONF);
sctp_auth_ep_add_chunkid(ep, SCTP_CID_ASCONF_ACK);
}
retval = 0;
out:
return retval;
}
static int sctp_setsockopt_auth_supported(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_association *asoc;
struct sctp_endpoint *ep;
int retval = -EINVAL;
if (optlen != sizeof(*params))
goto out;
asoc = sctp_id2assoc(sk, params->assoc_id);
if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
goto out;
ep = sctp_sk(sk)->ep;
if (params->assoc_value) {
retval = sctp_auth_init(ep, GFP_KERNEL);
if (retval)
goto out;
if (ep->asconf_enable) {
sctp_auth_ep_add_chunkid(ep, SCTP_CID_ASCONF);
sctp_auth_ep_add_chunkid(ep, SCTP_CID_ASCONF_ACK);
}
}
ep->auth_enable = !!params->assoc_value;
retval = 0;
out:
return retval;
}
static int sctp_setsockopt_ecn_supported(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_association *asoc;
int retval = -EINVAL;
if (optlen != sizeof(*params))
goto out;
asoc = sctp_id2assoc(sk, params->assoc_id);
if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
goto out;
sctp_sk(sk)->ep->ecn_enable = !!params->assoc_value;
retval = 0;
out:
return retval;
}
static int sctp_setsockopt_pf_expose(struct sock *sk,
struct sctp_assoc_value *params,
unsigned int optlen)
{
struct sctp_association *asoc;
int retval = -EINVAL;
if (optlen != sizeof(*params))
goto out;
if (params->assoc_value > SCTP_PF_EXPOSE_MAX)
goto out;
asoc = sctp_id2assoc(sk, params->assoc_id);
if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
goto out;
if (asoc)
asoc->pf_expose = params->assoc_value;
else
sctp_sk(sk)->pf_expose = params->assoc_value;
retval = 0;
out:
return retval;
}
static int sctp_setsockopt_encap_port(struct sock *sk,
struct sctp_udpencaps *encap,
unsigned int optlen)
{
struct sctp_association *asoc;
struct sctp_transport *t;
__be16 encap_port;
if (optlen != sizeof(*encap))
return -EINVAL;
/* If an address other than INADDR_ANY is specified, and
* no transport is found, then the request is invalid.
*/
encap_port = (__force __be16)encap->sue_port;
if (!sctp_is_any(sk, (union sctp_addr *)&encap->sue_address)) {
t = sctp_addr_id2transport(sk, &encap->sue_address,
encap->sue_assoc_id);
if (!t)
return -EINVAL;
t->encap_port = encap_port;
return 0;
}
/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
* socket is a one to many style socket, and an association
* was not found, then the id was invalid.
*/
asoc = sctp_id2assoc(sk, encap->sue_assoc_id);
if (!asoc && encap->sue_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
/* If changes are for association, also apply encap_port to
* each transport.
*/
if (asoc) {
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports)
t->encap_port = encap_port;
asoc->encap_port = encap_port;
return 0;
}
sctp_sk(sk)->encap_port = encap_port;
return 0;
}
static int sctp_setsockopt_probe_interval(struct sock *sk,
struct sctp_probeinterval *params,
unsigned int optlen)
{
struct sctp_association *asoc;
struct sctp_transport *t;
__u32 probe_interval;
if (optlen != sizeof(*params))
return -EINVAL;
probe_interval = params->spi_interval;
if (probe_interval && probe_interval < SCTP_PROBE_TIMER_MIN)
return -EINVAL;
/* If an address other than INADDR_ANY is specified, and
* no transport is found, then the request is invalid.
*/
if (!sctp_is_any(sk, (union sctp_addr *)¶ms->spi_address)) {
t = sctp_addr_id2transport(sk, ¶ms->spi_address,
params->spi_assoc_id);
if (!t)
return -EINVAL;
t->probe_interval = msecs_to_jiffies(probe_interval);
sctp_transport_pl_reset(t);
return 0;
}
/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
* socket is a one to many style socket, and an association
* was not found, then the id was invalid.
*/
asoc = sctp_id2assoc(sk, params->spi_assoc_id);
if (!asoc && params->spi_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
/* If changes are for association, also apply probe_interval to
* each transport.
*/
if (asoc) {
list_for_each_entry(t, &asoc->peer.transport_addr_list, transports) {
t->probe_interval = msecs_to_jiffies(probe_interval);
sctp_transport_pl_reset(t);
}
asoc->probe_interval = msecs_to_jiffies(probe_interval);
return 0;
}
sctp_sk(sk)->probe_interval = probe_interval;
return 0;
}
/* API 6.2 setsockopt(), getsockopt()
*
* Applications use setsockopt() and getsockopt() to set or retrieve
* socket options. Socket options are used to change the default
* behavior of sockets calls. They are described in Section 7.
*
* The syntax is:
*
* ret = getsockopt(int sd, int level, int optname, void __user *optval,
* int __user *optlen);
* ret = setsockopt(int sd, int level, int optname, const void __user *optval,
* int optlen);
*
* sd - the socket descript.
* level - set to IPPROTO_SCTP for all SCTP options.
* optname - the option name.
* optval - the buffer to store the value of the option.
* optlen - the size of the buffer.
*/
static int sctp_setsockopt(struct sock *sk, int level, int optname,
sockptr_t optval, unsigned int optlen)
{
void *kopt = NULL;
int retval = 0;
pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
/* I can hardly begin to describe how wrong this is. This is
* so broken as to be worse than useless. The API draft
* REALLY is NOT helpful here... I am not convinced that the
* semantics of setsockopt() with a level OTHER THAN SOL_SCTP
* are at all well-founded.
*/
if (level != SOL_SCTP) {
struct sctp_af *af = sctp_sk(sk)->pf->af;
return af->setsockopt(sk, level, optname, optval, optlen);
}
if (optlen > 0) {
/* Trim it to the biggest size sctp sockopt may need if necessary */
optlen = min_t(unsigned int, optlen,
PAGE_ALIGN(USHRT_MAX +
sizeof(__u16) * sizeof(struct sctp_reset_streams)));
kopt = memdup_sockptr(optval, optlen);
if (IS_ERR(kopt))
return PTR_ERR(kopt);
}
lock_sock(sk);
switch (optname) {
case SCTP_SOCKOPT_BINDX_ADD:
/* 'optlen' is the size of the addresses buffer. */
retval = sctp_setsockopt_bindx(sk, kopt, optlen,
SCTP_BINDX_ADD_ADDR);
break;
case SCTP_SOCKOPT_BINDX_REM:
/* 'optlen' is the size of the addresses buffer. */
retval = sctp_setsockopt_bindx(sk, kopt, optlen,
SCTP_BINDX_REM_ADDR);
break;
case SCTP_SOCKOPT_CONNECTX_OLD:
/* 'optlen' is the size of the addresses buffer. */
retval = sctp_setsockopt_connectx_old(sk, kopt, optlen);
break;
case SCTP_SOCKOPT_CONNECTX:
/* 'optlen' is the size of the addresses buffer. */
retval = sctp_setsockopt_connectx(sk, kopt, optlen);
break;
case SCTP_DISABLE_FRAGMENTS:
retval = sctp_setsockopt_disable_fragments(sk, kopt, optlen);
break;
case SCTP_EVENTS:
retval = sctp_setsockopt_events(sk, kopt, optlen);
break;
case SCTP_AUTOCLOSE:
retval = sctp_setsockopt_autoclose(sk, kopt, optlen);
break;
case SCTP_PEER_ADDR_PARAMS:
retval = sctp_setsockopt_peer_addr_params(sk, kopt, optlen);
break;
case SCTP_DELAYED_SACK:
retval = sctp_setsockopt_delayed_ack(sk, kopt, optlen);
break;
case SCTP_PARTIAL_DELIVERY_POINT:
retval = sctp_setsockopt_partial_delivery_point(sk, kopt, optlen);
break;
case SCTP_INITMSG:
retval = sctp_setsockopt_initmsg(sk, kopt, optlen);
break;
case SCTP_DEFAULT_SEND_PARAM:
retval = sctp_setsockopt_default_send_param(sk, kopt, optlen);
break;
case SCTP_DEFAULT_SNDINFO:
retval = sctp_setsockopt_default_sndinfo(sk, kopt, optlen);
break;
case SCTP_PRIMARY_ADDR:
retval = sctp_setsockopt_primary_addr(sk, kopt, optlen);
break;
case SCTP_SET_PEER_PRIMARY_ADDR:
retval = sctp_setsockopt_peer_primary_addr(sk, kopt, optlen);
break;
case SCTP_NODELAY:
retval = sctp_setsockopt_nodelay(sk, kopt, optlen);
break;
case SCTP_RTOINFO:
retval = sctp_setsockopt_rtoinfo(sk, kopt, optlen);
break;
case SCTP_ASSOCINFO:
retval = sctp_setsockopt_associnfo(sk, kopt, optlen);
break;
case SCTP_I_WANT_MAPPED_V4_ADDR:
retval = sctp_setsockopt_mappedv4(sk, kopt, optlen);
break;
case SCTP_MAXSEG:
retval = sctp_setsockopt_maxseg(sk, kopt, optlen);
break;
case SCTP_ADAPTATION_LAYER:
retval = sctp_setsockopt_adaptation_layer(sk, kopt, optlen);
break;
case SCTP_CONTEXT:
retval = sctp_setsockopt_context(sk, kopt, optlen);
break;
case SCTP_FRAGMENT_INTERLEAVE:
retval = sctp_setsockopt_fragment_interleave(sk, kopt, optlen);
break;
case SCTP_MAX_BURST:
retval = sctp_setsockopt_maxburst(sk, kopt, optlen);
break;
case SCTP_AUTH_CHUNK:
retval = sctp_setsockopt_auth_chunk(sk, kopt, optlen);
break;
case SCTP_HMAC_IDENT:
retval = sctp_setsockopt_hmac_ident(sk, kopt, optlen);
break;
case SCTP_AUTH_KEY:
retval = sctp_setsockopt_auth_key(sk, kopt, optlen);
break;
case SCTP_AUTH_ACTIVE_KEY:
retval = sctp_setsockopt_active_key(sk, kopt, optlen);
break;
case SCTP_AUTH_DELETE_KEY:
retval = sctp_setsockopt_del_key(sk, kopt, optlen);
break;
case SCTP_AUTH_DEACTIVATE_KEY:
retval = sctp_setsockopt_deactivate_key(sk, kopt, optlen);
break;
case SCTP_AUTO_ASCONF:
retval = sctp_setsockopt_auto_asconf(sk, kopt, optlen);
break;
case SCTP_PEER_ADDR_THLDS:
retval = sctp_setsockopt_paddr_thresholds(sk, kopt, optlen,
false);
break;
case SCTP_PEER_ADDR_THLDS_V2:
retval = sctp_setsockopt_paddr_thresholds(sk, kopt, optlen,
true);
break;
case SCTP_RECVRCVINFO:
retval = sctp_setsockopt_recvrcvinfo(sk, kopt, optlen);
break;
case SCTP_RECVNXTINFO:
retval = sctp_setsockopt_recvnxtinfo(sk, kopt, optlen);
break;
case SCTP_PR_SUPPORTED:
retval = sctp_setsockopt_pr_supported(sk, kopt, optlen);
break;
case SCTP_DEFAULT_PRINFO:
retval = sctp_setsockopt_default_prinfo(sk, kopt, optlen);
break;
case SCTP_RECONFIG_SUPPORTED:
retval = sctp_setsockopt_reconfig_supported(sk, kopt, optlen);
break;
case SCTP_ENABLE_STREAM_RESET:
retval = sctp_setsockopt_enable_strreset(sk, kopt, optlen);
break;
case SCTP_RESET_STREAMS:
retval = sctp_setsockopt_reset_streams(sk, kopt, optlen);
break;
case SCTP_RESET_ASSOC:
retval = sctp_setsockopt_reset_assoc(sk, kopt, optlen);
break;
case SCTP_ADD_STREAMS:
retval = sctp_setsockopt_add_streams(sk, kopt, optlen);
break;
case SCTP_STREAM_SCHEDULER:
retval = sctp_setsockopt_scheduler(sk, kopt, optlen);
break;
case SCTP_STREAM_SCHEDULER_VALUE:
retval = sctp_setsockopt_scheduler_value(sk, kopt, optlen);
break;
case SCTP_INTERLEAVING_SUPPORTED:
retval = sctp_setsockopt_interleaving_supported(sk, kopt,
optlen);
break;
case SCTP_REUSE_PORT:
retval = sctp_setsockopt_reuse_port(sk, kopt, optlen);
break;
case SCTP_EVENT:
retval = sctp_setsockopt_event(sk, kopt, optlen);
break;
case SCTP_ASCONF_SUPPORTED:
retval = sctp_setsockopt_asconf_supported(sk, kopt, optlen);
break;
case SCTP_AUTH_SUPPORTED:
retval = sctp_setsockopt_auth_supported(sk, kopt, optlen);
break;
case SCTP_ECN_SUPPORTED:
retval = sctp_setsockopt_ecn_supported(sk, kopt, optlen);
break;
case SCTP_EXPOSE_POTENTIALLY_FAILED_STATE:
retval = sctp_setsockopt_pf_expose(sk, kopt, optlen);
break;
case SCTP_REMOTE_UDP_ENCAPS_PORT:
retval = sctp_setsockopt_encap_port(sk, kopt, optlen);
break;
case SCTP_PLPMTUD_PROBE_INTERVAL:
retval = sctp_setsockopt_probe_interval(sk, kopt, optlen);
break;
default:
retval = -ENOPROTOOPT;
break;
}
release_sock(sk);
kfree(kopt);
return retval;
}
/* API 3.1.6 connect() - UDP Style Syntax
*
* An application may use the connect() call in the UDP model to initiate an
* association without sending data.
*
* The syntax is:
*
* ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
*
* sd: the socket descriptor to have a new association added to.
*
* nam: the address structure (either struct sockaddr_in or struct
* sockaddr_in6 defined in RFC2553 [7]).
*
* len: the size of the address.
*/
static int sctp_connect(struct sock *sk, struct sockaddr *addr,
int addr_len, int flags)
{
struct sctp_af *af;
int err = -EINVAL;
lock_sock(sk);
pr_debug("%s: sk:%p, sockaddr:%p, addr_len:%d\n", __func__, sk,
addr, addr_len);
/* Validate addr_len before calling common connect/connectx routine. */
af = sctp_get_af_specific(addr->sa_family);
if (af && addr_len >= af->sockaddr_len)
err = __sctp_connect(sk, addr, af->sockaddr_len, flags, NULL);
release_sock(sk);
return err;
}
int sctp_inet_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
if (addr_len < sizeof(uaddr->sa_family))
return -EINVAL;
if (uaddr->sa_family == AF_UNSPEC)
return -EOPNOTSUPP;
return sctp_connect(sock->sk, uaddr, addr_len, flags);
}
/* FIXME: Write comments. */
static int sctp_disconnect(struct sock *sk, int flags)
{
return -EOPNOTSUPP; /* STUB */
}
/* 4.1.4 accept() - TCP Style Syntax
*
* Applications use accept() call to remove an established SCTP
* association from the accept queue of the endpoint. A new socket
* descriptor will be returned from accept() to represent the newly
* formed association.
*/
static struct sock *sctp_accept(struct sock *sk, int flags, int *err, bool kern)
{
struct sctp_sock *sp;
struct sctp_endpoint *ep;
struct sock *newsk = NULL;
struct sctp_association *asoc;
long timeo;
int error = 0;
lock_sock(sk);
sp = sctp_sk(sk);
ep = sp->ep;
if (!sctp_style(sk, TCP)) {
error = -EOPNOTSUPP;
goto out;
}
if (!sctp_sstate(sk, LISTENING)) {
error = -EINVAL;
goto out;
}
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
error = sctp_wait_for_accept(sk, timeo);
if (error)
goto out;
/* We treat the list of associations on the endpoint as the accept
* queue and pick the first association on the list.
*/
asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
newsk = sp->pf->create_accept_sk(sk, asoc, kern);
if (!newsk) {
error = -ENOMEM;
goto out;
}
/* Populate the fields of the newsk from the oldsk and migrate the
* asoc to the newsk.
*/
error = sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
if (error) {
sk_common_release(newsk);
newsk = NULL;
}
out:
release_sock(sk);
*err = error;
return newsk;
}
/* The SCTP ioctl handler. */
static int sctp_ioctl(struct sock *sk, int cmd, int *karg)
{
int rc = -ENOTCONN;
lock_sock(sk);
/*
* SEQPACKET-style sockets in LISTENING state are valid, for
* SCTP, so only discard TCP-style sockets in LISTENING state.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
goto out;
switch (cmd) {
case SIOCINQ: {
struct sk_buff *skb;
*karg = 0;
skb = skb_peek(&sk->sk_receive_queue);
if (skb != NULL) {
/*
* We will only return the amount of this packet since
* that is all that will be read.
*/
*karg = skb->len;
}
rc = 0;
break;
}
default:
rc = -ENOIOCTLCMD;
break;
}
out:
release_sock(sk);
return rc;
}
/* This is the function which gets called during socket creation to
* initialized the SCTP-specific portion of the sock.
* The sock structure should already be zero-filled memory.
*/
static int sctp_init_sock(struct sock *sk)
{
struct net *net = sock_net(sk);
struct sctp_sock *sp;
pr_debug("%s: sk:%p\n", __func__, sk);
sp = sctp_sk(sk);
/* Initialize the SCTP per socket area. */
switch (sk->sk_type) {
case SOCK_SEQPACKET:
sp->type = SCTP_SOCKET_UDP;
break;
case SOCK_STREAM:
sp->type = SCTP_SOCKET_TCP;
break;
default:
return -ESOCKTNOSUPPORT;
}
sk->sk_gso_type = SKB_GSO_SCTP;
/* Initialize default send parameters. These parameters can be
* modified with the SCTP_DEFAULT_SEND_PARAM socket option.
*/
sp->default_stream = 0;
sp->default_ppid = 0;
sp->default_flags = 0;
sp->default_context = 0;
sp->default_timetolive = 0;
sp->default_rcv_context = 0;
sp->max_burst = net->sctp.max_burst;
sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg;
/* Initialize default setup parameters. These parameters
* can be modified with the SCTP_INITMSG socket option or
* overridden by the SCTP_INIT CMSG.
*/
sp->initmsg.sinit_num_ostreams = sctp_max_outstreams;
sp->initmsg.sinit_max_instreams = sctp_max_instreams;
sp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init;
sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max;
/* Initialize default RTO related parameters. These parameters can
* be modified for with the SCTP_RTOINFO socket option.
*/
sp->rtoinfo.srto_initial = net->sctp.rto_initial;
sp->rtoinfo.srto_max = net->sctp.rto_max;
sp->rtoinfo.srto_min = net->sctp.rto_min;
/* Initialize default association related parameters. These parameters
* can be modified with the SCTP_ASSOCINFO socket option.
*/
sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association;
sp->assocparams.sasoc_number_peer_destinations = 0;
sp->assocparams.sasoc_peer_rwnd = 0;
sp->assocparams.sasoc_local_rwnd = 0;
sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life;
/* Initialize default event subscriptions. By default, all the
* options are off.
*/
sp->subscribe = 0;
/* Default Peer Address Parameters. These defaults can
* be modified via SCTP_PEER_ADDR_PARAMS
*/
sp->hbinterval = net->sctp.hb_interval;
sp->udp_port = htons(net->sctp.udp_port);
sp->encap_port = htons(net->sctp.encap_port);
sp->pathmaxrxt = net->sctp.max_retrans_path;
sp->pf_retrans = net->sctp.pf_retrans;
sp->ps_retrans = net->sctp.ps_retrans;
sp->pf_expose = net->sctp.pf_expose;
sp->pathmtu = 0; /* allow default discovery */
sp->sackdelay = net->sctp.sack_timeout;
sp->sackfreq = 2;
sp->param_flags = SPP_HB_ENABLE |
SPP_PMTUD_ENABLE |
SPP_SACKDELAY_ENABLE;
sp->default_ss = SCTP_SS_DEFAULT;
/* If enabled no SCTP message fragmentation will be performed.
* Configure through SCTP_DISABLE_FRAGMENTS socket option.
*/
sp->disable_fragments = 0;
/* Enable Nagle algorithm by default. */
sp->nodelay = 0;
sp->recvrcvinfo = 0;
sp->recvnxtinfo = 0;
/* Enable by default. */
sp->v4mapped = 1;
/* Auto-close idle associations after the configured
* number of seconds. A value of 0 disables this
* feature. Configure through the SCTP_AUTOCLOSE socket option,
* for UDP-style sockets only.
*/
sp->autoclose = 0;
/* User specified fragmentation limit. */
sp->user_frag = 0;
sp->adaptation_ind = 0;
sp->pf = sctp_get_pf_specific(sk->sk_family);
/* Control variables for partial data delivery. */
atomic_set(&sp->pd_mode, 0);
skb_queue_head_init(&sp->pd_lobby);
sp->frag_interleave = 0;
sp->probe_interval = net->sctp.probe_interval;
/* Create a per socket endpoint structure. Even if we
* change the data structure relationships, this may still
* be useful for storing pre-connect address information.
*/
sp->ep = sctp_endpoint_new(sk, GFP_KERNEL);
if (!sp->ep)
return -ENOMEM;
sp->hmac = NULL;
sk->sk_destruct = sctp_destruct_sock;
SCTP_DBG_OBJCNT_INC(sock);
sk_sockets_allocated_inc(sk);
sock_prot_inuse_add(net, sk->sk_prot, 1);
return 0;
}
/* Cleanup any SCTP per socket resources. Must be called with
* sock_net(sk)->sctp.addr_wq_lock held if sp->do_auto_asconf is true
*/
static void sctp_destroy_sock(struct sock *sk)
{
struct sctp_sock *sp;
pr_debug("%s: sk:%p\n", __func__, sk);
/* Release our hold on the endpoint. */
sp = sctp_sk(sk);
/* This could happen during socket init, thus we bail out
* early, since the rest of the below is not setup either.
*/
if (sp->ep == NULL)
return;
if (sp->do_auto_asconf) {
sp->do_auto_asconf = 0;
list_del(&sp->auto_asconf_list);
}
sctp_endpoint_free(sp->ep);
sk_sockets_allocated_dec(sk);
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
}
/* Triggered when there are no references on the socket anymore */
static void sctp_destruct_common(struct sock *sk)
{
struct sctp_sock *sp = sctp_sk(sk);
/* Free up the HMAC transform. */
crypto_free_shash(sp->hmac);
}
static void sctp_destruct_sock(struct sock *sk)
{
sctp_destruct_common(sk);
inet_sock_destruct(sk);
}
/* API 4.1.7 shutdown() - TCP Style Syntax
* int shutdown(int socket, int how);
*
* sd - the socket descriptor of the association to be closed.
* how - Specifies the type of shutdown. The values are
* as follows:
* SHUT_RD
* Disables further receive operations. No SCTP
* protocol action is taken.
* SHUT_WR
* Disables further send operations, and initiates
* the SCTP shutdown sequence.
* SHUT_RDWR
* Disables further send and receive operations
* and initiates the SCTP shutdown sequence.
*/
static void sctp_shutdown(struct sock *sk, int how)
{
struct net *net = sock_net(sk);
struct sctp_endpoint *ep;
if (!sctp_style(sk, TCP))
return;
ep = sctp_sk(sk)->ep;
if (how & SEND_SHUTDOWN && !list_empty(&ep->asocs)) {
struct sctp_association *asoc;
inet_sk_set_state(sk, SCTP_SS_CLOSING);
asoc = list_entry(ep->asocs.next,
struct sctp_association, asocs);
sctp_primitive_SHUTDOWN(net, asoc, NULL);
}
}
int sctp_get_sctp_info(struct sock *sk, struct sctp_association *asoc,
struct sctp_info *info)
{
struct sctp_transport *prim;
struct list_head *pos;
int mask;
memset(info, 0, sizeof(*info));
if (!asoc) {
struct sctp_sock *sp = sctp_sk(sk);
info->sctpi_s_autoclose = sp->autoclose;
info->sctpi_s_adaptation_ind = sp->adaptation_ind;
info->sctpi_s_pd_point = sp->pd_point;
info->sctpi_s_nodelay = sp->nodelay;
info->sctpi_s_disable_fragments = sp->disable_fragments;
info->sctpi_s_v4mapped = sp->v4mapped;
info->sctpi_s_frag_interleave = sp->frag_interleave;
info->sctpi_s_type = sp->type;
return 0;
}
info->sctpi_tag = asoc->c.my_vtag;
info->sctpi_state = asoc->state;
info->sctpi_rwnd = asoc->a_rwnd;
info->sctpi_unackdata = asoc->unack_data;
info->sctpi_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
info->sctpi_instrms = asoc->stream.incnt;
info->sctpi_outstrms = asoc->stream.outcnt;
list_for_each(pos, &asoc->base.inqueue.in_chunk_list)
info->sctpi_inqueue++;
list_for_each(pos, &asoc->outqueue.out_chunk_list)
info->sctpi_outqueue++;
info->sctpi_overall_error = asoc->overall_error_count;
info->sctpi_max_burst = asoc->max_burst;
info->sctpi_maxseg = asoc->frag_point;
info->sctpi_peer_rwnd = asoc->peer.rwnd;
info->sctpi_peer_tag = asoc->c.peer_vtag;
mask = asoc->peer.intl_capable << 1;
mask = (mask | asoc->peer.ecn_capable) << 1;
mask = (mask | asoc->peer.ipv4_address) << 1;
mask = (mask | asoc->peer.ipv6_address) << 1;
mask = (mask | asoc->peer.reconf_capable) << 1;
mask = (mask | asoc->peer.asconf_capable) << 1;
mask = (mask | asoc->peer.prsctp_capable) << 1;
mask = (mask | asoc->peer.auth_capable);
info->sctpi_peer_capable = mask;
mask = asoc->peer.sack_needed << 1;
mask = (mask | asoc->peer.sack_generation) << 1;
mask = (mask | asoc->peer.zero_window_announced);
info->sctpi_peer_sack = mask;
info->sctpi_isacks = asoc->stats.isacks;
info->sctpi_osacks = asoc->stats.osacks;
info->sctpi_opackets = asoc->stats.opackets;
info->sctpi_ipackets = asoc->stats.ipackets;
info->sctpi_rtxchunks = asoc->stats.rtxchunks;
info->sctpi_outofseqtsns = asoc->stats.outofseqtsns;
info->sctpi_idupchunks = asoc->stats.idupchunks;
info->sctpi_gapcnt = asoc->stats.gapcnt;
info->sctpi_ouodchunks = asoc->stats.ouodchunks;
info->sctpi_iuodchunks = asoc->stats.iuodchunks;
info->sctpi_oodchunks = asoc->stats.oodchunks;
info->sctpi_iodchunks = asoc->stats.iodchunks;
info->sctpi_octrlchunks = asoc->stats.octrlchunks;
info->sctpi_ictrlchunks = asoc->stats.ictrlchunks;
prim = asoc->peer.primary_path;
memcpy(&info->sctpi_p_address, &prim->ipaddr, sizeof(prim->ipaddr));
info->sctpi_p_state = prim->state;
info->sctpi_p_cwnd = prim->cwnd;
info->sctpi_p_srtt = prim->srtt;
info->sctpi_p_rto = jiffies_to_msecs(prim->rto);
info->sctpi_p_hbinterval = prim->hbinterval;
info->sctpi_p_pathmaxrxt = prim->pathmaxrxt;
info->sctpi_p_sackdelay = jiffies_to_msecs(prim->sackdelay);
info->sctpi_p_ssthresh = prim->ssthresh;
info->sctpi_p_partial_bytes_acked = prim->partial_bytes_acked;
info->sctpi_p_flight_size = prim->flight_size;
info->sctpi_p_error = prim->error_count;
return 0;
}
EXPORT_SYMBOL_GPL(sctp_get_sctp_info);
/* use callback to avoid exporting the core structure */
void sctp_transport_walk_start(struct rhashtable_iter *iter) __acquires(RCU)
{
rhltable_walk_enter(&sctp_transport_hashtable, iter);
rhashtable_walk_start(iter);
}
void sctp_transport_walk_stop(struct rhashtable_iter *iter) __releases(RCU)
{
rhashtable_walk_stop(iter);
rhashtable_walk_exit(iter);
}
struct sctp_transport *sctp_transport_get_next(struct net *net,
struct rhashtable_iter *iter)
{
struct sctp_transport *t;
t = rhashtable_walk_next(iter);
for (; t; t = rhashtable_walk_next(iter)) {
if (IS_ERR(t)) {
if (PTR_ERR(t) == -EAGAIN)
continue;
break;
}
if (!sctp_transport_hold(t))
continue;
if (net_eq(t->asoc->base.net, net) &&
t->asoc->peer.primary_path == t)
break;
sctp_transport_put(t);
}
return t;
}
struct sctp_transport *sctp_transport_get_idx(struct net *net,
struct rhashtable_iter *iter,
int pos)
{
struct sctp_transport *t;
if (!pos)
return SEQ_START_TOKEN;
while ((t = sctp_transport_get_next(net, iter)) && !IS_ERR(t)) {
if (!--pos)
break;
sctp_transport_put(t);
}
return t;
}
int sctp_for_each_endpoint(int (*cb)(struct sctp_endpoint *, void *),
void *p) {
int err = 0;
int hash = 0;
struct sctp_endpoint *ep;
struct sctp_hashbucket *head;
for (head = sctp_ep_hashtable; hash < sctp_ep_hashsize;
hash++, head++) {
read_lock_bh(&head->lock);
sctp_for_each_hentry(ep, &head->chain) {
err = cb(ep, p);
if (err)
break;
}
read_unlock_bh(&head->lock);
}
return err;
}
EXPORT_SYMBOL_GPL(sctp_for_each_endpoint);
int sctp_transport_lookup_process(sctp_callback_t cb, struct net *net,
const union sctp_addr *laddr,
const union sctp_addr *paddr, void *p, int dif)
{
struct sctp_transport *transport;
struct sctp_endpoint *ep;
int err = -ENOENT;
rcu_read_lock();
transport = sctp_addrs_lookup_transport(net, laddr, paddr, dif, dif);
if (!transport) {
rcu_read_unlock();
return err;
}
ep = transport->asoc->ep;
if (!sctp_endpoint_hold(ep)) { /* asoc can be peeled off */
sctp_transport_put(transport);
rcu_read_unlock();
return err;
}
rcu_read_unlock();
err = cb(ep, transport, p);
sctp_endpoint_put(ep);
sctp_transport_put(transport);
return err;
}
EXPORT_SYMBOL_GPL(sctp_transport_lookup_process);
int sctp_transport_traverse_process(sctp_callback_t cb, sctp_callback_t cb_done,
struct net *net, int *pos, void *p)
{
struct rhashtable_iter hti;
struct sctp_transport *tsp;
struct sctp_endpoint *ep;
int ret;
again:
ret = 0;
sctp_transport_walk_start(&hti);
tsp = sctp_transport_get_idx(net, &hti, *pos + 1);
for (; !IS_ERR_OR_NULL(tsp); tsp = sctp_transport_get_next(net, &hti)) {
ep = tsp->asoc->ep;
if (sctp_endpoint_hold(ep)) { /* asoc can be peeled off */
ret = cb(ep, tsp, p);
if (ret)
break;
sctp_endpoint_put(ep);
}
(*pos)++;
sctp_transport_put(tsp);
}
sctp_transport_walk_stop(&hti);
if (ret) {
if (cb_done && !cb_done(ep, tsp, p)) {
(*pos)++;
sctp_endpoint_put(ep);
sctp_transport_put(tsp);
goto again;
}
sctp_endpoint_put(ep);
sctp_transport_put(tsp);
}
return ret;
}
EXPORT_SYMBOL_GPL(sctp_transport_traverse_process);
/* 7.2.1 Association Status (SCTP_STATUS)
* Applications can retrieve current status information about an
* association, including association state, peer receiver window size,
* number of unacked data chunks, and number of data chunks pending
* receipt. This information is read-only.
*/
static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_status status;
struct sctp_association *asoc = NULL;
struct sctp_transport *transport;
sctp_assoc_t associd;
int retval = 0;
if (len < sizeof(status)) {
retval = -EINVAL;
goto out;
}
len = sizeof(status);
if (copy_from_user(&status, optval, len)) {
retval = -EFAULT;
goto out;
}
associd = status.sstat_assoc_id;
asoc = sctp_id2assoc(sk, associd);
if (!asoc) {
retval = -EINVAL;
goto out;
}
transport = asoc->peer.primary_path;
status.sstat_assoc_id = sctp_assoc2id(asoc);
status.sstat_state = sctp_assoc_to_state(asoc);
status.sstat_rwnd = asoc->peer.rwnd;
status.sstat_unackdata = asoc->unack_data;
status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
status.sstat_instrms = asoc->stream.incnt;
status.sstat_outstrms = asoc->stream.outcnt;
status.sstat_fragmentation_point = asoc->frag_point;
status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr,
transport->af_specific->sockaddr_len);
/* Map ipv4 address into v4-mapped-on-v6 address. */
sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
(union sctp_addr *)&status.sstat_primary.spinfo_address);
status.sstat_primary.spinfo_state = transport->state;
status.sstat_primary.spinfo_cwnd = transport->cwnd;
status.sstat_primary.spinfo_srtt = transport->srtt;
status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
status.sstat_primary.spinfo_mtu = transport->pathmtu;
if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN)
status.sstat_primary.spinfo_state = SCTP_ACTIVE;
if (put_user(len, optlen)) {
retval = -EFAULT;
goto out;
}
pr_debug("%s: len:%d, state:%d, rwnd:%d, assoc_id:%d\n",
__func__, len, status.sstat_state, status.sstat_rwnd,
status.sstat_assoc_id);
if (copy_to_user(optval, &status, len)) {
retval = -EFAULT;
goto out;
}
out:
return retval;
}
/* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
*
* Applications can retrieve information about a specific peer address
* of an association, including its reachability state, congestion
* window, and retransmission timer values. This information is
* read-only.
*/
static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_paddrinfo pinfo;
struct sctp_transport *transport;
int retval = 0;
if (len < sizeof(pinfo)) {
retval = -EINVAL;
goto out;
}
len = sizeof(pinfo);
if (copy_from_user(&pinfo, optval, len)) {
retval = -EFAULT;
goto out;
}
transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
pinfo.spinfo_assoc_id);
if (!transport) {
retval = -EINVAL;
goto out;
}
if (transport->state == SCTP_PF &&
transport->asoc->pf_expose == SCTP_PF_EXPOSE_DISABLE) {
retval = -EACCES;
goto out;
}
pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
pinfo.spinfo_state = transport->state;
pinfo.spinfo_cwnd = transport->cwnd;
pinfo.spinfo_srtt = transport->srtt;
pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
pinfo.spinfo_mtu = transport->pathmtu;
if (pinfo.spinfo_state == SCTP_UNKNOWN)
pinfo.spinfo_state = SCTP_ACTIVE;
if (put_user(len, optlen)) {
retval = -EFAULT;
goto out;
}
if (copy_to_user(optval, &pinfo, len)) {
retval = -EFAULT;
goto out;
}
out:
return retval;
}
/* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
*
* This option is a on/off flag. If enabled no SCTP message
* fragmentation will be performed. Instead if a message being sent
* exceeds the current PMTU size, the message will NOT be sent and
* instead a error will be indicated to the user.
*/
static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
int val;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = (sctp_sk(sk)->disable_fragments == 1);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
*
* This socket option is used to specify various notifications and
* ancillary data the user wishes to receive.
*/
static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
int __user *optlen)
{
struct sctp_event_subscribe subscribe;
__u8 *sn_type = (__u8 *)&subscribe;
int i;
if (len == 0)
return -EINVAL;
if (len > sizeof(struct sctp_event_subscribe))
len = sizeof(struct sctp_event_subscribe);
if (put_user(len, optlen))
return -EFAULT;
for (i = 0; i < len; i++)
sn_type[i] = sctp_ulpevent_type_enabled(sctp_sk(sk)->subscribe,
SCTP_SN_TYPE_BASE + i);
if (copy_to_user(optval, &subscribe, len))
return -EFAULT;
return 0;
}
/* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
*
* This socket option is applicable to the UDP-style socket only. When
* set it will cause associations that are idle for more than the
* specified number of seconds to automatically close. An association
* being idle is defined an association that has NOT sent or received
* user data. The special value of '0' indicates that no automatic
* close of any associations should be performed. The option expects an
* integer defining the number of seconds of idle time before an
* association is closed.
*/
static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
{
/* Applicable to UDP-style socket only */
if (sctp_style(sk, TCP))
return -EOPNOTSUPP;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
if (put_user(len, optlen))
return -EFAULT;
if (put_user(sctp_sk(sk)->autoclose, (int __user *)optval))
return -EFAULT;
return 0;
}
/* Helper routine to branch off an association to a new socket. */
int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
{
struct sctp_association *asoc = sctp_id2assoc(sk, id);
struct sctp_sock *sp = sctp_sk(sk);
struct socket *sock;
int err = 0;
/* Do not peel off from one netns to another one. */
if (!net_eq(current->nsproxy->net_ns, sock_net(sk)))
return -EINVAL;
if (!asoc)
return -EINVAL;
/* An association cannot be branched off from an already peeled-off
* socket, nor is this supported for tcp style sockets.
*/
if (!sctp_style(sk, UDP))
return -EINVAL;
/* Create a new socket. */
err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
if (err < 0)
return err;
sctp_copy_sock(sock->sk, sk, asoc);
/* Make peeled-off sockets more like 1-1 accepted sockets.
* Set the daddr and initialize id to something more random and also
* copy over any ip options.
*/
sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sock->sk);
sp->pf->copy_ip_options(sk, sock->sk);
/* Populate the fields of the newsk from the oldsk and migrate the
* asoc to the newsk.
*/
err = sctp_sock_migrate(sk, sock->sk, asoc,
SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
if (err) {
sock_release(sock);
sock = NULL;
}
*sockp = sock;
return err;
}
EXPORT_SYMBOL(sctp_do_peeloff);
static int sctp_getsockopt_peeloff_common(struct sock *sk, sctp_peeloff_arg_t *peeloff,
struct file **newfile, unsigned flags)
{
struct socket *newsock;
int retval;
retval = sctp_do_peeloff(sk, peeloff->associd, &newsock);
if (retval < 0)
goto out;
/* Map the socket to an unused fd that can be returned to the user. */
retval = get_unused_fd_flags(flags & SOCK_CLOEXEC);
if (retval < 0) {
sock_release(newsock);
goto out;
}
*newfile = sock_alloc_file(newsock, 0, NULL);
if (IS_ERR(*newfile)) {
put_unused_fd(retval);
retval = PTR_ERR(*newfile);
*newfile = NULL;
return retval;
}
pr_debug("%s: sk:%p, newsk:%p, sd:%d\n", __func__, sk, newsock->sk,
retval);
peeloff->sd = retval;
if (flags & SOCK_NONBLOCK)
(*newfile)->f_flags |= O_NONBLOCK;
out:
return retval;
}
static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
{
sctp_peeloff_arg_t peeloff;
struct file *newfile = NULL;
int retval = 0;
if (len < sizeof(sctp_peeloff_arg_t))
return -EINVAL;
len = sizeof(sctp_peeloff_arg_t);
if (copy_from_user(&peeloff, optval, len))
return -EFAULT;
retval = sctp_getsockopt_peeloff_common(sk, &peeloff, &newfile, 0);
if (retval < 0)
goto out;
/* Return the fd mapped to the new socket. */
if (put_user(len, optlen)) {
fput(newfile);
put_unused_fd(retval);
return -EFAULT;
}
if (copy_to_user(optval, &peeloff, len)) {
fput(newfile);
put_unused_fd(retval);
return -EFAULT;
}
fd_install(retval, newfile);
out:
return retval;
}
static int sctp_getsockopt_peeloff_flags(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
sctp_peeloff_flags_arg_t peeloff;
struct file *newfile = NULL;
int retval = 0;
if (len < sizeof(sctp_peeloff_flags_arg_t))
return -EINVAL;
len = sizeof(sctp_peeloff_flags_arg_t);
if (copy_from_user(&peeloff, optval, len))
return -EFAULT;
retval = sctp_getsockopt_peeloff_common(sk, &peeloff.p_arg,
&newfile, peeloff.flags);
if (retval < 0)
goto out;
/* Return the fd mapped to the new socket. */
if (put_user(len, optlen)) {
fput(newfile);
put_unused_fd(retval);
return -EFAULT;
}
if (copy_to_user(optval, &peeloff, len)) {
fput(newfile);
put_unused_fd(retval);
return -EFAULT;
}
fd_install(retval, newfile);
out:
return retval;
}
/* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
*
* Applications can enable or disable heartbeats for any peer address of
* an association, modify an address's heartbeat interval, force a
* heartbeat to be sent immediately, and adjust the address's maximum
* number of retransmissions sent before an address is considered
* unreachable. The following structure is used to access and modify an
* address's parameters:
*
* struct sctp_paddrparams {
* sctp_assoc_t spp_assoc_id;
* struct sockaddr_storage spp_address;
* uint32_t spp_hbinterval;
* uint16_t spp_pathmaxrxt;
* uint32_t spp_pathmtu;
* uint32_t spp_sackdelay;
* uint32_t spp_flags;
* };
*
* spp_assoc_id - (one-to-many style socket) This is filled in the
* application, and identifies the association for
* this query.
* spp_address - This specifies which address is of interest.
* spp_hbinterval - This contains the value of the heartbeat interval,
* in milliseconds. If a value of zero
* is present in this field then no changes are to
* be made to this parameter.
* spp_pathmaxrxt - This contains the maximum number of
* retransmissions before this address shall be
* considered unreachable. If a value of zero
* is present in this field then no changes are to
* be made to this parameter.
* spp_pathmtu - When Path MTU discovery is disabled the value
* specified here will be the "fixed" path mtu.
* Note that if the spp_address field is empty
* then all associations on this address will
* have this fixed path mtu set upon them.
*
* spp_sackdelay - When delayed sack is enabled, this value specifies
* the number of milliseconds that sacks will be delayed
* for. This value will apply to all addresses of an
* association if the spp_address field is empty. Note
* also, that if delayed sack is enabled and this
* value is set to 0, no change is made to the last
* recorded delayed sack timer value.
*
* spp_flags - These flags are used to control various features
* on an association. The flag field may contain
* zero or more of the following options.
*
* SPP_HB_ENABLE - Enable heartbeats on the
* specified address. Note that if the address
* field is empty all addresses for the association
* have heartbeats enabled upon them.
*
* SPP_HB_DISABLE - Disable heartbeats on the
* speicifed address. Note that if the address
* field is empty all addresses for the association
* will have their heartbeats disabled. Note also
* that SPP_HB_ENABLE and SPP_HB_DISABLE are
* mutually exclusive, only one of these two should
* be specified. Enabling both fields will have
* undetermined results.
*
* SPP_HB_DEMAND - Request a user initiated heartbeat
* to be made immediately.
*
* SPP_PMTUD_ENABLE - This field will enable PMTU
* discovery upon the specified address. Note that
* if the address feild is empty then all addresses
* on the association are effected.
*
* SPP_PMTUD_DISABLE - This field will disable PMTU
* discovery upon the specified address. Note that
* if the address feild is empty then all addresses
* on the association are effected. Not also that
* SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
* exclusive. Enabling both will have undetermined
* results.
*
* SPP_SACKDELAY_ENABLE - Setting this flag turns
* on delayed sack. The time specified in spp_sackdelay
* is used to specify the sack delay for this address. Note
* that if spp_address is empty then all addresses will
* enable delayed sack and take on the sack delay
* value specified in spp_sackdelay.
* SPP_SACKDELAY_DISABLE - Setting this flag turns
* off delayed sack. If the spp_address field is blank then
* delayed sack is disabled for the entire association. Note
* also that this field is mutually exclusive to
* SPP_SACKDELAY_ENABLE, setting both will have undefined
* results.
*
* SPP_IPV6_FLOWLABEL: Setting this flag enables the
* setting of the IPV6 flow label value. The value is
* contained in the spp_ipv6_flowlabel field.
* Upon retrieval, this flag will be set to indicate that
* the spp_ipv6_flowlabel field has a valid value returned.
* If a specific destination address is set (in the
* spp_address field), then the value returned is that of
* the address. If just an association is specified (and
* no address), then the association's default flow label
* is returned. If neither an association nor a destination
* is specified, then the socket's default flow label is
* returned. For non-IPv6 sockets, this flag will be left
* cleared.
*
* SPP_DSCP: Setting this flag enables the setting of the
* Differentiated Services Code Point (DSCP) value
* associated with either the association or a specific
* address. The value is obtained in the spp_dscp field.
* Upon retrieval, this flag will be set to indicate that
* the spp_dscp field has a valid value returned. If a
* specific destination address is set when called (in the
* spp_address field), then that specific destination
* address's DSCP value is returned. If just an association
* is specified, then the association's default DSCP is
* returned. If neither an association nor a destination is
* specified, then the socket's default DSCP is returned.
*
* spp_ipv6_flowlabel
* - This field is used in conjunction with the
* SPP_IPV6_FLOWLABEL flag and contains the IPv6 flow label.
* The 20 least significant bits are used for the flow
* label. This setting has precedence over any IPv6-layer
* setting.
*
* spp_dscp - This field is used in conjunction with the SPP_DSCP flag
* and contains the DSCP. The 6 most significant bits are
* used for the DSCP. This setting has precedence over any
* IPv4- or IPv6- layer setting.
*/
static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_paddrparams params;
struct sctp_transport *trans = NULL;
struct sctp_association *asoc = NULL;
struct sctp_sock *sp = sctp_sk(sk);
if (len >= sizeof(params))
len = sizeof(params);
else if (len >= ALIGN(offsetof(struct sctp_paddrparams,
spp_ipv6_flowlabel), 4))
len = ALIGN(offsetof(struct sctp_paddrparams,
spp_ipv6_flowlabel), 4);
else
return -EINVAL;
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
/* If an address other than INADDR_ANY is specified, and
* no transport is found, then the request is invalid.
*/
if (!sctp_is_any(sk, (union sctp_addr *)¶ms.spp_address)) {
trans = sctp_addr_id2transport(sk, ¶ms.spp_address,
params.spp_assoc_id);
if (!trans) {
pr_debug("%s: failed no transport\n", __func__);
return -EINVAL;
}
}
/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
* socket is a one to many style socket, and an association
* was not found, then the id was invalid.
*/
asoc = sctp_id2assoc(sk, params.spp_assoc_id);
if (!asoc && params.spp_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
pr_debug("%s: failed no association\n", __func__);
return -EINVAL;
}
if (trans) {
/* Fetch transport values. */
params.spp_hbinterval = jiffies_to_msecs(trans->hbinterval);
params.spp_pathmtu = trans->pathmtu;
params.spp_pathmaxrxt = trans->pathmaxrxt;
params.spp_sackdelay = jiffies_to_msecs(trans->sackdelay);
/*draft-11 doesn't say what to return in spp_flags*/
params.spp_flags = trans->param_flags;
if (trans->flowlabel & SCTP_FLOWLABEL_SET_MASK) {
params.spp_ipv6_flowlabel = trans->flowlabel &
SCTP_FLOWLABEL_VAL_MASK;
params.spp_flags |= SPP_IPV6_FLOWLABEL;
}
if (trans->dscp & SCTP_DSCP_SET_MASK) {
params.spp_dscp = trans->dscp & SCTP_DSCP_VAL_MASK;
params.spp_flags |= SPP_DSCP;
}
} else if (asoc) {
/* Fetch association values. */
params.spp_hbinterval = jiffies_to_msecs(asoc->hbinterval);
params.spp_pathmtu = asoc->pathmtu;
params.spp_pathmaxrxt = asoc->pathmaxrxt;
params.spp_sackdelay = jiffies_to_msecs(asoc->sackdelay);
/*draft-11 doesn't say what to return in spp_flags*/
params.spp_flags = asoc->param_flags;
if (asoc->flowlabel & SCTP_FLOWLABEL_SET_MASK) {
params.spp_ipv6_flowlabel = asoc->flowlabel &
SCTP_FLOWLABEL_VAL_MASK;
params.spp_flags |= SPP_IPV6_FLOWLABEL;
}
if (asoc->dscp & SCTP_DSCP_SET_MASK) {
params.spp_dscp = asoc->dscp & SCTP_DSCP_VAL_MASK;
params.spp_flags |= SPP_DSCP;
}
} else {
/* Fetch socket values. */
params.spp_hbinterval = sp->hbinterval;
params.spp_pathmtu = sp->pathmtu;
params.spp_sackdelay = sp->sackdelay;
params.spp_pathmaxrxt = sp->pathmaxrxt;
/*draft-11 doesn't say what to return in spp_flags*/
params.spp_flags = sp->param_flags;
if (sp->flowlabel & SCTP_FLOWLABEL_SET_MASK) {
params.spp_ipv6_flowlabel = sp->flowlabel &
SCTP_FLOWLABEL_VAL_MASK;
params.spp_flags |= SPP_IPV6_FLOWLABEL;
}
if (sp->dscp & SCTP_DSCP_SET_MASK) {
params.spp_dscp = sp->dscp & SCTP_DSCP_VAL_MASK;
params.spp_flags |= SPP_DSCP;
}
}
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
/*
* 7.1.23. Get or set delayed ack timer (SCTP_DELAYED_SACK)
*
* This option will effect the way delayed acks are performed. This
* option allows you to get or set the delayed ack time, in
* milliseconds. It also allows changing the delayed ack frequency.
* Changing the frequency to 1 disables the delayed sack algorithm. If
* the assoc_id is 0, then this sets or gets the endpoints default
* values. If the assoc_id field is non-zero, then the set or get
* effects the specified association for the one to many model (the
* assoc_id field is ignored by the one to one model). Note that if
* sack_delay or sack_freq are 0 when setting this option, then the
* current values will remain unchanged.
*
* struct sctp_sack_info {
* sctp_assoc_t sack_assoc_id;
* uint32_t sack_delay;
* uint32_t sack_freq;
* };
*
* sack_assoc_id - This parameter, indicates which association the user
* is performing an action upon. Note that if this field's value is
* zero then the endpoints default value is changed (effecting future
* associations only).
*
* sack_delay - This parameter contains the number of milliseconds that
* the user is requesting the delayed ACK timer be set to. Note that
* this value is defined in the standard to be between 200 and 500
* milliseconds.
*
* sack_freq - This parameter contains the number of packets that must
* be received before a sack is sent without waiting for the delay
* timer to expire. The default value for this is 2, setting this
* value to 1 will disable the delayed sack algorithm.
*/
static int sctp_getsockopt_delayed_ack(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_sack_info params;
struct sctp_association *asoc = NULL;
struct sctp_sock *sp = sctp_sk(sk);
if (len >= sizeof(struct sctp_sack_info)) {
len = sizeof(struct sctp_sack_info);
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
} else if (len == sizeof(struct sctp_assoc_value)) {
pr_warn_ratelimited(DEPRECATED
"%s (pid %d) "
"Use of struct sctp_assoc_value in delayed_ack socket option.\n"
"Use struct sctp_sack_info instead\n",
current->comm, task_pid_nr(current));
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
} else
return -EINVAL;
/* Get association, if sack_assoc_id != SCTP_FUTURE_ASSOC and the
* socket is a one to many style socket, and an association
* was not found, then the id was invalid.
*/
asoc = sctp_id2assoc(sk, params.sack_assoc_id);
if (!asoc && params.sack_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
/* Fetch association values. */
if (asoc->param_flags & SPP_SACKDELAY_ENABLE) {
params.sack_delay = jiffies_to_msecs(asoc->sackdelay);
params.sack_freq = asoc->sackfreq;
} else {
params.sack_delay = 0;
params.sack_freq = 1;
}
} else {
/* Fetch socket values. */
if (sp->param_flags & SPP_SACKDELAY_ENABLE) {
params.sack_delay = sp->sackdelay;
params.sack_freq = sp->sackfreq;
} else {
params.sack_delay = 0;
params.sack_freq = 1;
}
}
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
/* 7.1.3 Initialization Parameters (SCTP_INITMSG)
*
* Applications can specify protocol parameters for the default association
* initialization. The option name argument to setsockopt() and getsockopt()
* is SCTP_INITMSG.
*
* Setting initialization parameters is effective only on an unconnected
* socket (for UDP-style sockets only future associations are effected
* by the change). With TCP-style sockets, this option is inherited by
* sockets derived from a listener socket.
*/
static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
{
if (len < sizeof(struct sctp_initmsg))
return -EINVAL;
len = sizeof(struct sctp_initmsg);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_association *asoc;
int cnt = 0;
struct sctp_getaddrs getaddrs;
struct sctp_transport *from;
void __user *to;
union sctp_addr temp;
struct sctp_sock *sp = sctp_sk(sk);
int addrlen;
size_t space_left;
int bytes_copied;
if (len < sizeof(struct sctp_getaddrs))
return -EINVAL;
if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
return -EFAULT;
/* For UDP-style sockets, id specifies the association to query. */
asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
if (!asoc)
return -EINVAL;
to = optval + offsetof(struct sctp_getaddrs, addrs);
space_left = len - offsetof(struct sctp_getaddrs, addrs);
list_for_each_entry(from, &asoc->peer.transport_addr_list,
transports) {
memcpy(&temp, &from->ipaddr, sizeof(temp));
addrlen = sctp_get_pf_specific(sk->sk_family)
->addr_to_user(sp, &temp);
if (space_left < addrlen)
return -ENOMEM;
if (copy_to_user(to, &temp, addrlen))
return -EFAULT;
to += addrlen;
cnt++;
space_left -= addrlen;
}
if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num))
return -EFAULT;
bytes_copied = ((char __user *)to) - optval;
if (put_user(bytes_copied, optlen))
return -EFAULT;
return 0;
}
static int sctp_copy_laddrs(struct sock *sk, __u16 port, void *to,
size_t space_left, int *bytes_copied)
{
struct sctp_sockaddr_entry *addr;
union sctp_addr temp;
int cnt = 0;
int addrlen;
struct net *net = sock_net(sk);
rcu_read_lock();
list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) {
if (!addr->valid)
continue;
if ((PF_INET == sk->sk_family) &&
(AF_INET6 == addr->a.sa.sa_family))
continue;
if ((PF_INET6 == sk->sk_family) &&
inet_v6_ipv6only(sk) &&
(AF_INET == addr->a.sa.sa_family))
continue;
memcpy(&temp, &addr->a, sizeof(temp));
if (!temp.v4.sin_port)
temp.v4.sin_port = htons(port);
addrlen = sctp_get_pf_specific(sk->sk_family)
->addr_to_user(sctp_sk(sk), &temp);
if (space_left < addrlen) {
cnt = -ENOMEM;
break;
}
memcpy(to, &temp, addrlen);
to += addrlen;
cnt++;
space_left -= addrlen;
*bytes_copied += addrlen;
}
rcu_read_unlock();
return cnt;
}
static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_bind_addr *bp;
struct sctp_association *asoc;
int cnt = 0;
struct sctp_getaddrs getaddrs;
struct sctp_sockaddr_entry *addr;
void __user *to;
union sctp_addr temp;
struct sctp_sock *sp = sctp_sk(sk);
int addrlen;
int err = 0;
size_t space_left;
int bytes_copied = 0;
void *addrs;
void *buf;
if (len < sizeof(struct sctp_getaddrs))
return -EINVAL;
if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
return -EFAULT;
/*
* For UDP-style sockets, id specifies the association to query.
* If the id field is set to the value '0' then the locally bound
* addresses are returned without regard to any particular
* association.
*/
if (0 == getaddrs.assoc_id) {
bp = &sctp_sk(sk)->ep->base.bind_addr;
} else {
asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
if (!asoc)
return -EINVAL;
bp = &asoc->base.bind_addr;
}
to = optval + offsetof(struct sctp_getaddrs, addrs);
space_left = len - offsetof(struct sctp_getaddrs, addrs);
addrs = kmalloc(space_left, GFP_USER | __GFP_NOWARN);
if (!addrs)
return -ENOMEM;
/* If the endpoint is bound to 0.0.0.0 or ::0, get the valid
* addresses from the global local address list.
*/
if (sctp_list_single_entry(&bp->address_list)) {
addr = list_entry(bp->address_list.next,
struct sctp_sockaddr_entry, list);
if (sctp_is_any(sk, &addr->a)) {
cnt = sctp_copy_laddrs(sk, bp->port, addrs,
space_left, &bytes_copied);
if (cnt < 0) {
err = cnt;
goto out;
}
goto copy_getaddrs;
}
}
buf = addrs;
/* Protection on the bound address list is not needed since
* in the socket option context we hold a socket lock and
* thus the bound address list can't change.
*/
list_for_each_entry(addr, &bp->address_list, list) {
memcpy(&temp, &addr->a, sizeof(temp));
addrlen = sctp_get_pf_specific(sk->sk_family)
->addr_to_user(sp, &temp);
if (space_left < addrlen) {
err = -ENOMEM; /*fixme: right error?*/
goto out;
}
memcpy(buf, &temp, addrlen);
buf += addrlen;
bytes_copied += addrlen;
cnt++;
space_left -= addrlen;
}
copy_getaddrs:
if (copy_to_user(to, addrs, bytes_copied)) {
err = -EFAULT;
goto out;
}
if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num)) {
err = -EFAULT;
goto out;
}
/* XXX: We should have accounted for sizeof(struct sctp_getaddrs) too,
* but we can't change it anymore.
*/
if (put_user(bytes_copied, optlen))
err = -EFAULT;
out:
kfree(addrs);
return err;
}
/* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
*
* Requests that the local SCTP stack use the enclosed peer address as
* the association primary. The enclosed address must be one of the
* association peer's addresses.
*/
static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_prim prim;
struct sctp_association *asoc;
struct sctp_sock *sp = sctp_sk(sk);
if (len < sizeof(struct sctp_prim))
return -EINVAL;
len = sizeof(struct sctp_prim);
if (copy_from_user(&prim, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
if (!asoc)
return -EINVAL;
if (!asoc->peer.primary_path)
return -ENOTCONN;
memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
asoc->peer.primary_path->af_specific->sockaddr_len);
sctp_get_pf_specific(sk->sk_family)->addr_to_user(sp,
(union sctp_addr *)&prim.ssp_addr);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &prim, len))
return -EFAULT;
return 0;
}
/*
* 7.1.11 Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER)
*
* Requests that the local endpoint set the specified Adaptation Layer
* Indication parameter for all future INIT and INIT-ACK exchanges.
*/
static int sctp_getsockopt_adaptation_layer(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_setadaptation adaptation;
if (len < sizeof(struct sctp_setadaptation))
return -EINVAL;
len = sizeof(struct sctp_setadaptation);
adaptation.ssb_adaptation_ind = sctp_sk(sk)->adaptation_ind;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &adaptation, len))
return -EFAULT;
return 0;
}
/*
*
* 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
*
* Applications that wish to use the sendto() system call may wish to
* specify a default set of parameters that would normally be supplied
* through the inclusion of ancillary data. This socket option allows
* such an application to set the default sctp_sndrcvinfo structure.
* The application that wishes to use this socket option simply passes
* in to this call the sctp_sndrcvinfo structure defined in Section
* 5.2.2) The input parameters accepted by this call include
* sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
* sinfo_timetolive. The user must provide the sinfo_assoc_id field in
* to this call if the caller is using the UDP model.
*
* For getsockopt, it get the default sctp_sndrcvinfo structure.
*/
static int sctp_getsockopt_default_send_param(struct sock *sk,
int len, char __user *optval,
int __user *optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
struct sctp_sndrcvinfo info;
if (len < sizeof(info))
return -EINVAL;
len = sizeof(info);
if (copy_from_user(&info, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
if (!asoc && info.sinfo_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
info.sinfo_stream = asoc->default_stream;
info.sinfo_flags = asoc->default_flags;
info.sinfo_ppid = asoc->default_ppid;
info.sinfo_context = asoc->default_context;
info.sinfo_timetolive = asoc->default_timetolive;
} else {
info.sinfo_stream = sp->default_stream;
info.sinfo_flags = sp->default_flags;
info.sinfo_ppid = sp->default_ppid;
info.sinfo_context = sp->default_context;
info.sinfo_timetolive = sp->default_timetolive;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &info, len))
return -EFAULT;
return 0;
}
/* RFC6458, Section 8.1.31. Set/get Default Send Parameters
* (SCTP_DEFAULT_SNDINFO)
*/
static int sctp_getsockopt_default_sndinfo(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
struct sctp_sndinfo info;
if (len < sizeof(info))
return -EINVAL;
len = sizeof(info);
if (copy_from_user(&info, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, info.snd_assoc_id);
if (!asoc && info.snd_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
info.snd_sid = asoc->default_stream;
info.snd_flags = asoc->default_flags;
info.snd_ppid = asoc->default_ppid;
info.snd_context = asoc->default_context;
} else {
info.snd_sid = sp->default_stream;
info.snd_flags = sp->default_flags;
info.snd_ppid = sp->default_ppid;
info.snd_context = sp->default_context;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &info, len))
return -EFAULT;
return 0;
}
/*
*
* 7.1.5 SCTP_NODELAY
*
* Turn on/off any Nagle-like algorithm. This means that packets are
* generally sent as soon as possible and no unnecessary delays are
* introduced, at the cost of more packets in the network. Expects an
* integer boolean flag.
*/
static int sctp_getsockopt_nodelay(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
int val;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = (sctp_sk(sk)->nodelay == 1);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
*
* 7.1.1 SCTP_RTOINFO
*
* The protocol parameters used to initialize and bound retransmission
* timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
* and modify these parameters.
* All parameters are time values, in milliseconds. A value of 0, when
* modifying the parameters, indicates that the current value should not
* be changed.
*
*/
static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
char __user *optval,
int __user *optlen) {
struct sctp_rtoinfo rtoinfo;
struct sctp_association *asoc;
if (len < sizeof (struct sctp_rtoinfo))
return -EINVAL;
len = sizeof(struct sctp_rtoinfo);
if (copy_from_user(&rtoinfo, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
if (!asoc && rtoinfo.srto_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
/* Values corresponding to the specific association. */
if (asoc) {
rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
} else {
/* Values corresponding to the endpoint. */
struct sctp_sock *sp = sctp_sk(sk);
rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
rtoinfo.srto_max = sp->rtoinfo.srto_max;
rtoinfo.srto_min = sp->rtoinfo.srto_min;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &rtoinfo, len))
return -EFAULT;
return 0;
}
/*
*
* 7.1.2 SCTP_ASSOCINFO
*
* This option is used to tune the maximum retransmission attempts
* of the association.
* Returns an error if the new association retransmission value is
* greater than the sum of the retransmission value of the peer.
* See [SCTP] for more information.
*
*/
static int sctp_getsockopt_associnfo(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assocparams assocparams;
struct sctp_association *asoc;
struct list_head *pos;
int cnt = 0;
if (len < sizeof (struct sctp_assocparams))
return -EINVAL;
len = sizeof(struct sctp_assocparams);
if (copy_from_user(&assocparams, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
if (!asoc && assocparams.sasoc_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
/* Values correspoinding to the specific association */
if (asoc) {
assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
assocparams.sasoc_local_rwnd = asoc->a_rwnd;
assocparams.sasoc_cookie_life = ktime_to_ms(asoc->cookie_life);
list_for_each(pos, &asoc->peer.transport_addr_list) {
cnt++;
}
assocparams.sasoc_number_peer_destinations = cnt;
} else {
/* Values corresponding to the endpoint */
struct sctp_sock *sp = sctp_sk(sk);
assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
assocparams.sasoc_cookie_life =
sp->assocparams.sasoc_cookie_life;
assocparams.sasoc_number_peer_destinations =
sp->assocparams.
sasoc_number_peer_destinations;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &assocparams, len))
return -EFAULT;
return 0;
}
/*
* 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
*
* This socket option is a boolean flag which turns on or off mapped V4
* addresses. If this option is turned on and the socket is type
* PF_INET6, then IPv4 addresses will be mapped to V6 representation.
* If this option is turned off, then no mapping will be done of V4
* addresses and a user will receive both PF_INET6 and PF_INET type
* addresses on the socket.
*/
static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
int val;
struct sctp_sock *sp = sctp_sk(sk);
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = sp->v4mapped;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* 7.1.29. Set or Get the default context (SCTP_CONTEXT)
* (chapter and verse is quoted at sctp_setsockopt_context())
*/
static int sctp_getsockopt_context(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
if (len < sizeof(struct sctp_assoc_value))
return -EINVAL;
len = sizeof(struct sctp_assoc_value);
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
params.assoc_value = asoc ? asoc->default_rcv_context
: sctp_sk(sk)->default_rcv_context;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
return 0;
}
/*
* 8.1.16. Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
* This option will get or set the maximum size to put in any outgoing
* SCTP DATA chunk. If a message is larger than this size it will be
* fragmented by SCTP into the specified size. Note that the underlying
* SCTP implementation may fragment into smaller sized chunks when the
* PMTU of the underlying association is smaller than the value set by
* the user. The default value for this option is '0' which indicates
* the user is NOT limiting fragmentation and only the PMTU will effect
* SCTP's choice of DATA chunk size. Note also that values set larger
* than the maximum size of an IP datagram will effectively let SCTP
* control fragmentation (i.e. the same as setting this option to 0).
*
* The following structure is used to access and modify this parameter:
*
* struct sctp_assoc_value {
* sctp_assoc_t assoc_id;
* uint32_t assoc_value;
* };
*
* assoc_id: This parameter is ignored for one-to-one style sockets.
* For one-to-many style sockets this parameter indicates which
* association the user is performing an action upon. Note that if
* this field's value is zero then the endpoints default value is
* changed (effecting future associations only).
* assoc_value: This parameter specifies the maximum size in bytes.
*/
static int sctp_getsockopt_maxseg(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
if (len == sizeof(int)) {
pr_warn_ratelimited(DEPRECATED
"%s (pid %d) "
"Use of int in maxseg socket option.\n"
"Use struct sctp_assoc_value instead\n",
current->comm, task_pid_nr(current));
params.assoc_id = SCTP_FUTURE_ASSOC;
} else if (len >= sizeof(struct sctp_assoc_value)) {
len = sizeof(struct sctp_assoc_value);
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
} else
return -EINVAL;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc)
params.assoc_value = asoc->frag_point;
else
params.assoc_value = sctp_sk(sk)->user_frag;
if (put_user(len, optlen))
return -EFAULT;
if (len == sizeof(int)) {
if (copy_to_user(optval, ¶ms.assoc_value, len))
return -EFAULT;
} else {
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
}
return 0;
}
/*
* 7.1.24. Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
* (chapter and verse is quoted at sctp_setsockopt_fragment_interleave())
*/
static int sctp_getsockopt_fragment_interleave(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
int val;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = sctp_sk(sk)->frag_interleave;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* 7.1.25. Set or Get the sctp partial delivery point
* (chapter and verse is quoted at sctp_setsockopt_partial_delivery_point())
*/
static int sctp_getsockopt_partial_delivery_point(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
u32 val;
if (len < sizeof(u32))
return -EINVAL;
len = sizeof(u32);
val = sctp_sk(sk)->pd_point;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* 7.1.28. Set or Get the maximum burst (SCTP_MAX_BURST)
* (chapter and verse is quoted at sctp_setsockopt_maxburst())
*/
static int sctp_getsockopt_maxburst(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
if (len == sizeof(int)) {
pr_warn_ratelimited(DEPRECATED
"%s (pid %d) "
"Use of int in max_burst socket option.\n"
"Use struct sctp_assoc_value instead\n",
current->comm, task_pid_nr(current));
params.assoc_id = SCTP_FUTURE_ASSOC;
} else if (len >= sizeof(struct sctp_assoc_value)) {
len = sizeof(struct sctp_assoc_value);
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
} else
return -EINVAL;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
params.assoc_value = asoc ? asoc->max_burst : sctp_sk(sk)->max_burst;
if (len == sizeof(int)) {
if (copy_to_user(optval, ¶ms.assoc_value, len))
return -EFAULT;
} else {
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
}
return 0;
}
static int sctp_getsockopt_hmac_ident(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct sctp_hmacalgo __user *p = (void __user *)optval;
struct sctp_hmac_algo_param *hmacs;
__u16 data_len = 0;
u32 num_idents;
int i;
if (!ep->auth_enable)
return -EACCES;
hmacs = ep->auth_hmacs_list;
data_len = ntohs(hmacs->param_hdr.length) -
sizeof(struct sctp_paramhdr);
if (len < sizeof(struct sctp_hmacalgo) + data_len)
return -EINVAL;
len = sizeof(struct sctp_hmacalgo) + data_len;
num_idents = data_len / sizeof(u16);
if (put_user(len, optlen))
return -EFAULT;
if (put_user(num_idents, &p->shmac_num_idents))
return -EFAULT;
for (i = 0; i < num_idents; i++) {
__u16 hmacid = ntohs(hmacs->hmac_ids[i]);
if (copy_to_user(&p->shmac_idents[i], &hmacid, sizeof(__u16)))
return -EFAULT;
}
return 0;
}
static int sctp_getsockopt_active_key(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct sctp_authkeyid val;
struct sctp_association *asoc;
if (len < sizeof(struct sctp_authkeyid))
return -EINVAL;
len = sizeof(struct sctp_authkeyid);
if (copy_from_user(&val, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, val.scact_assoc_id);
if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
if (!asoc->peer.auth_capable)
return -EACCES;
val.scact_keynumber = asoc->active_key_id;
} else {
if (!ep->auth_enable)
return -EACCES;
val.scact_keynumber = ep->active_key_id;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_peer_auth_chunks(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_authchunks __user *p = (void __user *)optval;
struct sctp_authchunks val;
struct sctp_association *asoc;
struct sctp_chunks_param *ch;
u32 num_chunks = 0;
char __user *to;
if (len < sizeof(struct sctp_authchunks))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
to = p->gauth_chunks;
asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
if (!asoc)
return -EINVAL;
if (!asoc->peer.auth_capable)
return -EACCES;
ch = asoc->peer.peer_chunks;
if (!ch)
goto num;
/* See if the user provided enough room for all the data */
num_chunks = ntohs(ch->param_hdr.length) - sizeof(struct sctp_paramhdr);
if (len < num_chunks)
return -EINVAL;
if (copy_to_user(to, ch->chunks, num_chunks))
return -EFAULT;
num:
len = sizeof(struct sctp_authchunks) + num_chunks;
if (put_user(len, optlen))
return -EFAULT;
if (put_user(num_chunks, &p->gauth_number_of_chunks))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_local_auth_chunks(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
struct sctp_authchunks __user *p = (void __user *)optval;
struct sctp_authchunks val;
struct sctp_association *asoc;
struct sctp_chunks_param *ch;
u32 num_chunks = 0;
char __user *to;
if (len < sizeof(struct sctp_authchunks))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
to = p->gauth_chunks;
asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
if (!asoc && val.gauth_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
if (!asoc->peer.auth_capable)
return -EACCES;
ch = (struct sctp_chunks_param *)asoc->c.auth_chunks;
} else {
if (!ep->auth_enable)
return -EACCES;
ch = ep->auth_chunk_list;
}
if (!ch)
goto num;
num_chunks = ntohs(ch->param_hdr.length) - sizeof(struct sctp_paramhdr);
if (len < sizeof(struct sctp_authchunks) + num_chunks)
return -EINVAL;
if (copy_to_user(to, ch->chunks, num_chunks))
return -EFAULT;
num:
len = sizeof(struct sctp_authchunks) + num_chunks;
if (put_user(len, optlen))
return -EFAULT;
if (put_user(num_chunks, &p->gauth_number_of_chunks))
return -EFAULT;
return 0;
}
/*
* 8.2.5. Get the Current Number of Associations (SCTP_GET_ASSOC_NUMBER)
* This option gets the current number of associations that are attached
* to a one-to-many style socket. The option value is an uint32_t.
*/
static int sctp_getsockopt_assoc_number(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
u32 val = 0;
if (sctp_style(sk, TCP))
return -EOPNOTSUPP;
if (len < sizeof(u32))
return -EINVAL;
len = sizeof(u32);
list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
val++;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* 8.1.23 SCTP_AUTO_ASCONF
* See the corresponding setsockopt entry as description
*/
static int sctp_getsockopt_auto_asconf(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
int val = 0;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
if (sctp_sk(sk)->do_auto_asconf && sctp_is_ep_boundall(sk))
val = 1;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* 8.2.6. Get the Current Identifiers of Associations
* (SCTP_GET_ASSOC_ID_LIST)
*
* This option gets the current list of SCTP association identifiers of
* the SCTP associations handled by a one-to-many style socket.
*/
static int sctp_getsockopt_assoc_ids(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
struct sctp_assoc_ids *ids;
u32 num = 0;
if (sctp_style(sk, TCP))
return -EOPNOTSUPP;
if (len < sizeof(struct sctp_assoc_ids))
return -EINVAL;
list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
num++;
}
if (len < sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num)
return -EINVAL;
len = sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num;
ids = kmalloc(len, GFP_USER | __GFP_NOWARN);
if (unlikely(!ids))
return -ENOMEM;
ids->gaids_number_of_ids = num;
num = 0;
list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
ids->gaids_assoc_id[num++] = asoc->assoc_id;
}
if (put_user(len, optlen) || copy_to_user(optval, ids, len)) {
kfree(ids);
return -EFAULT;
}
kfree(ids);
return 0;
}
/*
* SCTP_PEER_ADDR_THLDS
*
* This option allows us to fetch the partially failed threshold for one or all
* transports in an association. See Section 6.1 of:
* http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
*/
static int sctp_getsockopt_paddr_thresholds(struct sock *sk,
char __user *optval, int len,
int __user *optlen, bool v2)
{
struct sctp_paddrthlds_v2 val;
struct sctp_transport *trans;
struct sctp_association *asoc;
int min;
min = v2 ? sizeof(val) : sizeof(struct sctp_paddrthlds);
if (len < min)
return -EINVAL;
len = min;
if (copy_from_user(&val, optval, len))
return -EFAULT;
if (!sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
trans = sctp_addr_id2transport(sk, &val.spt_address,
val.spt_assoc_id);
if (!trans)
return -ENOENT;
val.spt_pathmaxrxt = trans->pathmaxrxt;
val.spt_pathpfthld = trans->pf_retrans;
val.spt_pathcpthld = trans->ps_retrans;
goto out;
}
asoc = sctp_id2assoc(sk, val.spt_assoc_id);
if (!asoc && val.spt_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
val.spt_pathpfthld = asoc->pf_retrans;
val.spt_pathmaxrxt = asoc->pathmaxrxt;
val.spt_pathcpthld = asoc->ps_retrans;
} else {
struct sctp_sock *sp = sctp_sk(sk);
val.spt_pathpfthld = sp->pf_retrans;
val.spt_pathmaxrxt = sp->pathmaxrxt;
val.spt_pathcpthld = sp->ps_retrans;
}
out:
if (put_user(len, optlen) || copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
/*
* SCTP_GET_ASSOC_STATS
*
* This option retrieves local per endpoint statistics. It is modeled
* after OpenSolaris' implementation
*/
static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_stats sas;
struct sctp_association *asoc = NULL;
/* User must provide at least the assoc id */
if (len < sizeof(sctp_assoc_t))
return -EINVAL;
/* Allow the struct to grow and fill in as much as possible */
len = min_t(size_t, len, sizeof(sas));
if (copy_from_user(&sas, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
if (!asoc)
return -EINVAL;
sas.sas_rtxchunks = asoc->stats.rtxchunks;
sas.sas_gapcnt = asoc->stats.gapcnt;
sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
sas.sas_osacks = asoc->stats.osacks;
sas.sas_isacks = asoc->stats.isacks;
sas.sas_octrlchunks = asoc->stats.octrlchunks;
sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
sas.sas_oodchunks = asoc->stats.oodchunks;
sas.sas_iodchunks = asoc->stats.iodchunks;
sas.sas_ouodchunks = asoc->stats.ouodchunks;
sas.sas_iuodchunks = asoc->stats.iuodchunks;
sas.sas_idupchunks = asoc->stats.idupchunks;
sas.sas_opackets = asoc->stats.opackets;
sas.sas_ipackets = asoc->stats.ipackets;
/* New high max rto observed, will return 0 if not a single
* RTO update took place. obs_rto_ipaddr will be bogus
* in such a case
*/
sas.sas_maxrto = asoc->stats.max_obs_rto;
memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
sizeof(struct sockaddr_storage));
/* Mark beginning of a new observation period */
asoc->stats.max_obs_rto = asoc->rto_min;
if (put_user(len, optlen))
return -EFAULT;
pr_debug("%s: len:%d, assoc_id:%d\n", __func__, len, sas.sas_assoc_id);
if (copy_to_user(optval, &sas, len))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_recvrcvinfo(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
int val = 0;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
if (sctp_sk(sk)->recvrcvinfo)
val = 1;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_recvnxtinfo(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
int val = 0;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
if (sctp_sk(sk)->recvnxtinfo)
val = 1;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_pr_supported(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(params)) {
retval = -EINVAL;
goto out;
}
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
goto out;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
retval = -EINVAL;
goto out;
}
params.assoc_value = asoc ? asoc->peer.prsctp_capable
: sctp_sk(sk)->ep->prsctp_enable;
if (put_user(len, optlen))
goto out;
if (copy_to_user(optval, ¶ms, len))
goto out;
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_default_prinfo(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_default_prinfo info;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(info)) {
retval = -EINVAL;
goto out;
}
len = sizeof(info);
if (copy_from_user(&info, optval, len))
goto out;
asoc = sctp_id2assoc(sk, info.pr_assoc_id);
if (!asoc && info.pr_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
retval = -EINVAL;
goto out;
}
if (asoc) {
info.pr_policy = SCTP_PR_POLICY(asoc->default_flags);
info.pr_value = asoc->default_timetolive;
} else {
struct sctp_sock *sp = sctp_sk(sk);
info.pr_policy = SCTP_PR_POLICY(sp->default_flags);
info.pr_value = sp->default_timetolive;
}
if (put_user(len, optlen))
goto out;
if (copy_to_user(optval, &info, len))
goto out;
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_pr_assocstatus(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_prstatus params;
struct sctp_association *asoc;
int policy;
int retval = -EINVAL;
if (len < sizeof(params))
goto out;
len = sizeof(params);
if (copy_from_user(¶ms, optval, len)) {
retval = -EFAULT;
goto out;
}
policy = params.sprstat_policy;
if (!policy || (policy & ~(SCTP_PR_SCTP_MASK | SCTP_PR_SCTP_ALL)) ||
((policy & SCTP_PR_SCTP_ALL) && (policy & SCTP_PR_SCTP_MASK)))
goto out;
asoc = sctp_id2assoc(sk, params.sprstat_assoc_id);
if (!asoc)
goto out;
if (policy == SCTP_PR_SCTP_ALL) {
params.sprstat_abandoned_unsent = 0;
params.sprstat_abandoned_sent = 0;
for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) {
params.sprstat_abandoned_unsent +=
asoc->abandoned_unsent[policy];
params.sprstat_abandoned_sent +=
asoc->abandoned_sent[policy];
}
} else {
params.sprstat_abandoned_unsent =
asoc->abandoned_unsent[__SCTP_PR_INDEX(policy)];
params.sprstat_abandoned_sent =
asoc->abandoned_sent[__SCTP_PR_INDEX(policy)];
}
if (put_user(len, optlen)) {
retval = -EFAULT;
goto out;
}
if (copy_to_user(optval, ¶ms, len)) {
retval = -EFAULT;
goto out;
}
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_pr_streamstatus(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_stream_out_ext *streamoute;
struct sctp_association *asoc;
struct sctp_prstatus params;
int retval = -EINVAL;
int policy;
if (len < sizeof(params))
goto out;
len = sizeof(params);
if (copy_from_user(¶ms, optval, len)) {
retval = -EFAULT;
goto out;
}
policy = params.sprstat_policy;
if (!policy || (policy & ~(SCTP_PR_SCTP_MASK | SCTP_PR_SCTP_ALL)) ||
((policy & SCTP_PR_SCTP_ALL) && (policy & SCTP_PR_SCTP_MASK)))
goto out;
asoc = sctp_id2assoc(sk, params.sprstat_assoc_id);
if (!asoc || params.sprstat_sid >= asoc->stream.outcnt)
goto out;
streamoute = SCTP_SO(&asoc->stream, params.sprstat_sid)->ext;
if (!streamoute) {
/* Not allocated yet, means all stats are 0 */
params.sprstat_abandoned_unsent = 0;
params.sprstat_abandoned_sent = 0;
retval = 0;
goto out;
}
if (policy == SCTP_PR_SCTP_ALL) {
params.sprstat_abandoned_unsent = 0;
params.sprstat_abandoned_sent = 0;
for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) {
params.sprstat_abandoned_unsent +=
streamoute->abandoned_unsent[policy];
params.sprstat_abandoned_sent +=
streamoute->abandoned_sent[policy];
}
} else {
params.sprstat_abandoned_unsent =
streamoute->abandoned_unsent[__SCTP_PR_INDEX(policy)];
params.sprstat_abandoned_sent =
streamoute->abandoned_sent[__SCTP_PR_INDEX(policy)];
}
if (put_user(len, optlen) || copy_to_user(optval, ¶ms, len)) {
retval = -EFAULT;
goto out;
}
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_reconfig_supported(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(params)) {
retval = -EINVAL;
goto out;
}
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
goto out;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
retval = -EINVAL;
goto out;
}
params.assoc_value = asoc ? asoc->peer.reconf_capable
: sctp_sk(sk)->ep->reconf_enable;
if (put_user(len, optlen))
goto out;
if (copy_to_user(optval, ¶ms, len))
goto out;
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_enable_strreset(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(params)) {
retval = -EINVAL;
goto out;
}
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
goto out;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
retval = -EINVAL;
goto out;
}
params.assoc_value = asoc ? asoc->strreset_enable
: sctp_sk(sk)->ep->strreset_enable;
if (put_user(len, optlen))
goto out;
if (copy_to_user(optval, ¶ms, len))
goto out;
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_scheduler(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(params)) {
retval = -EINVAL;
goto out;
}
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
goto out;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
retval = -EINVAL;
goto out;
}
params.assoc_value = asoc ? sctp_sched_get_sched(asoc)
: sctp_sk(sk)->default_ss;
if (put_user(len, optlen))
goto out;
if (copy_to_user(optval, ¶ms, len))
goto out;
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_scheduler_value(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_stream_value params;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(params)) {
retval = -EINVAL;
goto out;
}
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
goto out;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc) {
retval = -EINVAL;
goto out;
}
retval = sctp_sched_get_value(asoc, params.stream_id,
¶ms.stream_value);
if (retval)
goto out;
if (put_user(len, optlen)) {
retval = -EFAULT;
goto out;
}
if (copy_to_user(optval, ¶ms, len)) {
retval = -EFAULT;
goto out;
}
out:
return retval;
}
static int sctp_getsockopt_interleaving_supported(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(params)) {
retval = -EINVAL;
goto out;
}
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
goto out;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
retval = -EINVAL;
goto out;
}
params.assoc_value = asoc ? asoc->peer.intl_capable
: sctp_sk(sk)->ep->intl_enable;
if (put_user(len, optlen))
goto out;
if (copy_to_user(optval, ¶ms, len))
goto out;
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_reuse_port(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
int val;
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = sctp_sk(sk)->reuse;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_event(struct sock *sk, int len, char __user *optval,
int __user *optlen)
{
struct sctp_association *asoc;
struct sctp_event param;
__u16 subscribe;
if (len < sizeof(param))
return -EINVAL;
len = sizeof(param);
if (copy_from_user(¶m, optval, len))
return -EFAULT;
if (param.se_type < SCTP_SN_TYPE_BASE ||
param.se_type > SCTP_SN_TYPE_MAX)
return -EINVAL;
asoc = sctp_id2assoc(sk, param.se_assoc_id);
if (!asoc && param.se_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP))
return -EINVAL;
subscribe = asoc ? asoc->subscribe : sctp_sk(sk)->subscribe;
param.se_on = sctp_ulpevent_type_enabled(subscribe, param.se_type);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, ¶m, len))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_asconf_supported(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(params)) {
retval = -EINVAL;
goto out;
}
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
goto out;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
retval = -EINVAL;
goto out;
}
params.assoc_value = asoc ? asoc->peer.asconf_capable
: sctp_sk(sk)->ep->asconf_enable;
if (put_user(len, optlen))
goto out;
if (copy_to_user(optval, ¶ms, len))
goto out;
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_auth_supported(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(params)) {
retval = -EINVAL;
goto out;
}
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
goto out;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
retval = -EINVAL;
goto out;
}
params.assoc_value = asoc ? asoc->peer.auth_capable
: sctp_sk(sk)->ep->auth_enable;
if (put_user(len, optlen))
goto out;
if (copy_to_user(optval, ¶ms, len))
goto out;
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_ecn_supported(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(params)) {
retval = -EINVAL;
goto out;
}
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
goto out;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
retval = -EINVAL;
goto out;
}
params.assoc_value = asoc ? asoc->peer.ecn_capable
: sctp_sk(sk)->ep->ecn_enable;
if (put_user(len, optlen))
goto out;
if (copy_to_user(optval, ¶ms, len))
goto out;
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_pf_expose(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_value params;
struct sctp_association *asoc;
int retval = -EFAULT;
if (len < sizeof(params)) {
retval = -EINVAL;
goto out;
}
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
goto out;
asoc = sctp_id2assoc(sk, params.assoc_id);
if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
retval = -EINVAL;
goto out;
}
params.assoc_value = asoc ? asoc->pf_expose
: sctp_sk(sk)->pf_expose;
if (put_user(len, optlen))
goto out;
if (copy_to_user(optval, ¶ms, len))
goto out;
retval = 0;
out:
return retval;
}
static int sctp_getsockopt_encap_port(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_association *asoc;
struct sctp_udpencaps encap;
struct sctp_transport *t;
__be16 encap_port;
if (len < sizeof(encap))
return -EINVAL;
len = sizeof(encap);
if (copy_from_user(&encap, optval, len))
return -EFAULT;
/* If an address other than INADDR_ANY is specified, and
* no transport is found, then the request is invalid.
*/
if (!sctp_is_any(sk, (union sctp_addr *)&encap.sue_address)) {
t = sctp_addr_id2transport(sk, &encap.sue_address,
encap.sue_assoc_id);
if (!t) {
pr_debug("%s: failed no transport\n", __func__);
return -EINVAL;
}
encap_port = t->encap_port;
goto out;
}
/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
* socket is a one to many style socket, and an association
* was not found, then the id was invalid.
*/
asoc = sctp_id2assoc(sk, encap.sue_assoc_id);
if (!asoc && encap.sue_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
pr_debug("%s: failed no association\n", __func__);
return -EINVAL;
}
if (asoc) {
encap_port = asoc->encap_port;
goto out;
}
encap_port = sctp_sk(sk)->encap_port;
out:
encap.sue_port = (__force uint16_t)encap_port;
if (copy_to_user(optval, &encap, len))
return -EFAULT;
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
static int sctp_getsockopt_probe_interval(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_probeinterval params;
struct sctp_association *asoc;
struct sctp_transport *t;
__u32 probe_interval;
if (len < sizeof(params))
return -EINVAL;
len = sizeof(params);
if (copy_from_user(¶ms, optval, len))
return -EFAULT;
/* If an address other than INADDR_ANY is specified, and
* no transport is found, then the request is invalid.
*/
if (!sctp_is_any(sk, (union sctp_addr *)¶ms.spi_address)) {
t = sctp_addr_id2transport(sk, ¶ms.spi_address,
params.spi_assoc_id);
if (!t) {
pr_debug("%s: failed no transport\n", __func__);
return -EINVAL;
}
probe_interval = jiffies_to_msecs(t->probe_interval);
goto out;
}
/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
* socket is a one to many style socket, and an association
* was not found, then the id was invalid.
*/
asoc = sctp_id2assoc(sk, params.spi_assoc_id);
if (!asoc && params.spi_assoc_id != SCTP_FUTURE_ASSOC &&
sctp_style(sk, UDP)) {
pr_debug("%s: failed no association\n", __func__);
return -EINVAL;
}
if (asoc) {
probe_interval = jiffies_to_msecs(asoc->probe_interval);
goto out;
}
probe_interval = sctp_sk(sk)->probe_interval;
out:
params.spi_interval = probe_interval;
if (copy_to_user(optval, ¶ms, len))
return -EFAULT;
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
static int sctp_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
int retval = 0;
int len;
pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
/* I can hardly begin to describe how wrong this is. This is
* so broken as to be worse than useless. The API draft
* REALLY is NOT helpful here... I am not convinced that the
* semantics of getsockopt() with a level OTHER THAN SOL_SCTP
* are at all well-founded.
*/
if (level != SOL_SCTP) {
struct sctp_af *af = sctp_sk(sk)->pf->af;
retval = af->getsockopt(sk, level, optname, optval, optlen);
return retval;
}
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
lock_sock(sk);
switch (optname) {
case SCTP_STATUS:
retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
break;
case SCTP_DISABLE_FRAGMENTS:
retval = sctp_getsockopt_disable_fragments(sk, len, optval,
optlen);
break;
case SCTP_EVENTS:
retval = sctp_getsockopt_events(sk, len, optval, optlen);
break;
case SCTP_AUTOCLOSE:
retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
break;
case SCTP_SOCKOPT_PEELOFF:
retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
break;
case SCTP_SOCKOPT_PEELOFF_FLAGS:
retval = sctp_getsockopt_peeloff_flags(sk, len, optval, optlen);
break;
case SCTP_PEER_ADDR_PARAMS:
retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
optlen);
break;
case SCTP_DELAYED_SACK:
retval = sctp_getsockopt_delayed_ack(sk, len, optval,
optlen);
break;
case SCTP_INITMSG:
retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
break;
case SCTP_GET_PEER_ADDRS:
retval = sctp_getsockopt_peer_addrs(sk, len, optval,
optlen);
break;
case SCTP_GET_LOCAL_ADDRS:
retval = sctp_getsockopt_local_addrs(sk, len, optval,
optlen);
break;
case SCTP_SOCKOPT_CONNECTX3:
retval = sctp_getsockopt_connectx3(sk, len, optval, optlen);
break;
case SCTP_DEFAULT_SEND_PARAM:
retval = sctp_getsockopt_default_send_param(sk, len,
optval, optlen);
break;
case SCTP_DEFAULT_SNDINFO:
retval = sctp_getsockopt_default_sndinfo(sk, len,
optval, optlen);
break;
case SCTP_PRIMARY_ADDR:
retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
break;
case SCTP_NODELAY:
retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
break;
case SCTP_RTOINFO:
retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
break;
case SCTP_ASSOCINFO:
retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
break;
case SCTP_I_WANT_MAPPED_V4_ADDR:
retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
break;
case SCTP_MAXSEG:
retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
break;
case SCTP_GET_PEER_ADDR_INFO:
retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
optlen);
break;
case SCTP_ADAPTATION_LAYER:
retval = sctp_getsockopt_adaptation_layer(sk, len, optval,
optlen);
break;
case SCTP_CONTEXT:
retval = sctp_getsockopt_context(sk, len, optval, optlen);
break;
case SCTP_FRAGMENT_INTERLEAVE:
retval = sctp_getsockopt_fragment_interleave(sk, len, optval,
optlen);
break;
case SCTP_PARTIAL_DELIVERY_POINT:
retval = sctp_getsockopt_partial_delivery_point(sk, len, optval,
optlen);
break;
case SCTP_MAX_BURST:
retval = sctp_getsockopt_maxburst(sk, len, optval, optlen);
break;
case SCTP_AUTH_KEY:
case SCTP_AUTH_CHUNK:
case SCTP_AUTH_DELETE_KEY:
case SCTP_AUTH_DEACTIVATE_KEY:
retval = -EOPNOTSUPP;
break;
case SCTP_HMAC_IDENT:
retval = sctp_getsockopt_hmac_ident(sk, len, optval, optlen);
break;
case SCTP_AUTH_ACTIVE_KEY:
retval = sctp_getsockopt_active_key(sk, len, optval, optlen);
break;
case SCTP_PEER_AUTH_CHUNKS:
retval = sctp_getsockopt_peer_auth_chunks(sk, len, optval,
optlen);
break;
case SCTP_LOCAL_AUTH_CHUNKS:
retval = sctp_getsockopt_local_auth_chunks(sk, len, optval,
optlen);
break;
case SCTP_GET_ASSOC_NUMBER:
retval = sctp_getsockopt_assoc_number(sk, len, optval, optlen);
break;
case SCTP_GET_ASSOC_ID_LIST:
retval = sctp_getsockopt_assoc_ids(sk, len, optval, optlen);
break;
case SCTP_AUTO_ASCONF:
retval = sctp_getsockopt_auto_asconf(sk, len, optval, optlen);
break;
case SCTP_PEER_ADDR_THLDS:
retval = sctp_getsockopt_paddr_thresholds(sk, optval, len,
optlen, false);
break;
case SCTP_PEER_ADDR_THLDS_V2:
retval = sctp_getsockopt_paddr_thresholds(sk, optval, len,
optlen, true);
break;
case SCTP_GET_ASSOC_STATS:
retval = sctp_getsockopt_assoc_stats(sk, len, optval, optlen);
break;
case SCTP_RECVRCVINFO:
retval = sctp_getsockopt_recvrcvinfo(sk, len, optval, optlen);
break;
case SCTP_RECVNXTINFO:
retval = sctp_getsockopt_recvnxtinfo(sk, len, optval, optlen);
break;
case SCTP_PR_SUPPORTED:
retval = sctp_getsockopt_pr_supported(sk, len, optval, optlen);
break;
case SCTP_DEFAULT_PRINFO:
retval = sctp_getsockopt_default_prinfo(sk, len, optval,
optlen);
break;
case SCTP_PR_ASSOC_STATUS:
retval = sctp_getsockopt_pr_assocstatus(sk, len, optval,
optlen);
break;
case SCTP_PR_STREAM_STATUS:
retval = sctp_getsockopt_pr_streamstatus(sk, len, optval,
optlen);
break;
case SCTP_RECONFIG_SUPPORTED:
retval = sctp_getsockopt_reconfig_supported(sk, len, optval,
optlen);
break;
case SCTP_ENABLE_STREAM_RESET:
retval = sctp_getsockopt_enable_strreset(sk, len, optval,
optlen);
break;
case SCTP_STREAM_SCHEDULER:
retval = sctp_getsockopt_scheduler(sk, len, optval,
optlen);
break;
case SCTP_STREAM_SCHEDULER_VALUE:
retval = sctp_getsockopt_scheduler_value(sk, len, optval,
optlen);
break;
case SCTP_INTERLEAVING_SUPPORTED:
retval = sctp_getsockopt_interleaving_supported(sk, len, optval,
optlen);
break;
case SCTP_REUSE_PORT:
retval = sctp_getsockopt_reuse_port(sk, len, optval, optlen);
break;
case SCTP_EVENT:
retval = sctp_getsockopt_event(sk, len, optval, optlen);
break;
case SCTP_ASCONF_SUPPORTED:
retval = sctp_getsockopt_asconf_supported(sk, len, optval,
optlen);
break;
case SCTP_AUTH_SUPPORTED:
retval = sctp_getsockopt_auth_supported(sk, len, optval,
optlen);
break;
case SCTP_ECN_SUPPORTED:
retval = sctp_getsockopt_ecn_supported(sk, len, optval, optlen);
break;
case SCTP_EXPOSE_POTENTIALLY_FAILED_STATE:
retval = sctp_getsockopt_pf_expose(sk, len, optval, optlen);
break;
case SCTP_REMOTE_UDP_ENCAPS_PORT:
retval = sctp_getsockopt_encap_port(sk, len, optval, optlen);
break;
case SCTP_PLPMTUD_PROBE_INTERVAL:
retval = sctp_getsockopt_probe_interval(sk, len, optval, optlen);
break;
default:
retval = -ENOPROTOOPT;
break;
}
release_sock(sk);
return retval;
}
static bool sctp_bpf_bypass_getsockopt(int level, int optname)
{
if (level == SOL_SCTP) {
switch (optname) {
case SCTP_SOCKOPT_PEELOFF:
case SCTP_SOCKOPT_PEELOFF_FLAGS:
case SCTP_SOCKOPT_CONNECTX3:
return true;
default:
return false;
}
}
return false;
}
static int sctp_hash(struct sock *sk)
{
/* STUB */
return 0;
}
static void sctp_unhash(struct sock *sk)
{
/* STUB */
}
/* Check if port is acceptable. Possibly find first available port.
*
* The port hash table (contained in the 'global' SCTP protocol storage
* returned by struct sctp_protocol *sctp_get_protocol()). The hash
* table is an array of 4096 lists (sctp_bind_hashbucket). Each
* list (the list number is the port number hashed out, so as you
* would expect from a hash function, all the ports in a given list have
* such a number that hashes out to the same list number; you were
* expecting that, right?); so each list has a set of ports, with a
* link to the socket (struct sock) that uses it, the port number and
* a fastreuse flag (FIXME: NPI ipg).
*/
static struct sctp_bind_bucket *sctp_bucket_create(
struct sctp_bind_hashbucket *head, struct net *, unsigned short snum);
static int sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
{
struct sctp_sock *sp = sctp_sk(sk);
bool reuse = (sk->sk_reuse || sp->reuse);
struct sctp_bind_hashbucket *head; /* hash list */
struct net *net = sock_net(sk);
kuid_t uid = sock_i_uid(sk);
struct sctp_bind_bucket *pp;
unsigned short snum;
int ret;
snum = ntohs(addr->v4.sin_port);
pr_debug("%s: begins, snum:%d\n", __func__, snum);
if (snum == 0) {
/* Search for an available port. */
int low, high, remaining, index;
unsigned int rover;
inet_sk_get_local_port_range(sk, &low, &high);
remaining = (high - low) + 1;
rover = get_random_u32_below(remaining) + low;
do {
rover++;
if ((rover < low) || (rover > high))
rover = low;
if (inet_is_local_reserved_port(net, rover))
continue;
index = sctp_phashfn(net, rover);
head = &sctp_port_hashtable[index];
spin_lock_bh(&head->lock);
sctp_for_each_hentry(pp, &head->chain)
if ((pp->port == rover) &&
net_eq(net, pp->net))
goto next;
break;
next:
spin_unlock_bh(&head->lock);
cond_resched();
} while (--remaining > 0);
/* Exhausted local port range during search? */
ret = 1;
if (remaining <= 0)
return ret;
/* OK, here is the one we will use. HEAD (the port
* hash table list entry) is non-NULL and we hold it's
* mutex.
*/
snum = rover;
} else {
/* We are given an specific port number; we verify
* that it is not being used. If it is used, we will
* exahust the search in the hash list corresponding
* to the port number (snum) - we detect that with the
* port iterator, pp being NULL.
*/
head = &sctp_port_hashtable[sctp_phashfn(net, snum)];
spin_lock_bh(&head->lock);
sctp_for_each_hentry(pp, &head->chain) {
if ((pp->port == snum) && net_eq(pp->net, net))
goto pp_found;
}
}
pp = NULL;
goto pp_not_found;
pp_found:
if (!hlist_empty(&pp->owner)) {
/* We had a port hash table hit - there is an
* available port (pp != NULL) and it is being
* used by other socket (pp->owner not empty); that other
* socket is going to be sk2.
*/
struct sock *sk2;
pr_debug("%s: found a possible match\n", __func__);
if ((pp->fastreuse && reuse &&
sk->sk_state != SCTP_SS_LISTENING) ||
(pp->fastreuseport && sk->sk_reuseport &&
uid_eq(pp->fastuid, uid)))
goto success;
/* Run through the list of sockets bound to the port
* (pp->port) [via the pointers bind_next and
* bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
* we get the endpoint they describe and run through
* the endpoint's list of IP (v4 or v6) addresses,
* comparing each of the addresses with the address of
* the socket sk. If we find a match, then that means
* that this port/socket (sk) combination are already
* in an endpoint.
*/
sk_for_each_bound(sk2, &pp->owner) {
int bound_dev_if2 = READ_ONCE(sk2->sk_bound_dev_if);
struct sctp_sock *sp2 = sctp_sk(sk2);
struct sctp_endpoint *ep2 = sp2->ep;
if (sk == sk2 ||
(reuse && (sk2->sk_reuse || sp2->reuse) &&
sk2->sk_state != SCTP_SS_LISTENING) ||
(sk->sk_reuseport && sk2->sk_reuseport &&
uid_eq(uid, sock_i_uid(sk2))))
continue;
if ((!sk->sk_bound_dev_if || !bound_dev_if2 ||
sk->sk_bound_dev_if == bound_dev_if2) &&
sctp_bind_addr_conflict(&ep2->base.bind_addr,
addr, sp2, sp)) {
ret = 1;
goto fail_unlock;
}
}
pr_debug("%s: found a match\n", __func__);
}
pp_not_found:
/* If there was a hash table miss, create a new port. */
ret = 1;
if (!pp && !(pp = sctp_bucket_create(head, net, snum)))
goto fail_unlock;
/* In either case (hit or miss), make sure fastreuse is 1 only
* if sk->sk_reuse is too (that is, if the caller requested
* SO_REUSEADDR on this socket -sk-).
*/
if (hlist_empty(&pp->owner)) {
if (reuse && sk->sk_state != SCTP_SS_LISTENING)
pp->fastreuse = 1;
else
pp->fastreuse = 0;
if (sk->sk_reuseport) {
pp->fastreuseport = 1;
pp->fastuid = uid;
} else {
pp->fastreuseport = 0;
}
} else {
if (pp->fastreuse &&
(!reuse || sk->sk_state == SCTP_SS_LISTENING))
pp->fastreuse = 0;
if (pp->fastreuseport &&
(!sk->sk_reuseport || !uid_eq(pp->fastuid, uid)))
pp->fastreuseport = 0;
}
/* We are set, so fill up all the data in the hash table
* entry, tie the socket list information with the rest of the
* sockets FIXME: Blurry, NPI (ipg).
*/
success:
if (!sp->bind_hash) {
inet_sk(sk)->inet_num = snum;
sk_add_bind_node(sk, &pp->owner);
sp->bind_hash = pp;
}
ret = 0;
fail_unlock:
spin_unlock_bh(&head->lock);
return ret;
}
/* Assign a 'snum' port to the socket. If snum == 0, an ephemeral
* port is requested.
*/
static int sctp_get_port(struct sock *sk, unsigned short snum)
{
union sctp_addr addr;
struct sctp_af *af = sctp_sk(sk)->pf->af;
/* Set up a dummy address struct from the sk. */
af->from_sk(&addr, sk);
addr.v4.sin_port = htons(snum);
/* Note: sk->sk_num gets filled in if ephemeral port request. */
return sctp_get_port_local(sk, &addr);
}
/*
* Move a socket to LISTENING state.
*/
static int sctp_listen_start(struct sock *sk, int backlog)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_endpoint *ep = sp->ep;
struct crypto_shash *tfm = NULL;
char alg[32];
/* Allocate HMAC for generating cookie. */
if (!sp->hmac && sp->sctp_hmac_alg) {
sprintf(alg, "hmac(%s)", sp->sctp_hmac_alg);
tfm = crypto_alloc_shash(alg, 0, 0);
if (IS_ERR(tfm)) {
net_info_ratelimited("failed to load transform for %s: %ld\n",
sp->sctp_hmac_alg, PTR_ERR(tfm));
return -ENOSYS;
}
sctp_sk(sk)->hmac = tfm;
}
/*
* If a bind() or sctp_bindx() is not called prior to a listen()
* call that allows new associations to be accepted, the system
* picks an ephemeral port and will choose an address set equivalent
* to binding with a wildcard address.
*
* This is not currently spelled out in the SCTP sockets
* extensions draft, but follows the practice as seen in TCP
* sockets.
*
*/
inet_sk_set_state(sk, SCTP_SS_LISTENING);
if (!ep->base.bind_addr.port) {
if (sctp_autobind(sk))
return -EAGAIN;
} else {
if (sctp_get_port(sk, inet_sk(sk)->inet_num)) {
inet_sk_set_state(sk, SCTP_SS_CLOSED);
return -EADDRINUSE;
}
}
WRITE_ONCE(sk->sk_max_ack_backlog, backlog);
return sctp_hash_endpoint(ep);
}
/*
* 4.1.3 / 5.1.3 listen()
*
* By default, new associations are not accepted for UDP style sockets.
* An application uses listen() to mark a socket as being able to
* accept new associations.
*
* On TCP style sockets, applications use listen() to ready the SCTP
* endpoint for accepting inbound associations.
*
* On both types of endpoints a backlog of '0' disables listening.
*
* Move a socket to LISTENING state.
*/
int sctp_inet_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
struct sctp_endpoint *ep = sctp_sk(sk)->ep;
int err = -EINVAL;
if (unlikely(backlog < 0))
return err;
lock_sock(sk);
/* Peeled-off sockets are not allowed to listen(). */
if (sctp_style(sk, UDP_HIGH_BANDWIDTH))
goto out;
if (sock->state != SS_UNCONNECTED)
goto out;
if (!sctp_sstate(sk, LISTENING) && !sctp_sstate(sk, CLOSED))
goto out;
/* If backlog is zero, disable listening. */
if (!backlog) {
if (sctp_sstate(sk, CLOSED))
goto out;
err = 0;
sctp_unhash_endpoint(ep);
sk->sk_state = SCTP_SS_CLOSED;
if (sk->sk_reuse || sctp_sk(sk)->reuse)
sctp_sk(sk)->bind_hash->fastreuse = 1;
goto out;
}
/* If we are already listening, just update the backlog */
if (sctp_sstate(sk, LISTENING))
WRITE_ONCE(sk->sk_max_ack_backlog, backlog);
else {
err = sctp_listen_start(sk, backlog);
if (err)
goto out;
}
err = 0;
out:
release_sock(sk);
return err;
}
/*
* This function is done by modeling the current datagram_poll() and the
* tcp_poll(). Note that, based on these implementations, we don't
* lock the socket in this function, even though it seems that,
* ideally, locking or some other mechanisms can be used to ensure
* the integrity of the counters (sndbuf and wmem_alloc) used
* in this place. We assume that we don't need locks either until proven
* otherwise.
*
* Another thing to note is that we include the Async I/O support
* here, again, by modeling the current TCP/UDP code. We don't have
* a good way to test with it yet.
*/
__poll_t sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
{
struct sock *sk = sock->sk;
struct sctp_sock *sp = sctp_sk(sk);
__poll_t mask;
poll_wait(file, sk_sleep(sk), wait);
sock_rps_record_flow(sk);
/* A TCP-style listening socket becomes readable when the accept queue
* is not empty.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
return (!list_empty(&sp->ep->asocs)) ?
(EPOLLIN | EPOLLRDNORM) : 0;
mask = 0;
/* Is there any exceptional events? */
if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
mask |= EPOLLERR |
(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? EPOLLPRI : 0);
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= EPOLLHUP;
/* Is it readable? Reconsider this code with TCP-style support. */
if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
mask |= EPOLLIN | EPOLLRDNORM;
/* The association is either gone or not ready. */
if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
return mask;
/* Is it writable? */
if (sctp_writeable(sk)) {
mask |= EPOLLOUT | EPOLLWRNORM;
} else {
sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
/*
* Since the socket is not locked, the buffer
* might be made available after the writeable check and
* before the bit is set. This could cause a lost I/O
* signal. tcp_poll() has a race breaker for this race
* condition. Based on their implementation, we put
* in the following code to cover it as well.
*/
if (sctp_writeable(sk))
mask |= EPOLLOUT | EPOLLWRNORM;
}
return mask;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
static struct sctp_bind_bucket *sctp_bucket_create(
struct sctp_bind_hashbucket *head, struct net *net, unsigned short snum)
{
struct sctp_bind_bucket *pp;
pp = kmem_cache_alloc(sctp_bucket_cachep, GFP_ATOMIC);
if (pp) {
SCTP_DBG_OBJCNT_INC(bind_bucket);
pp->port = snum;
pp->fastreuse = 0;
INIT_HLIST_HEAD(&pp->owner);
pp->net = net;
hlist_add_head(&pp->node, &head->chain);
}
return pp;
}
/* Caller must hold hashbucket lock for this tb with local BH disabled */
static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
{
if (pp && hlist_empty(&pp->owner)) {
__hlist_del(&pp->node);
kmem_cache_free(sctp_bucket_cachep, pp);
SCTP_DBG_OBJCNT_DEC(bind_bucket);
}
}
/* Release this socket's reference to a local port. */
static inline void __sctp_put_port(struct sock *sk)
{
struct sctp_bind_hashbucket *head =
&sctp_port_hashtable[sctp_phashfn(sock_net(sk),
inet_sk(sk)->inet_num)];
struct sctp_bind_bucket *pp;
spin_lock(&head->lock);
pp = sctp_sk(sk)->bind_hash;
__sk_del_bind_node(sk);
sctp_sk(sk)->bind_hash = NULL;
inet_sk(sk)->inet_num = 0;
sctp_bucket_destroy(pp);
spin_unlock(&head->lock);
}
void sctp_put_port(struct sock *sk)
{
local_bh_disable();
__sctp_put_port(sk);
local_bh_enable();
}
/*
* The system picks an ephemeral port and choose an address set equivalent
* to binding with a wildcard address.
* One of those addresses will be the primary address for the association.
* This automatically enables the multihoming capability of SCTP.
*/
static int sctp_autobind(struct sock *sk)
{
union sctp_addr autoaddr;
struct sctp_af *af;
__be16 port;
/* Initialize a local sockaddr structure to INADDR_ANY. */
af = sctp_sk(sk)->pf->af;
port = htons(inet_sk(sk)->inet_num);
af->inaddr_any(&autoaddr, port);
return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
}
/* Parse out IPPROTO_SCTP CMSG headers. Perform only minimal validation.
*
* From RFC 2292
* 4.2 The cmsghdr Structure *
*
* When ancillary data is sent or received, any number of ancillary data
* objects can be specified by the msg_control and msg_controllen members of
* the msghdr structure, because each object is preceded by
* a cmsghdr structure defining the object's length (the cmsg_len member).
* Historically Berkeley-derived implementations have passed only one object
* at a time, but this API allows multiple objects to be
* passed in a single call to sendmsg() or recvmsg(). The following example
* shows two ancillary data objects in a control buffer.
*
* |<--------------------------- msg_controllen -------------------------->|
* | |
*
* |<----- ancillary data object ----->|<----- ancillary data object ----->|
*
* |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
* | | |
*
* |<---------- cmsg_len ---------->| |<--------- cmsg_len ----------->| |
*
* |<--------- CMSG_LEN() --------->| |<-------- CMSG_LEN() ---------->| |
* | | | | |
*
* +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
* |cmsg_|cmsg_|cmsg_|XX| |XX|cmsg_|cmsg_|cmsg_|XX| |XX|
*
* |len |level|type |XX|cmsg_data[]|XX|len |level|type |XX|cmsg_data[]|XX|
*
* +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
* ^
* |
*
* msg_control
* points here
*/
static int sctp_msghdr_parse(const struct msghdr *msg, struct sctp_cmsgs *cmsgs)
{
struct msghdr *my_msg = (struct msghdr *)msg;
struct cmsghdr *cmsg;
for_each_cmsghdr(cmsg, my_msg) {
if (!CMSG_OK(my_msg, cmsg))
return -EINVAL;
/* Should we parse this header or ignore? */
if (cmsg->cmsg_level != IPPROTO_SCTP)
continue;
/* Strictly check lengths following example in SCM code. */
switch (cmsg->cmsg_type) {
case SCTP_INIT:
/* SCTP Socket API Extension
* 5.3.1 SCTP Initiation Structure (SCTP_INIT)
*
* This cmsghdr structure provides information for
* initializing new SCTP associations with sendmsg().
* The SCTP_INITMSG socket option uses this same data
* structure. This structure is not used for
* recvmsg().
*
* cmsg_level cmsg_type cmsg_data[]
* ------------ ------------ ----------------------
* IPPROTO_SCTP SCTP_INIT struct sctp_initmsg
*/
if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_initmsg)))
return -EINVAL;
cmsgs->init = CMSG_DATA(cmsg);
break;
case SCTP_SNDRCV:
/* SCTP Socket API Extension
* 5.3.2 SCTP Header Information Structure(SCTP_SNDRCV)
*
* This cmsghdr structure specifies SCTP options for
* sendmsg() and describes SCTP header information
* about a received message through recvmsg().
*
* cmsg_level cmsg_type cmsg_data[]
* ------------ ------------ ----------------------
* IPPROTO_SCTP SCTP_SNDRCV struct sctp_sndrcvinfo
*/
if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
return -EINVAL;
cmsgs->srinfo = CMSG_DATA(cmsg);
if (cmsgs->srinfo->sinfo_flags &
~(SCTP_UNORDERED | SCTP_ADDR_OVER |
SCTP_SACK_IMMEDIATELY | SCTP_SENDALL |
SCTP_PR_SCTP_MASK | SCTP_ABORT | SCTP_EOF))
return -EINVAL;
break;
case SCTP_SNDINFO:
/* SCTP Socket API Extension
* 5.3.4 SCTP Send Information Structure (SCTP_SNDINFO)
*
* This cmsghdr structure specifies SCTP options for
* sendmsg(). This structure and SCTP_RCVINFO replaces
* SCTP_SNDRCV which has been deprecated.
*
* cmsg_level cmsg_type cmsg_data[]
* ------------ ------------ ---------------------
* IPPROTO_SCTP SCTP_SNDINFO struct sctp_sndinfo
*/
if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndinfo)))
return -EINVAL;
cmsgs->sinfo = CMSG_DATA(cmsg);
if (cmsgs->sinfo->snd_flags &
~(SCTP_UNORDERED | SCTP_ADDR_OVER |
SCTP_SACK_IMMEDIATELY | SCTP_SENDALL |
SCTP_PR_SCTP_MASK | SCTP_ABORT | SCTP_EOF))
return -EINVAL;
break;
case SCTP_PRINFO:
/* SCTP Socket API Extension
* 5.3.7 SCTP PR-SCTP Information Structure (SCTP_PRINFO)
*
* This cmsghdr structure specifies SCTP options for sendmsg().
*
* cmsg_level cmsg_type cmsg_data[]
* ------------ ------------ ---------------------
* IPPROTO_SCTP SCTP_PRINFO struct sctp_prinfo
*/
if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_prinfo)))
return -EINVAL;
cmsgs->prinfo = CMSG_DATA(cmsg);
if (cmsgs->prinfo->pr_policy & ~SCTP_PR_SCTP_MASK)
return -EINVAL;
if (cmsgs->prinfo->pr_policy == SCTP_PR_SCTP_NONE)
cmsgs->prinfo->pr_value = 0;
break;
case SCTP_AUTHINFO:
/* SCTP Socket API Extension
* 5.3.8 SCTP AUTH Information Structure (SCTP_AUTHINFO)
*
* This cmsghdr structure specifies SCTP options for sendmsg().
*
* cmsg_level cmsg_type cmsg_data[]
* ------------ ------------ ---------------------
* IPPROTO_SCTP SCTP_AUTHINFO struct sctp_authinfo
*/
if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_authinfo)))
return -EINVAL;
cmsgs->authinfo = CMSG_DATA(cmsg);
break;
case SCTP_DSTADDRV4:
case SCTP_DSTADDRV6:
/* SCTP Socket API Extension
* 5.3.9/10 SCTP Destination IPv4/6 Address Structure (SCTP_DSTADDRV4/6)
*
* This cmsghdr structure specifies SCTP options for sendmsg().
*
* cmsg_level cmsg_type cmsg_data[]
* ------------ ------------ ---------------------
* IPPROTO_SCTP SCTP_DSTADDRV4 struct in_addr
* ------------ ------------ ---------------------
* IPPROTO_SCTP SCTP_DSTADDRV6 struct in6_addr
*/
cmsgs->addrs_msg = my_msg;
break;
default:
return -EINVAL;
}
}
return 0;
}
/*
* Wait for a packet..
* Note: This function is the same function as in core/datagram.c
* with a few modifications to make lksctp work.
*/
static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p)
{
int error;
DEFINE_WAIT(wait);
prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
/* Socket errors? */
error = sock_error(sk);
if (error)
goto out;
if (!skb_queue_empty(&sk->sk_receive_queue))
goto ready;
/* Socket shut down? */
if (sk->sk_shutdown & RCV_SHUTDOWN)
goto out;
/* Sequenced packets can come disconnected. If so we report the
* problem.
*/
error = -ENOTCONN;
/* Is there a good reason to think that we may receive some data? */
if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
goto out;
/* Handle signals. */
if (signal_pending(current))
goto interrupted;
/* Let another process have a go. Since we are going to sleep
* anyway. Note: This may cause odd behaviors if the message
* does not fit in the user's buffer, but this seems to be the
* only way to honor MSG_DONTWAIT realistically.
*/
release_sock(sk);
*timeo_p = schedule_timeout(*timeo_p);
lock_sock(sk);
ready:
finish_wait(sk_sleep(sk), &wait);
return 0;
interrupted:
error = sock_intr_errno(*timeo_p);
out:
finish_wait(sk_sleep(sk), &wait);
*err = error;
return error;
}
/* Receive a datagram.
* Note: This is pretty much the same routine as in core/datagram.c
* with a few changes to make lksctp work.
*/
struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags, int *err)
{
int error;
struct sk_buff *skb;
long timeo;
timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
pr_debug("%s: timeo:%ld, max:%ld\n", __func__, timeo,
MAX_SCHEDULE_TIMEOUT);
do {
/* Again only user level code calls this function,
* so nothing interrupt level
* will suddenly eat the receive_queue.
*
* Look at current nfs client by the way...
* However, this function was correct in any case. 8)
*/
if (flags & MSG_PEEK) {
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
refcount_inc(&skb->users);
} else {
skb = __skb_dequeue(&sk->sk_receive_queue);
}
if (skb)
return skb;
/* Caller is allowed not to check sk->sk_err before calling. */
error = sock_error(sk);
if (error)
goto no_packet;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk_can_busy_loop(sk)) {
sk_busy_loop(sk, flags & MSG_DONTWAIT);
if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
continue;
}
/* User doesn't want to wait. */
error = -EAGAIN;
if (!timeo)
goto no_packet;
} while (sctp_wait_for_packet(sk, err, &timeo) == 0);
return NULL;
no_packet:
*err = error;
return NULL;
}
/* If sndbuf has changed, wake up per association sndbuf waiters. */
static void __sctp_write_space(struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
if (sctp_wspace(asoc) <= 0)
return;
if (waitqueue_active(&asoc->wait))
wake_up_interruptible(&asoc->wait);
if (sctp_writeable(sk)) {
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq) {
if (waitqueue_active(&wq->wait))
wake_up_interruptible(&wq->wait);
/* Note that we try to include the Async I/O support
* here by modeling from the current TCP/UDP code.
* We have not tested with it yet.
*/
if (!(sk->sk_shutdown & SEND_SHUTDOWN))
sock_wake_async(wq, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
}
static void sctp_wake_up_waiters(struct sock *sk,
struct sctp_association *asoc)
{
struct sctp_association *tmp = asoc;
/* We do accounting for the sndbuf space per association,
* so we only need to wake our own association.
*/
if (asoc->ep->sndbuf_policy)
return __sctp_write_space(asoc);
/* If association goes down and is just flushing its
* outq, then just normally notify others.
*/
if (asoc->base.dead)
return sctp_write_space(sk);
/* Accounting for the sndbuf space is per socket, so we
* need to wake up others, try to be fair and in case of
* other associations, let them have a go first instead
* of just doing a sctp_write_space() call.
*
* Note that we reach sctp_wake_up_waiters() only when
* associations free up queued chunks, thus we are under
* lock and the list of associations on a socket is
* guaranteed not to change.
*/
for (tmp = list_next_entry(tmp, asocs); 1;
tmp = list_next_entry(tmp, asocs)) {
/* Manually skip the head element. */
if (&tmp->asocs == &((sctp_sk(sk))->ep->asocs))
continue;
/* Wake up association. */
__sctp_write_space(tmp);
/* We've reached the end. */
if (tmp == asoc)
break;
}
}
/* Do accounting for the sndbuf space.
* Decrement the used sndbuf space of the corresponding association by the
* data size which was just transmitted(freed).
*/
static void sctp_wfree(struct sk_buff *skb)
{
struct sctp_chunk *chunk = skb_shinfo(skb)->destructor_arg;
struct sctp_association *asoc = chunk->asoc;
struct sock *sk = asoc->base.sk;
sk_mem_uncharge(sk, skb->truesize);
sk_wmem_queued_add(sk, -(skb->truesize + sizeof(struct sctp_chunk)));
asoc->sndbuf_used -= skb->truesize + sizeof(struct sctp_chunk);
WARN_ON(refcount_sub_and_test(sizeof(struct sctp_chunk),
&sk->sk_wmem_alloc));
if (chunk->shkey) {
struct sctp_shared_key *shkey = chunk->shkey;
/* refcnt == 2 and !list_empty mean after this release, it's
* not being used anywhere, and it's time to notify userland
* that this shkey can be freed if it's been deactivated.
*/
if (shkey->deactivated && !list_empty(&shkey->key_list) &&
refcount_read(&shkey->refcnt) == 2) {
struct sctp_ulpevent *ev;
ev = sctp_ulpevent_make_authkey(asoc, shkey->key_id,
SCTP_AUTH_FREE_KEY,
GFP_KERNEL);
if (ev)
asoc->stream.si->enqueue_event(&asoc->ulpq, ev);
}
sctp_auth_shkey_release(chunk->shkey);
}
sock_wfree(skb);
sctp_wake_up_waiters(sk, asoc);
sctp_association_put(asoc);
}
/* Do accounting for the receive space on the socket.
* Accounting for the association is done in ulpevent.c
* We set this as a destructor for the cloned data skbs so that
* accounting is done at the correct time.
*/
void sctp_sock_rfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
struct sctp_ulpevent *event = sctp_skb2event(skb);
atomic_sub(event->rmem_len, &sk->sk_rmem_alloc);
/*
* Mimic the behavior of sock_rfree
*/
sk_mem_uncharge(sk, event->rmem_len);
}
/* Helper function to wait for space in the sndbuf. */
static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
size_t msg_len)
{
struct sock *sk = asoc->base.sk;
long current_timeo = *timeo_p;
DEFINE_WAIT(wait);
int err = 0;
pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc,
*timeo_p, msg_len);
/* Increment the association's refcnt. */
sctp_association_hold(asoc);
/* Wait on the association specific sndbuf space. */
for (;;) {
prepare_to_wait_exclusive(&asoc->wait, &wait,
TASK_INTERRUPTIBLE);
if (asoc->base.dead)
goto do_dead;
if (!*timeo_p)
goto do_nonblock;
if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING)
goto do_error;
if (signal_pending(current))
goto do_interrupted;
if ((int)msg_len <= sctp_wspace(asoc) &&
sk_wmem_schedule(sk, msg_len))
break;
/* Let another process have a go. Since we are going
* to sleep anyway.
*/
release_sock(sk);
current_timeo = schedule_timeout(current_timeo);
lock_sock(sk);
if (sk != asoc->base.sk)
goto do_error;
*timeo_p = current_timeo;
}
out:
finish_wait(&asoc->wait, &wait);
/* Release the association's refcnt. */
sctp_association_put(asoc);
return err;
do_dead:
err = -ESRCH;
goto out;
do_error:
err = -EPIPE;
goto out;
do_interrupted:
err = sock_intr_errno(*timeo_p);
goto out;
do_nonblock:
err = -EAGAIN;
goto out;
}
void sctp_data_ready(struct sock *sk)
{
struct socket_wq *wq;
trace_sk_data_ready(sk);
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (skwq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN |
EPOLLRDNORM | EPOLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
rcu_read_unlock();
}
/* If socket sndbuf has changed, wake up all per association waiters. */
void sctp_write_space(struct sock *sk)
{
struct sctp_association *asoc;
/* Wake up the tasks in each wait queue. */
list_for_each_entry(asoc, &((sctp_sk(sk))->ep->asocs), asocs) {
__sctp_write_space(asoc);
}
}
/* Is there any sndbuf space available on the socket?
*
* Note that sk_wmem_alloc is the sum of the send buffers on all of the
* associations on the same socket. For a UDP-style socket with
* multiple associations, it is possible for it to be "unwriteable"
* prematurely. I assume that this is acceptable because
* a premature "unwriteable" is better than an accidental "writeable" which
* would cause an unwanted block under certain circumstances. For the 1-1
* UDP-style sockets or TCP-style sockets, this code should work.
* - Daisy
*/
static bool sctp_writeable(const struct sock *sk)
{
return READ_ONCE(sk->sk_sndbuf) > READ_ONCE(sk->sk_wmem_queued);
}
/* Wait for an association to go into ESTABLISHED state. If timeout is 0,
* returns immediately with EINPROGRESS.
*/
static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
{
struct sock *sk = asoc->base.sk;
int err = 0;
long current_timeo = *timeo_p;
DEFINE_WAIT(wait);
pr_debug("%s: asoc:%p, timeo:%ld\n", __func__, asoc, *timeo_p);
/* Increment the association's refcnt. */
sctp_association_hold(asoc);
for (;;) {
prepare_to_wait_exclusive(&asoc->wait, &wait,
TASK_INTERRUPTIBLE);
if (!*timeo_p)
goto do_nonblock;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
asoc->base.dead)
goto do_error;
if (signal_pending(current))
goto do_interrupted;
if (sctp_state(asoc, ESTABLISHED))
break;
/* Let another process have a go. Since we are going
* to sleep anyway.
*/
release_sock(sk);
current_timeo = schedule_timeout(current_timeo);
lock_sock(sk);
*timeo_p = current_timeo;
}
out:
finish_wait(&asoc->wait, &wait);
/* Release the association's refcnt. */
sctp_association_put(asoc);
return err;
do_error:
if (asoc->init_err_counter + 1 > asoc->max_init_attempts)
err = -ETIMEDOUT;
else
err = -ECONNREFUSED;
goto out;
do_interrupted:
err = sock_intr_errno(*timeo_p);
goto out;
do_nonblock:
err = -EINPROGRESS;
goto out;
}
static int sctp_wait_for_accept(struct sock *sk, long timeo)
{
struct sctp_endpoint *ep;
int err = 0;
DEFINE_WAIT(wait);
ep = sctp_sk(sk)->ep;
for (;;) {
prepare_to_wait_exclusive(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
if (list_empty(&ep->asocs)) {
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
}
err = -EINVAL;
if (!sctp_sstate(sk, LISTENING))
break;
err = 0;
if (!list_empty(&ep->asocs))
break;
err = sock_intr_errno(timeo);
if (signal_pending(current))
break;
err = -EAGAIN;
if (!timeo)
break;
}
finish_wait(sk_sleep(sk), &wait);
return err;
}
static void sctp_wait_for_close(struct sock *sk, long timeout)
{
DEFINE_WAIT(wait);
do {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
if (list_empty(&sctp_sk(sk)->ep->asocs))
break;
release_sock(sk);
timeout = schedule_timeout(timeout);
lock_sock(sk);
} while (!signal_pending(current) && timeout);
finish_wait(sk_sleep(sk), &wait);
}
static void sctp_skb_set_owner_r_frag(struct sk_buff *skb, struct sock *sk)
{
struct sk_buff *frag;
if (!skb->data_len)
goto done;
/* Don't forget the fragments. */
skb_walk_frags(skb, frag)
sctp_skb_set_owner_r_frag(frag, sk);
done:
sctp_skb_set_owner_r(skb, sk);
}
void sctp_copy_sock(struct sock *newsk, struct sock *sk,
struct sctp_association *asoc)
{
struct inet_sock *inet = inet_sk(sk);
struct inet_sock *newinet;
struct sctp_sock *sp = sctp_sk(sk);
newsk->sk_type = sk->sk_type;
newsk->sk_bound_dev_if = sk->sk_bound_dev_if;
newsk->sk_flags = sk->sk_flags;
newsk->sk_tsflags = sk->sk_tsflags;
newsk->sk_no_check_tx = sk->sk_no_check_tx;
newsk->sk_no_check_rx = sk->sk_no_check_rx;
newsk->sk_reuse = sk->sk_reuse;
sctp_sk(newsk)->reuse = sp->reuse;
newsk->sk_shutdown = sk->sk_shutdown;
newsk->sk_destruct = sk->sk_destruct;
newsk->sk_family = sk->sk_family;
newsk->sk_protocol = IPPROTO_SCTP;
newsk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
newsk->sk_sndbuf = sk->sk_sndbuf;
newsk->sk_rcvbuf = sk->sk_rcvbuf;
newsk->sk_lingertime = sk->sk_lingertime;
newsk->sk_rcvtimeo = sk->sk_rcvtimeo;
newsk->sk_sndtimeo = sk->sk_sndtimeo;
newsk->sk_rxhash = sk->sk_rxhash;
newinet = inet_sk(newsk);
/* Initialize sk's sport, dport, rcv_saddr and daddr for
* getsockname() and getpeername()
*/
newinet->inet_sport = inet->inet_sport;
newinet->inet_saddr = inet->inet_saddr;
newinet->inet_rcv_saddr = inet->inet_rcv_saddr;
newinet->inet_dport = htons(asoc->peer.port);
newinet->pmtudisc = inet->pmtudisc;
atomic_set(&newinet->inet_id, get_random_u16());
newinet->uc_ttl = inet->uc_ttl;
inet_set_bit(MC_LOOP, newsk);
newinet->mc_ttl = 1;
newinet->mc_index = 0;
newinet->mc_list = NULL;
if (newsk->sk_flags & SK_FLAGS_TIMESTAMP)
net_enable_timestamp();
/* Set newsk security attributes from original sk and connection
* security attribute from asoc.
*/
security_sctp_sk_clone(asoc, sk, newsk);
}
static inline void sctp_copy_descendant(struct sock *sk_to,
const struct sock *sk_from)
{
size_t ancestor_size = sizeof(struct inet_sock);
ancestor_size += sk_from->sk_prot->obj_size;
ancestor_size -= offsetof(struct sctp_sock, pd_lobby);
__inet_sk_copy_descendant(sk_to, sk_from, ancestor_size);
}
/* Populate the fields of the newsk from the oldsk and migrate the assoc
* and its messages to the newsk.
*/
static int sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
struct sctp_association *assoc,
enum sctp_socket_type type)
{
struct sctp_sock *oldsp = sctp_sk(oldsk);
struct sctp_sock *newsp = sctp_sk(newsk);
struct sctp_bind_bucket *pp; /* hash list port iterator */
struct sctp_endpoint *newep = newsp->ep;
struct sk_buff *skb, *tmp;
struct sctp_ulpevent *event;
struct sctp_bind_hashbucket *head;
int err;
/* Migrate socket buffer sizes and all the socket level options to the
* new socket.
*/
newsk->sk_sndbuf = oldsk->sk_sndbuf;
newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
/* Brute force copy old sctp opt. */
sctp_copy_descendant(newsk, oldsk);
/* Restore the ep value that was overwritten with the above structure
* copy.
*/
newsp->ep = newep;
newsp->hmac = NULL;
/* Hook this new socket in to the bind_hash list. */
head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk),
inet_sk(oldsk)->inet_num)];
spin_lock_bh(&head->lock);
pp = sctp_sk(oldsk)->bind_hash;
sk_add_bind_node(newsk, &pp->owner);
sctp_sk(newsk)->bind_hash = pp;
inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num;
spin_unlock_bh(&head->lock);
/* Copy the bind_addr list from the original endpoint to the new
* endpoint so that we can handle restarts properly
*/
err = sctp_bind_addr_dup(&newsp->ep->base.bind_addr,
&oldsp->ep->base.bind_addr, GFP_KERNEL);
if (err)
return err;
/* New ep's auth_hmacs should be set if old ep's is set, in case
* that net->sctp.auth_enable has been changed to 0 by users and
* new ep's auth_hmacs couldn't be set in sctp_endpoint_init().
*/
if (oldsp->ep->auth_hmacs) {
err = sctp_auth_init_hmacs(newsp->ep, GFP_KERNEL);
if (err)
return err;
}
sctp_auto_asconf_init(newsp);
/* Move any messages in the old socket's receive queue that are for the
* peeled off association to the new socket's receive queue.
*/
sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
__skb_unlink(skb, &oldsk->sk_receive_queue);
__skb_queue_tail(&newsk->sk_receive_queue, skb);
sctp_skb_set_owner_r_frag(skb, newsk);
}
}
/* Clean up any messages pending delivery due to partial
* delivery. Three cases:
* 1) No partial deliver; no work.
* 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
* 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
*/
atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
struct sk_buff_head *queue;
/* Decide which queue to move pd_lobby skbs to. */
if (assoc->ulpq.pd_mode) {
queue = &newsp->pd_lobby;
} else
queue = &newsk->sk_receive_queue;
/* Walk through the pd_lobby, looking for skbs that
* need moved to the new socket.
*/
sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
__skb_unlink(skb, &oldsp->pd_lobby);
__skb_queue_tail(queue, skb);
sctp_skb_set_owner_r_frag(skb, newsk);
}
}
/* Clear up any skbs waiting for the partial
* delivery to finish.
*/
if (assoc->ulpq.pd_mode)
sctp_clear_pd(oldsk, NULL);
}
sctp_for_each_rx_skb(assoc, newsk, sctp_skb_set_owner_r_frag);
/* Set the type of socket to indicate that it is peeled off from the
* original UDP-style socket or created with the accept() call on a
* TCP-style socket..
*/
newsp->type = type;
/* Mark the new socket "in-use" by the user so that any packets
* that may arrive on the association after we've moved it are
* queued to the backlog. This prevents a potential race between
* backlog processing on the old socket and new-packet processing
* on the new socket.
*
* The caller has just allocated newsk so we can guarantee that other
* paths won't try to lock it and then oldsk.
*/
lock_sock_nested(newsk, SINGLE_DEPTH_NESTING);
sctp_for_each_tx_datachunk(assoc, true, sctp_clear_owner_w);
sctp_assoc_migrate(assoc, newsk);
sctp_for_each_tx_datachunk(assoc, false, sctp_set_owner_w);
/* If the association on the newsk is already closed before accept()
* is called, set RCV_SHUTDOWN flag.
*/
if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP)) {
inet_sk_set_state(newsk, SCTP_SS_CLOSED);
newsk->sk_shutdown |= RCV_SHUTDOWN;
} else {
inet_sk_set_state(newsk, SCTP_SS_ESTABLISHED);
}
release_sock(newsk);
return 0;
}
/* This proto struct describes the ULP interface for SCTP. */
struct proto sctp_prot = {
.name = "SCTP",
.owner = THIS_MODULE,
.close = sctp_close,
.disconnect = sctp_disconnect,
.accept = sctp_accept,
.ioctl = sctp_ioctl,
.init = sctp_init_sock,
.destroy = sctp_destroy_sock,
.shutdown = sctp_shutdown,
.setsockopt = sctp_setsockopt,
.getsockopt = sctp_getsockopt,
.bpf_bypass_getsockopt = sctp_bpf_bypass_getsockopt,
.sendmsg = sctp_sendmsg,
.recvmsg = sctp_recvmsg,
.bind = sctp_bind,
.bind_add = sctp_bind_add,
.backlog_rcv = sctp_backlog_rcv,
.hash = sctp_hash,
.unhash = sctp_unhash,
.no_autobind = true,
.obj_size = sizeof(struct sctp_sock),
.useroffset = offsetof(struct sctp_sock, subscribe),
.usersize = offsetof(struct sctp_sock, initmsg) -
offsetof(struct sctp_sock, subscribe) +
sizeof_field(struct sctp_sock, initmsg),
.sysctl_mem = sysctl_sctp_mem,
.sysctl_rmem = sysctl_sctp_rmem,
.sysctl_wmem = sysctl_sctp_wmem,
.memory_pressure = &sctp_memory_pressure,
.enter_memory_pressure = sctp_enter_memory_pressure,
.memory_allocated = &sctp_memory_allocated,
.per_cpu_fw_alloc = &sctp_memory_per_cpu_fw_alloc,
.sockets_allocated = &sctp_sockets_allocated,
};
#if IS_ENABLED(CONFIG_IPV6)
static void sctp_v6_destruct_sock(struct sock *sk)
{
sctp_destruct_common(sk);
inet6_sock_destruct(sk);
}
static int sctp_v6_init_sock(struct sock *sk)
{
int ret = sctp_init_sock(sk);
if (!ret)
sk->sk_destruct = sctp_v6_destruct_sock;
return ret;
}
struct proto sctpv6_prot = {
.name = "SCTPv6",
.owner = THIS_MODULE,
.close = sctp_close,
.disconnect = sctp_disconnect,
.accept = sctp_accept,
.ioctl = sctp_ioctl,
.init = sctp_v6_init_sock,
.destroy = sctp_destroy_sock,
.shutdown = sctp_shutdown,
.setsockopt = sctp_setsockopt,
.getsockopt = sctp_getsockopt,
.bpf_bypass_getsockopt = sctp_bpf_bypass_getsockopt,
.sendmsg = sctp_sendmsg,
.recvmsg = sctp_recvmsg,
.bind = sctp_bind,
.bind_add = sctp_bind_add,
.backlog_rcv = sctp_backlog_rcv,
.hash = sctp_hash,
.unhash = sctp_unhash,
.no_autobind = true,
.obj_size = sizeof(struct sctp6_sock),
.ipv6_pinfo_offset = offsetof(struct sctp6_sock, inet6),
.useroffset = offsetof(struct sctp6_sock, sctp.subscribe),
.usersize = offsetof(struct sctp6_sock, sctp.initmsg) -
offsetof(struct sctp6_sock, sctp.subscribe) +
sizeof_field(struct sctp6_sock, sctp.initmsg),
.sysctl_mem = sysctl_sctp_mem,
.sysctl_rmem = sysctl_sctp_rmem,
.sysctl_wmem = sysctl_sctp_wmem,
.memory_pressure = &sctp_memory_pressure,
.enter_memory_pressure = sctp_enter_memory_pressure,
.memory_allocated = &sctp_memory_allocated,
.per_cpu_fw_alloc = &sctp_memory_per_cpu_fw_alloc,
.sockets_allocated = &sctp_sockets_allocated,
};
#endif /* IS_ENABLED(CONFIG_IPV6) */
| linux-master | net/sctp/socket.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* sctp_offload - GRO/GSO Offloading for SCTP
*
* Copyright (C) 2015, Marcelo Ricardo Leitner <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/socket.h>
#include <linux/sctp.h>
#include <linux/proc_fs.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
#include <linux/kfifo.h>
#include <linux/time.h>
#include <net/net_namespace.h>
#include <linux/skbuff.h>
#include <net/sctp/sctp.h>
#include <net/sctp/checksum.h>
#include <net/protocol.h>
#include <net/gso.h>
static __le32 sctp_gso_make_checksum(struct sk_buff *skb)
{
skb->ip_summed = CHECKSUM_NONE;
skb->csum_not_inet = 0;
/* csum and csum_start in GSO CB may be needed to do the UDP
* checksum when it's a UDP tunneling packet.
*/
SKB_GSO_CB(skb)->csum = (__force __wsum)~0;
SKB_GSO_CB(skb)->csum_start = skb_headroom(skb) + skb->len;
return sctp_compute_cksum(skb, skb_transport_offset(skb));
}
static struct sk_buff *sctp_gso_segment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
struct sctphdr *sh;
if (!skb_is_gso_sctp(skb))
goto out;
sh = sctp_hdr(skb);
if (!pskb_may_pull(skb, sizeof(*sh)))
goto out;
__skb_pull(skb, sizeof(*sh));
if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
/* Packet is from an untrusted source, reset gso_segs. */
struct skb_shared_info *pinfo = skb_shinfo(skb);
struct sk_buff *frag_iter;
pinfo->gso_segs = 0;
if (skb->len != skb->data_len) {
/* Means we have chunks in here too */
pinfo->gso_segs++;
}
skb_walk_frags(skb, frag_iter)
pinfo->gso_segs++;
segs = NULL;
goto out;
}
segs = skb_segment(skb, (features | NETIF_F_HW_CSUM) & ~NETIF_F_SG);
if (IS_ERR(segs))
goto out;
/* All that is left is update SCTP CRC if necessary */
if (!(features & NETIF_F_SCTP_CRC)) {
for (skb = segs; skb; skb = skb->next) {
if (skb->ip_summed == CHECKSUM_PARTIAL) {
sh = sctp_hdr(skb);
sh->checksum = sctp_gso_make_checksum(skb);
}
}
}
out:
return segs;
}
static const struct net_offload sctp_offload = {
.callbacks = {
.gso_segment = sctp_gso_segment,
},
};
static const struct net_offload sctp6_offload = {
.callbacks = {
.gso_segment = sctp_gso_segment,
},
};
int __init sctp_offload_init(void)
{
int ret;
ret = inet_add_offload(&sctp_offload, IPPROTO_SCTP);
if (ret)
goto out;
ret = inet6_add_offload(&sctp6_offload, IPPROTO_SCTP);
if (ret)
goto ipv4;
crc32c_csum_stub = &sctp_csum_ops;
return ret;
ipv4:
inet_del_offload(&sctp_offload, IPPROTO_SCTP);
out:
return ret;
}
| linux-master | net/sctp/offload.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 Nokia, Inc.
*
* This file is part of the SCTP kernel implementation
*
* These are the state tables for the SCTP state machine.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Jon Grimm <[email protected]>
* Hui Huang <[email protected]>
* Daisy Chang <[email protected]>
* Ardelle Fan <[email protected]>
* Sridhar Samudrala <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/skbuff.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
static const struct sctp_sm_table_entry
primitive_event_table[SCTP_NUM_PRIMITIVE_TYPES][SCTP_STATE_NUM_STATES];
static const struct sctp_sm_table_entry
other_event_table[SCTP_NUM_OTHER_TYPES][SCTP_STATE_NUM_STATES];
static const struct sctp_sm_table_entry
timeout_event_table[SCTP_NUM_TIMEOUT_TYPES][SCTP_STATE_NUM_STATES];
static const struct sctp_sm_table_entry *sctp_chunk_event_lookup(
struct net *net,
enum sctp_cid cid,
enum sctp_state state);
static const struct sctp_sm_table_entry bug = {
.fn = sctp_sf_bug,
.name = "sctp_sf_bug"
};
#define DO_LOOKUP(_max, _type, _table) \
({ \
const struct sctp_sm_table_entry *rtn; \
\
if ((event_subtype._type > (_max))) { \
pr_warn("table %p possible attack: event %d exceeds max %d\n", \
_table, event_subtype._type, _max); \
rtn = &bug; \
} else \
rtn = &_table[event_subtype._type][(int)state]; \
\
rtn; \
})
const struct sctp_sm_table_entry *sctp_sm_lookup_event(
struct net *net,
enum sctp_event_type event_type,
enum sctp_state state,
union sctp_subtype event_subtype)
{
switch (event_type) {
case SCTP_EVENT_T_CHUNK:
return sctp_chunk_event_lookup(net, event_subtype.chunk, state);
case SCTP_EVENT_T_TIMEOUT:
return DO_LOOKUP(SCTP_EVENT_TIMEOUT_MAX, timeout,
timeout_event_table);
case SCTP_EVENT_T_OTHER:
return DO_LOOKUP(SCTP_EVENT_OTHER_MAX, other,
other_event_table);
case SCTP_EVENT_T_PRIMITIVE:
return DO_LOOKUP(SCTP_EVENT_PRIMITIVE_MAX, primitive,
primitive_event_table);
default:
/* Yikes! We got an illegal event type. */
return &bug;
}
}
#define TYPE_SCTP_FUNC(func) {.fn = func, .name = #func}
#define TYPE_SCTP_DATA { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ootb), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_eat_data_6_2), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_eat_data_6_2), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_eat_data_fast_4_4), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_DATA */
#define TYPE_SCTP_INIT { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_1B_init), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_1_siminit), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_1_siminit), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_2_dupinit), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_2_dupinit), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_2_dupinit), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_2_dupinit), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_2_reshutack), \
} /* TYPE_SCTP_INIT */
#define TYPE_SCTP_INIT_ACK { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_3_initack), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_1C_ack), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_INIT_ACK */
#define TYPE_SCTP_SACK { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ootb), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_eat_sack_6_2), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_eat_sack_6_2), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_eat_sack_6_2), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_eat_sack_6_2), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_SACK */
#define TYPE_SCTP_HEARTBEAT { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ootb), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_beat_8_3), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_beat_8_3), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_beat_8_3), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_beat_8_3), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_beat_8_3), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
/* This should not happen, but we are nice. */ \
TYPE_SCTP_FUNC(sctp_sf_beat_8_3), \
} /* TYPE_SCTP_HEARTBEAT */
#define TYPE_SCTP_HEARTBEAT_ACK { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ootb), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_violation), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_backbeat_8_3), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_backbeat_8_3), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_backbeat_8_3), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_backbeat_8_3), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_HEARTBEAT_ACK */
#define TYPE_SCTP_ABORT { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_pdiscard), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_cookie_wait_abort), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_cookie_echoed_abort), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_1_abort), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_shutdown_pending_abort), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_shutdown_sent_abort), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_1_abort), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_shutdown_ack_sent_abort), \
} /* TYPE_SCTP_ABORT */
#define TYPE_SCTP_SHUTDOWN { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ootb), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_2_shutdown), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_2_shutdown), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_2_shutdown_ack), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_2_shut_ctsn), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_SHUTDOWN */
#define TYPE_SCTP_SHUTDOWN_ACK { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ootb), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_do_8_5_1_E_sa), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_do_8_5_1_E_sa), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_violation), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_violation), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_2_final), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_violation), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_2_final), \
} /* TYPE_SCTP_SHUTDOWN_ACK */
#define TYPE_SCTP_ERROR { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ootb), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_cookie_echoed_err), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_operr_notify), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_operr_notify), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_operr_notify), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_ERROR */
#define TYPE_SCTP_COOKIE_ECHO { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_1D_ce), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_4_dupcook), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_4_dupcook), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_4_dupcook), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_4_dupcook), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_4_dupcook), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_4_dupcook), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_2_4_dupcook), \
} /* TYPE_SCTP_COOKIE_ECHO */
#define TYPE_SCTP_COOKIE_ACK { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_do_5_1E_ca), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_COOKIE_ACK */
#define TYPE_SCTP_ECN_ECNE { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_do_ecne), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_ecne), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_ecne), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_ecne), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_ecne), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_ECN_ECNE */
#define TYPE_SCTP_ECN_CWR { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_ecn_cwr), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_ecn_cwr), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_ecn_cwr), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_ECN_CWR */
#define TYPE_SCTP_SHUTDOWN_COMPLETE { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_4_C), \
} /* TYPE_SCTP_SHUTDOWN_COMPLETE */
/* The primary index for this table is the chunk type.
* The secondary index for this table is the state.
*
* For base protocol (RFC 2960).
*/
static const struct sctp_sm_table_entry
chunk_event_table[SCTP_NUM_BASE_CHUNK_TYPES][SCTP_STATE_NUM_STATES] = {
TYPE_SCTP_DATA,
TYPE_SCTP_INIT,
TYPE_SCTP_INIT_ACK,
TYPE_SCTP_SACK,
TYPE_SCTP_HEARTBEAT,
TYPE_SCTP_HEARTBEAT_ACK,
TYPE_SCTP_ABORT,
TYPE_SCTP_SHUTDOWN,
TYPE_SCTP_SHUTDOWN_ACK,
TYPE_SCTP_ERROR,
TYPE_SCTP_COOKIE_ECHO,
TYPE_SCTP_COOKIE_ACK,
TYPE_SCTP_ECN_ECNE,
TYPE_SCTP_ECN_CWR,
TYPE_SCTP_SHUTDOWN_COMPLETE,
}; /* state_fn_t chunk_event_table[][] */
#define TYPE_SCTP_ASCONF { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_asconf), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_asconf), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_asconf), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_asconf), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_ASCONF */
#define TYPE_SCTP_ASCONF_ACK { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_asconf_ack), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_asconf_ack), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_asconf_ack), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_asconf_ack), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_ASCONF_ACK */
/* The primary index for this table is the chunk type.
* The secondary index for this table is the state.
*/
static const struct sctp_sm_table_entry
addip_chunk_event_table[SCTP_NUM_ADDIP_CHUNK_TYPES][SCTP_STATE_NUM_STATES] = {
TYPE_SCTP_ASCONF,
TYPE_SCTP_ASCONF_ACK,
}; /*state_fn_t addip_chunk_event_table[][] */
#define TYPE_SCTP_FWD_TSN { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ootb), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_eat_fwd_tsn), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_eat_fwd_tsn), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_eat_fwd_tsn_fast), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_FWD_TSN */
/* The primary index for this table is the chunk type.
* The secondary index for this table is the state.
*/
static const struct sctp_sm_table_entry
prsctp_chunk_event_table[SCTP_NUM_PRSCTP_CHUNK_TYPES][SCTP_STATE_NUM_STATES] = {
TYPE_SCTP_FWD_TSN,
}; /*state_fn_t prsctp_chunk_event_table[][] */
#define TYPE_SCTP_RECONF { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_reconf), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_reconf), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
} /* TYPE_SCTP_RECONF */
/* The primary index for this table is the chunk type.
* The secondary index for this table is the state.
*/
static const struct sctp_sm_table_entry
reconf_chunk_event_table[SCTP_NUM_RECONF_CHUNK_TYPES][SCTP_STATE_NUM_STATES] = {
TYPE_SCTP_RECONF,
}; /*state_fn_t reconf_chunk_event_table[][] */
#define TYPE_SCTP_AUTH { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ootb), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_discard_chunk), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_eat_auth), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_eat_auth), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_eat_auth), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_eat_auth), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_eat_auth), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_eat_auth), \
} /* TYPE_SCTP_AUTH */
/* The primary index for this table is the chunk type.
* The secondary index for this table is the state.
*/
static const struct sctp_sm_table_entry
auth_chunk_event_table[SCTP_NUM_AUTH_CHUNK_TYPES][SCTP_STATE_NUM_STATES] = {
TYPE_SCTP_AUTH,
}; /*state_fn_t auth_chunk_event_table[][] */
static const struct sctp_sm_table_entry
pad_chunk_event_table[SCTP_STATE_NUM_STATES] = {
/* SCTP_STATE_CLOSED */
TYPE_SCTP_FUNC(sctp_sf_discard_chunk),
/* SCTP_STATE_COOKIE_WAIT */
TYPE_SCTP_FUNC(sctp_sf_discard_chunk),
/* SCTP_STATE_COOKIE_ECHOED */
TYPE_SCTP_FUNC(sctp_sf_discard_chunk),
/* SCTP_STATE_ESTABLISHED */
TYPE_SCTP_FUNC(sctp_sf_discard_chunk),
/* SCTP_STATE_SHUTDOWN_PENDING */
TYPE_SCTP_FUNC(sctp_sf_discard_chunk),
/* SCTP_STATE_SHUTDOWN_SENT */
TYPE_SCTP_FUNC(sctp_sf_discard_chunk),
/* SCTP_STATE_SHUTDOWN_RECEIVED */
TYPE_SCTP_FUNC(sctp_sf_discard_chunk),
/* SCTP_STATE_SHUTDOWN_ACK_SENT */
TYPE_SCTP_FUNC(sctp_sf_discard_chunk),
}; /* chunk pad */
static const struct sctp_sm_table_entry
chunk_event_table_unknown[SCTP_STATE_NUM_STATES] = {
/* SCTP_STATE_CLOSED */
TYPE_SCTP_FUNC(sctp_sf_ootb),
/* SCTP_STATE_COOKIE_WAIT */
TYPE_SCTP_FUNC(sctp_sf_unk_chunk),
/* SCTP_STATE_COOKIE_ECHOED */
TYPE_SCTP_FUNC(sctp_sf_unk_chunk),
/* SCTP_STATE_ESTABLISHED */
TYPE_SCTP_FUNC(sctp_sf_unk_chunk),
/* SCTP_STATE_SHUTDOWN_PENDING */
TYPE_SCTP_FUNC(sctp_sf_unk_chunk),
/* SCTP_STATE_SHUTDOWN_SENT */
TYPE_SCTP_FUNC(sctp_sf_unk_chunk),
/* SCTP_STATE_SHUTDOWN_RECEIVED */
TYPE_SCTP_FUNC(sctp_sf_unk_chunk),
/* SCTP_STATE_SHUTDOWN_ACK_SENT */
TYPE_SCTP_FUNC(sctp_sf_unk_chunk),
}; /* chunk unknown */
#define TYPE_SCTP_PRIMITIVE_ASSOCIATE { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_asoc), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_not_impl), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_not_impl), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_not_impl), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_not_impl), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_not_impl), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_not_impl), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_not_impl), \
} /* TYPE_SCTP_PRIMITIVE_ASSOCIATE */
#define TYPE_SCTP_PRIMITIVE_SHUTDOWN { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_error_closed), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_cookie_wait_prm_shutdown), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_cookie_echoed_prm_shutdown),\
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_2_prm_shutdown), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_primitive), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_primitive), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_primitive), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_primitive), \
} /* TYPE_SCTP_PRIMITIVE_SHUTDOWN */
#define TYPE_SCTP_PRIMITIVE_ABORT { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_error_closed), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_cookie_wait_prm_abort), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_cookie_echoed_prm_abort), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_1_prm_abort), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_shutdown_pending_prm_abort), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_shutdown_sent_prm_abort), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_1_prm_abort), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_shutdown_ack_sent_prm_abort), \
} /* TYPE_SCTP_PRIMITIVE_ABORT */
#define TYPE_SCTP_PRIMITIVE_SEND { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_error_closed), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_send), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_send), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_send), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_error_shutdown), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_error_shutdown), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_error_shutdown), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_error_shutdown), \
} /* TYPE_SCTP_PRIMITIVE_SEND */
#define TYPE_SCTP_PRIMITIVE_REQUESTHEARTBEAT { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_error_closed), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_requestheartbeat), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_requestheartbeat), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_requestheartbeat), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_requestheartbeat), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_requestheartbeat), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_requestheartbeat), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_requestheartbeat), \
} /* TYPE_SCTP_PRIMITIVE_REQUESTHEARTBEAT */
#define TYPE_SCTP_PRIMITIVE_ASCONF { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_error_closed), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_error_closed), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_error_closed), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_asconf), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_asconf), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_asconf), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_asconf), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_error_shutdown), \
} /* TYPE_SCTP_PRIMITIVE_ASCONF */
#define TYPE_SCTP_PRIMITIVE_RECONF { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_error_closed), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_error_closed), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_error_closed), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_reconf), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_reconf), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_reconf), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_prm_reconf), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_error_shutdown), \
} /* TYPE_SCTP_PRIMITIVE_RECONF */
/* The primary index for this table is the primitive type.
* The secondary index for this table is the state.
*/
static const struct sctp_sm_table_entry
primitive_event_table[SCTP_NUM_PRIMITIVE_TYPES][SCTP_STATE_NUM_STATES] = {
TYPE_SCTP_PRIMITIVE_ASSOCIATE,
TYPE_SCTP_PRIMITIVE_SHUTDOWN,
TYPE_SCTP_PRIMITIVE_ABORT,
TYPE_SCTP_PRIMITIVE_SEND,
TYPE_SCTP_PRIMITIVE_REQUESTHEARTBEAT,
TYPE_SCTP_PRIMITIVE_ASCONF,
TYPE_SCTP_PRIMITIVE_RECONF,
};
#define TYPE_SCTP_OTHER_NO_PENDING_TSN { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_no_pending_tsn), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_2_start_shutdown), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_9_2_shutdown_ack), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
}
#define TYPE_SCTP_OTHER_ICMP_PROTO_UNREACH { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_cookie_wait_icmp_abort), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_ignore_other), \
}
static const struct sctp_sm_table_entry
other_event_table[SCTP_NUM_OTHER_TYPES][SCTP_STATE_NUM_STATES] = {
TYPE_SCTP_OTHER_NO_PENDING_TSN,
TYPE_SCTP_OTHER_ICMP_PROTO_UNREACH,
};
#define TYPE_SCTP_EVENT_TIMEOUT_NONE { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_bug), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_bug), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_bug), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_bug), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_bug), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_bug), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_bug), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_bug), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_T1_COOKIE { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_bug), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_t1_cookie_timer_expire), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_T1_INIT { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_t1_init_timer_expire), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_T2_SHUTDOWN { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_t2_timer_expire), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_t2_timer_expire), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_T3_RTX { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_do_6_3_3_rtx), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_6_3_3_rtx), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_6_3_3_rtx), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_do_6_3_3_rtx), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_T4_RTO { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_t4_timer_expire), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_t5_timer_expire), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_t5_timer_expire), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_HEARTBEAT { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_sendbeat_8_3), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_sendbeat_8_3), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_sendbeat_8_3), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_SACK { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_do_6_2_sack), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_do_6_2_sack), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_do_6_2_sack), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_AUTOCLOSE { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_autoclose_timer_expire), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_RECONF { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_send_reconf), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
}
#define TYPE_SCTP_EVENT_TIMEOUT_PROBE { \
/* SCTP_STATE_CLOSED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_WAIT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_COOKIE_ECHOED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_ESTABLISHED */ \
TYPE_SCTP_FUNC(sctp_sf_send_probe), \
/* SCTP_STATE_SHUTDOWN_PENDING */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_RECEIVED */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
/* SCTP_STATE_SHUTDOWN_ACK_SENT */ \
TYPE_SCTP_FUNC(sctp_sf_timer_ignore), \
}
static const struct sctp_sm_table_entry
timeout_event_table[SCTP_NUM_TIMEOUT_TYPES][SCTP_STATE_NUM_STATES] = {
TYPE_SCTP_EVENT_TIMEOUT_NONE,
TYPE_SCTP_EVENT_TIMEOUT_T1_COOKIE,
TYPE_SCTP_EVENT_TIMEOUT_T1_INIT,
TYPE_SCTP_EVENT_TIMEOUT_T2_SHUTDOWN,
TYPE_SCTP_EVENT_TIMEOUT_T3_RTX,
TYPE_SCTP_EVENT_TIMEOUT_T4_RTO,
TYPE_SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD,
TYPE_SCTP_EVENT_TIMEOUT_HEARTBEAT,
TYPE_SCTP_EVENT_TIMEOUT_RECONF,
TYPE_SCTP_EVENT_TIMEOUT_PROBE,
TYPE_SCTP_EVENT_TIMEOUT_SACK,
TYPE_SCTP_EVENT_TIMEOUT_AUTOCLOSE,
};
static const struct sctp_sm_table_entry *sctp_chunk_event_lookup(
struct net *net,
enum sctp_cid cid,
enum sctp_state state)
{
if (state > SCTP_STATE_MAX)
return &bug;
if (cid == SCTP_CID_I_DATA)
cid = SCTP_CID_DATA;
if (cid <= SCTP_CID_BASE_MAX)
return &chunk_event_table[cid][state];
switch ((u16)cid) {
case SCTP_CID_FWD_TSN:
case SCTP_CID_I_FWD_TSN:
return &prsctp_chunk_event_table[0][state];
case SCTP_CID_ASCONF:
return &addip_chunk_event_table[0][state];
case SCTP_CID_ASCONF_ACK:
return &addip_chunk_event_table[1][state];
case SCTP_CID_RECONF:
return &reconf_chunk_event_table[0][state];
case SCTP_CID_AUTH:
return &auth_chunk_event_table[0][state];
case SCTP_CID_PAD:
return &pad_chunk_event_table[state];
}
return &chunk_event_table_unknown[state];
}
| linux-master | net/sctp/sm_statetable.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright Red Hat Inc. 2017
*
* This file is part of the SCTP kernel implementation
*
* These functions implement sctp stream message interleaving, mostly
* including I-DATA and I-FORWARD-TSN chunks process.
*
* Please send any bug reports or fixes you make to the
* email addresched(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Xin Long <[email protected]>
*/
#include <net/busy_poll.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/ulpevent.h>
#include <linux/sctp.h>
static struct sctp_chunk *sctp_make_idatafrag_empty(
const struct sctp_association *asoc,
const struct sctp_sndrcvinfo *sinfo,
int len, __u8 flags, gfp_t gfp)
{
struct sctp_chunk *retval;
struct sctp_idatahdr dp;
memset(&dp, 0, sizeof(dp));
dp.stream = htons(sinfo->sinfo_stream);
if (sinfo->sinfo_flags & SCTP_UNORDERED)
flags |= SCTP_DATA_UNORDERED;
retval = sctp_make_idata(asoc, flags, sizeof(dp) + len, gfp);
if (!retval)
return NULL;
retval->subh.idata_hdr = sctp_addto_chunk(retval, sizeof(dp), &dp);
memcpy(&retval->sinfo, sinfo, sizeof(struct sctp_sndrcvinfo));
return retval;
}
static void sctp_chunk_assign_mid(struct sctp_chunk *chunk)
{
struct sctp_stream *stream;
struct sctp_chunk *lchunk;
__u32 cfsn = 0;
__u16 sid;
if (chunk->has_mid)
return;
sid = sctp_chunk_stream_no(chunk);
stream = &chunk->asoc->stream;
list_for_each_entry(lchunk, &chunk->msg->chunks, frag_list) {
struct sctp_idatahdr *hdr;
__u32 mid;
lchunk->has_mid = 1;
hdr = lchunk->subh.idata_hdr;
if (lchunk->chunk_hdr->flags & SCTP_DATA_FIRST_FRAG)
hdr->ppid = lchunk->sinfo.sinfo_ppid;
else
hdr->fsn = htonl(cfsn++);
if (lchunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
mid = lchunk->chunk_hdr->flags & SCTP_DATA_LAST_FRAG ?
sctp_mid_uo_next(stream, out, sid) :
sctp_mid_uo_peek(stream, out, sid);
} else {
mid = lchunk->chunk_hdr->flags & SCTP_DATA_LAST_FRAG ?
sctp_mid_next(stream, out, sid) :
sctp_mid_peek(stream, out, sid);
}
hdr->mid = htonl(mid);
}
}
static bool sctp_validate_data(struct sctp_chunk *chunk)
{
struct sctp_stream *stream;
__u16 sid, ssn;
if (chunk->chunk_hdr->type != SCTP_CID_DATA)
return false;
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED)
return true;
stream = &chunk->asoc->stream;
sid = sctp_chunk_stream_no(chunk);
ssn = ntohs(chunk->subh.data_hdr->ssn);
return !SSN_lt(ssn, sctp_ssn_peek(stream, in, sid));
}
static bool sctp_validate_idata(struct sctp_chunk *chunk)
{
struct sctp_stream *stream;
__u32 mid;
__u16 sid;
if (chunk->chunk_hdr->type != SCTP_CID_I_DATA)
return false;
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED)
return true;
stream = &chunk->asoc->stream;
sid = sctp_chunk_stream_no(chunk);
mid = ntohl(chunk->subh.idata_hdr->mid);
return !MID_lt(mid, sctp_mid_peek(stream, in, sid));
}
static void sctp_intl_store_reasm(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sctp_ulpevent *cevent;
struct sk_buff *pos, *loc;
pos = skb_peek_tail(&ulpq->reasm);
if (!pos) {
__skb_queue_tail(&ulpq->reasm, sctp_event2skb(event));
return;
}
cevent = sctp_skb2event(pos);
if (event->stream == cevent->stream &&
event->mid == cevent->mid &&
(cevent->msg_flags & SCTP_DATA_FIRST_FRAG ||
(!(event->msg_flags & SCTP_DATA_FIRST_FRAG) &&
event->fsn > cevent->fsn))) {
__skb_queue_tail(&ulpq->reasm, sctp_event2skb(event));
return;
}
if ((event->stream == cevent->stream &&
MID_lt(cevent->mid, event->mid)) ||
event->stream > cevent->stream) {
__skb_queue_tail(&ulpq->reasm, sctp_event2skb(event));
return;
}
loc = NULL;
skb_queue_walk(&ulpq->reasm, pos) {
cevent = sctp_skb2event(pos);
if (event->stream < cevent->stream ||
(event->stream == cevent->stream &&
MID_lt(event->mid, cevent->mid))) {
loc = pos;
break;
}
if (event->stream == cevent->stream &&
event->mid == cevent->mid &&
!(cevent->msg_flags & SCTP_DATA_FIRST_FRAG) &&
(event->msg_flags & SCTP_DATA_FIRST_FRAG ||
event->fsn < cevent->fsn)) {
loc = pos;
break;
}
}
if (!loc)
__skb_queue_tail(&ulpq->reasm, sctp_event2skb(event));
else
__skb_queue_before(&ulpq->reasm, loc, sctp_event2skb(event));
}
static struct sctp_ulpevent *sctp_intl_retrieve_partial(
struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sk_buff *first_frag = NULL;
struct sk_buff *last_frag = NULL;
struct sctp_ulpevent *retval;
struct sctp_stream_in *sin;
struct sk_buff *pos;
__u32 next_fsn = 0;
int is_last = 0;
sin = sctp_stream_in(&ulpq->asoc->stream, event->stream);
skb_queue_walk(&ulpq->reasm, pos) {
struct sctp_ulpevent *cevent = sctp_skb2event(pos);
if (cevent->stream < event->stream)
continue;
if (cevent->stream > event->stream ||
cevent->mid != sin->mid)
break;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
goto out;
case SCTP_DATA_MIDDLE_FRAG:
if (!first_frag) {
if (cevent->fsn == sin->fsn) {
first_frag = pos;
last_frag = pos;
next_fsn = cevent->fsn + 1;
}
} else if (cevent->fsn == next_fsn) {
last_frag = pos;
next_fsn++;
} else {
goto out;
}
break;
case SCTP_DATA_LAST_FRAG:
if (!first_frag) {
if (cevent->fsn == sin->fsn) {
first_frag = pos;
last_frag = pos;
next_fsn = 0;
is_last = 1;
}
} else if (cevent->fsn == next_fsn) {
last_frag = pos;
next_fsn = 0;
is_last = 1;
}
goto out;
default:
goto out;
}
}
out:
if (!first_frag)
return NULL;
retval = sctp_make_reassembled_event(ulpq->asoc->base.net, &ulpq->reasm,
first_frag, last_frag);
if (retval) {
sin->fsn = next_fsn;
if (is_last) {
retval->msg_flags |= MSG_EOR;
sin->pd_mode = 0;
}
}
return retval;
}
static struct sctp_ulpevent *sctp_intl_retrieve_reassembled(
struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sctp_association *asoc = ulpq->asoc;
struct sk_buff *pos, *first_frag = NULL;
struct sctp_ulpevent *retval = NULL;
struct sk_buff *pd_first = NULL;
struct sk_buff *pd_last = NULL;
struct sctp_stream_in *sin;
__u32 next_fsn = 0;
__u32 pd_point = 0;
__u32 pd_len = 0;
__u32 mid = 0;
sin = sctp_stream_in(&ulpq->asoc->stream, event->stream);
skb_queue_walk(&ulpq->reasm, pos) {
struct sctp_ulpevent *cevent = sctp_skb2event(pos);
if (cevent->stream < event->stream)
continue;
if (cevent->stream > event->stream)
break;
if (MID_lt(cevent->mid, event->mid))
continue;
if (MID_lt(event->mid, cevent->mid))
break;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
if (cevent->mid == sin->mid) {
pd_first = pos;
pd_last = pos;
pd_len = pos->len;
}
first_frag = pos;
next_fsn = 0;
mid = cevent->mid;
break;
case SCTP_DATA_MIDDLE_FRAG:
if (first_frag && cevent->mid == mid &&
cevent->fsn == next_fsn) {
next_fsn++;
if (pd_first) {
pd_last = pos;
pd_len += pos->len;
}
} else {
first_frag = NULL;
}
break;
case SCTP_DATA_LAST_FRAG:
if (first_frag && cevent->mid == mid &&
cevent->fsn == next_fsn)
goto found;
else
first_frag = NULL;
break;
}
}
if (!pd_first)
goto out;
pd_point = sctp_sk(asoc->base.sk)->pd_point;
if (pd_point && pd_point <= pd_len) {
retval = sctp_make_reassembled_event(asoc->base.net,
&ulpq->reasm,
pd_first, pd_last);
if (retval) {
sin->fsn = next_fsn;
sin->pd_mode = 1;
}
}
goto out;
found:
retval = sctp_make_reassembled_event(asoc->base.net, &ulpq->reasm,
first_frag, pos);
if (retval)
retval->msg_flags |= MSG_EOR;
out:
return retval;
}
static struct sctp_ulpevent *sctp_intl_reasm(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sctp_ulpevent *retval = NULL;
struct sctp_stream_in *sin;
if (SCTP_DATA_NOT_FRAG == (event->msg_flags & SCTP_DATA_FRAG_MASK)) {
event->msg_flags |= MSG_EOR;
return event;
}
sctp_intl_store_reasm(ulpq, event);
sin = sctp_stream_in(&ulpq->asoc->stream, event->stream);
if (sin->pd_mode && event->mid == sin->mid &&
event->fsn == sin->fsn)
retval = sctp_intl_retrieve_partial(ulpq, event);
if (!retval)
retval = sctp_intl_retrieve_reassembled(ulpq, event);
return retval;
}
static void sctp_intl_store_ordered(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sctp_ulpevent *cevent;
struct sk_buff *pos, *loc;
pos = skb_peek_tail(&ulpq->lobby);
if (!pos) {
__skb_queue_tail(&ulpq->lobby, sctp_event2skb(event));
return;
}
cevent = (struct sctp_ulpevent *)pos->cb;
if (event->stream == cevent->stream &&
MID_lt(cevent->mid, event->mid)) {
__skb_queue_tail(&ulpq->lobby, sctp_event2skb(event));
return;
}
if (event->stream > cevent->stream) {
__skb_queue_tail(&ulpq->lobby, sctp_event2skb(event));
return;
}
loc = NULL;
skb_queue_walk(&ulpq->lobby, pos) {
cevent = (struct sctp_ulpevent *)pos->cb;
if (cevent->stream > event->stream) {
loc = pos;
break;
}
if (cevent->stream == event->stream &&
MID_lt(event->mid, cevent->mid)) {
loc = pos;
break;
}
}
if (!loc)
__skb_queue_tail(&ulpq->lobby, sctp_event2skb(event));
else
__skb_queue_before(&ulpq->lobby, loc, sctp_event2skb(event));
}
static void sctp_intl_retrieve_ordered(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sk_buff_head *event_list;
struct sctp_stream *stream;
struct sk_buff *pos, *tmp;
__u16 sid = event->stream;
stream = &ulpq->asoc->stream;
event_list = (struct sk_buff_head *)sctp_event2skb(event)->prev;
sctp_skb_for_each(pos, &ulpq->lobby, tmp) {
struct sctp_ulpevent *cevent = (struct sctp_ulpevent *)pos->cb;
if (cevent->stream > sid)
break;
if (cevent->stream < sid)
continue;
if (cevent->mid != sctp_mid_peek(stream, in, sid))
break;
sctp_mid_next(stream, in, sid);
__skb_unlink(pos, &ulpq->lobby);
__skb_queue_tail(event_list, pos);
}
}
static struct sctp_ulpevent *sctp_intl_order(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sctp_stream *stream;
__u16 sid;
stream = &ulpq->asoc->stream;
sid = event->stream;
if (event->mid != sctp_mid_peek(stream, in, sid)) {
sctp_intl_store_ordered(ulpq, event);
return NULL;
}
sctp_mid_next(stream, in, sid);
sctp_intl_retrieve_ordered(ulpq, event);
return event;
}
static int sctp_enqueue_event(struct sctp_ulpq *ulpq,
struct sk_buff_head *skb_list)
{
struct sock *sk = ulpq->asoc->base.sk;
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_ulpevent *event;
struct sk_buff *skb;
skb = __skb_peek(skb_list);
event = sctp_skb2event(skb);
if (sk->sk_shutdown & RCV_SHUTDOWN &&
(sk->sk_shutdown & SEND_SHUTDOWN ||
!sctp_ulpevent_is_notification(event)))
goto out_free;
if (!sctp_ulpevent_is_notification(event)) {
sk_mark_napi_id(sk, skb);
sk_incoming_cpu_update(sk);
}
if (!sctp_ulpevent_is_enabled(event, ulpq->asoc->subscribe))
goto out_free;
skb_queue_splice_tail_init(skb_list,
&sk->sk_receive_queue);
if (!sp->data_ready_signalled) {
sp->data_ready_signalled = 1;
sk->sk_data_ready(sk);
}
return 1;
out_free:
sctp_queue_purge_ulpevents(skb_list);
return 0;
}
static void sctp_intl_store_reasm_uo(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sctp_ulpevent *cevent;
struct sk_buff *pos;
pos = skb_peek_tail(&ulpq->reasm_uo);
if (!pos) {
__skb_queue_tail(&ulpq->reasm_uo, sctp_event2skb(event));
return;
}
cevent = sctp_skb2event(pos);
if (event->stream == cevent->stream &&
event->mid == cevent->mid &&
(cevent->msg_flags & SCTP_DATA_FIRST_FRAG ||
(!(event->msg_flags & SCTP_DATA_FIRST_FRAG) &&
event->fsn > cevent->fsn))) {
__skb_queue_tail(&ulpq->reasm_uo, sctp_event2skb(event));
return;
}
if ((event->stream == cevent->stream &&
MID_lt(cevent->mid, event->mid)) ||
event->stream > cevent->stream) {
__skb_queue_tail(&ulpq->reasm_uo, sctp_event2skb(event));
return;
}
skb_queue_walk(&ulpq->reasm_uo, pos) {
cevent = sctp_skb2event(pos);
if (event->stream < cevent->stream ||
(event->stream == cevent->stream &&
MID_lt(event->mid, cevent->mid)))
break;
if (event->stream == cevent->stream &&
event->mid == cevent->mid &&
!(cevent->msg_flags & SCTP_DATA_FIRST_FRAG) &&
(event->msg_flags & SCTP_DATA_FIRST_FRAG ||
event->fsn < cevent->fsn))
break;
}
__skb_queue_before(&ulpq->reasm_uo, pos, sctp_event2skb(event));
}
static struct sctp_ulpevent *sctp_intl_retrieve_partial_uo(
struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sk_buff *first_frag = NULL;
struct sk_buff *last_frag = NULL;
struct sctp_ulpevent *retval;
struct sctp_stream_in *sin;
struct sk_buff *pos;
__u32 next_fsn = 0;
int is_last = 0;
sin = sctp_stream_in(&ulpq->asoc->stream, event->stream);
skb_queue_walk(&ulpq->reasm_uo, pos) {
struct sctp_ulpevent *cevent = sctp_skb2event(pos);
if (cevent->stream < event->stream)
continue;
if (cevent->stream > event->stream)
break;
if (MID_lt(cevent->mid, sin->mid_uo))
continue;
if (MID_lt(sin->mid_uo, cevent->mid))
break;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
goto out;
case SCTP_DATA_MIDDLE_FRAG:
if (!first_frag) {
if (cevent->fsn == sin->fsn_uo) {
first_frag = pos;
last_frag = pos;
next_fsn = cevent->fsn + 1;
}
} else if (cevent->fsn == next_fsn) {
last_frag = pos;
next_fsn++;
} else {
goto out;
}
break;
case SCTP_DATA_LAST_FRAG:
if (!first_frag) {
if (cevent->fsn == sin->fsn_uo) {
first_frag = pos;
last_frag = pos;
next_fsn = 0;
is_last = 1;
}
} else if (cevent->fsn == next_fsn) {
last_frag = pos;
next_fsn = 0;
is_last = 1;
}
goto out;
default:
goto out;
}
}
out:
if (!first_frag)
return NULL;
retval = sctp_make_reassembled_event(ulpq->asoc->base.net,
&ulpq->reasm_uo, first_frag,
last_frag);
if (retval) {
sin->fsn_uo = next_fsn;
if (is_last) {
retval->msg_flags |= MSG_EOR;
sin->pd_mode_uo = 0;
}
}
return retval;
}
static struct sctp_ulpevent *sctp_intl_retrieve_reassembled_uo(
struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sctp_association *asoc = ulpq->asoc;
struct sk_buff *pos, *first_frag = NULL;
struct sctp_ulpevent *retval = NULL;
struct sk_buff *pd_first = NULL;
struct sk_buff *pd_last = NULL;
struct sctp_stream_in *sin;
__u32 next_fsn = 0;
__u32 pd_point = 0;
__u32 pd_len = 0;
__u32 mid = 0;
sin = sctp_stream_in(&ulpq->asoc->stream, event->stream);
skb_queue_walk(&ulpq->reasm_uo, pos) {
struct sctp_ulpevent *cevent = sctp_skb2event(pos);
if (cevent->stream < event->stream)
continue;
if (cevent->stream > event->stream)
break;
if (MID_lt(cevent->mid, event->mid))
continue;
if (MID_lt(event->mid, cevent->mid))
break;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
if (!sin->pd_mode_uo) {
sin->mid_uo = cevent->mid;
pd_first = pos;
pd_last = pos;
pd_len = pos->len;
}
first_frag = pos;
next_fsn = 0;
mid = cevent->mid;
break;
case SCTP_DATA_MIDDLE_FRAG:
if (first_frag && cevent->mid == mid &&
cevent->fsn == next_fsn) {
next_fsn++;
if (pd_first) {
pd_last = pos;
pd_len += pos->len;
}
} else {
first_frag = NULL;
}
break;
case SCTP_DATA_LAST_FRAG:
if (first_frag && cevent->mid == mid &&
cevent->fsn == next_fsn)
goto found;
else
first_frag = NULL;
break;
}
}
if (!pd_first)
goto out;
pd_point = sctp_sk(asoc->base.sk)->pd_point;
if (pd_point && pd_point <= pd_len) {
retval = sctp_make_reassembled_event(asoc->base.net,
&ulpq->reasm_uo,
pd_first, pd_last);
if (retval) {
sin->fsn_uo = next_fsn;
sin->pd_mode_uo = 1;
}
}
goto out;
found:
retval = sctp_make_reassembled_event(asoc->base.net, &ulpq->reasm_uo,
first_frag, pos);
if (retval)
retval->msg_flags |= MSG_EOR;
out:
return retval;
}
static struct sctp_ulpevent *sctp_intl_reasm_uo(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sctp_ulpevent *retval = NULL;
struct sctp_stream_in *sin;
if (SCTP_DATA_NOT_FRAG == (event->msg_flags & SCTP_DATA_FRAG_MASK)) {
event->msg_flags |= MSG_EOR;
return event;
}
sctp_intl_store_reasm_uo(ulpq, event);
sin = sctp_stream_in(&ulpq->asoc->stream, event->stream);
if (sin->pd_mode_uo && event->mid == sin->mid_uo &&
event->fsn == sin->fsn_uo)
retval = sctp_intl_retrieve_partial_uo(ulpq, event);
if (!retval)
retval = sctp_intl_retrieve_reassembled_uo(ulpq, event);
return retval;
}
static struct sctp_ulpevent *sctp_intl_retrieve_first_uo(struct sctp_ulpq *ulpq)
{
struct sctp_stream_in *csin, *sin = NULL;
struct sk_buff *first_frag = NULL;
struct sk_buff *last_frag = NULL;
struct sctp_ulpevent *retval;
struct sk_buff *pos;
__u32 next_fsn = 0;
__u16 sid = 0;
skb_queue_walk(&ulpq->reasm_uo, pos) {
struct sctp_ulpevent *cevent = sctp_skb2event(pos);
csin = sctp_stream_in(&ulpq->asoc->stream, cevent->stream);
if (csin->pd_mode_uo)
continue;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
if (first_frag)
goto out;
first_frag = pos;
last_frag = pos;
next_fsn = 0;
sin = csin;
sid = cevent->stream;
sin->mid_uo = cevent->mid;
break;
case SCTP_DATA_MIDDLE_FRAG:
if (!first_frag)
break;
if (cevent->stream == sid &&
cevent->mid == sin->mid_uo &&
cevent->fsn == next_fsn) {
next_fsn++;
last_frag = pos;
} else {
goto out;
}
break;
case SCTP_DATA_LAST_FRAG:
if (first_frag)
goto out;
break;
default:
break;
}
}
if (!first_frag)
return NULL;
out:
retval = sctp_make_reassembled_event(ulpq->asoc->base.net,
&ulpq->reasm_uo, first_frag,
last_frag);
if (retval) {
sin->fsn_uo = next_fsn;
sin->pd_mode_uo = 1;
}
return retval;
}
static int sctp_ulpevent_idata(struct sctp_ulpq *ulpq,
struct sctp_chunk *chunk, gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sk_buff_head temp;
int event_eor = 0;
event = sctp_ulpevent_make_rcvmsg(chunk->asoc, chunk, gfp);
if (!event)
return -ENOMEM;
event->mid = ntohl(chunk->subh.idata_hdr->mid);
if (event->msg_flags & SCTP_DATA_FIRST_FRAG)
event->ppid = chunk->subh.idata_hdr->ppid;
else
event->fsn = ntohl(chunk->subh.idata_hdr->fsn);
if (!(event->msg_flags & SCTP_DATA_UNORDERED)) {
event = sctp_intl_reasm(ulpq, event);
if (event) {
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
if (event->msg_flags & MSG_EOR)
event = sctp_intl_order(ulpq, event);
}
} else {
event = sctp_intl_reasm_uo(ulpq, event);
if (event) {
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
}
}
if (event) {
event_eor = (event->msg_flags & MSG_EOR) ? 1 : 0;
sctp_enqueue_event(ulpq, &temp);
}
return event_eor;
}
static struct sctp_ulpevent *sctp_intl_retrieve_first(struct sctp_ulpq *ulpq)
{
struct sctp_stream_in *csin, *sin = NULL;
struct sk_buff *first_frag = NULL;
struct sk_buff *last_frag = NULL;
struct sctp_ulpevent *retval;
struct sk_buff *pos;
__u32 next_fsn = 0;
__u16 sid = 0;
skb_queue_walk(&ulpq->reasm, pos) {
struct sctp_ulpevent *cevent = sctp_skb2event(pos);
csin = sctp_stream_in(&ulpq->asoc->stream, cevent->stream);
if (csin->pd_mode)
continue;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
if (first_frag)
goto out;
if (cevent->mid == csin->mid) {
first_frag = pos;
last_frag = pos;
next_fsn = 0;
sin = csin;
sid = cevent->stream;
}
break;
case SCTP_DATA_MIDDLE_FRAG:
if (!first_frag)
break;
if (cevent->stream == sid &&
cevent->mid == sin->mid &&
cevent->fsn == next_fsn) {
next_fsn++;
last_frag = pos;
} else {
goto out;
}
break;
case SCTP_DATA_LAST_FRAG:
if (first_frag)
goto out;
break;
default:
break;
}
}
if (!first_frag)
return NULL;
out:
retval = sctp_make_reassembled_event(ulpq->asoc->base.net,
&ulpq->reasm, first_frag,
last_frag);
if (retval) {
sin->fsn = next_fsn;
sin->pd_mode = 1;
}
return retval;
}
static void sctp_intl_start_pd(struct sctp_ulpq *ulpq, gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sk_buff_head temp;
if (!skb_queue_empty(&ulpq->reasm)) {
do {
event = sctp_intl_retrieve_first(ulpq);
if (event) {
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
sctp_enqueue_event(ulpq, &temp);
}
} while (event);
}
if (!skb_queue_empty(&ulpq->reasm_uo)) {
do {
event = sctp_intl_retrieve_first_uo(ulpq);
if (event) {
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
sctp_enqueue_event(ulpq, &temp);
}
} while (event);
}
}
static void sctp_renege_events(struct sctp_ulpq *ulpq, struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sctp_association *asoc = ulpq->asoc;
__u32 freed = 0;
__u16 needed;
needed = ntohs(chunk->chunk_hdr->length) -
sizeof(struct sctp_idata_chunk);
if (skb_queue_empty(&asoc->base.sk->sk_receive_queue)) {
freed = sctp_ulpq_renege_list(ulpq, &ulpq->lobby, needed);
if (freed < needed)
freed += sctp_ulpq_renege_list(ulpq, &ulpq->reasm,
needed);
if (freed < needed)
freed += sctp_ulpq_renege_list(ulpq, &ulpq->reasm_uo,
needed);
}
if (freed >= needed && sctp_ulpevent_idata(ulpq, chunk, gfp) <= 0)
sctp_intl_start_pd(ulpq, gfp);
}
static void sctp_intl_stream_abort_pd(struct sctp_ulpq *ulpq, __u16 sid,
__u32 mid, __u16 flags, gfp_t gfp)
{
struct sock *sk = ulpq->asoc->base.sk;
struct sctp_ulpevent *ev = NULL;
if (!sctp_ulpevent_type_enabled(ulpq->asoc->subscribe,
SCTP_PARTIAL_DELIVERY_EVENT))
return;
ev = sctp_ulpevent_make_pdapi(ulpq->asoc, SCTP_PARTIAL_DELIVERY_ABORTED,
sid, mid, flags, gfp);
if (ev) {
struct sctp_sock *sp = sctp_sk(sk);
__skb_queue_tail(&sk->sk_receive_queue, sctp_event2skb(ev));
if (!sp->data_ready_signalled) {
sp->data_ready_signalled = 1;
sk->sk_data_ready(sk);
}
}
}
static void sctp_intl_reap_ordered(struct sctp_ulpq *ulpq, __u16 sid)
{
struct sctp_stream *stream = &ulpq->asoc->stream;
struct sctp_ulpevent *cevent, *event = NULL;
struct sk_buff_head *lobby = &ulpq->lobby;
struct sk_buff *pos, *tmp;
struct sk_buff_head temp;
__u16 csid;
__u32 cmid;
skb_queue_head_init(&temp);
sctp_skb_for_each(pos, lobby, tmp) {
cevent = (struct sctp_ulpevent *)pos->cb;
csid = cevent->stream;
cmid = cevent->mid;
if (csid > sid)
break;
if (csid < sid)
continue;
if (!MID_lt(cmid, sctp_mid_peek(stream, in, csid)))
break;
__skb_unlink(pos, lobby);
if (!event)
event = sctp_skb2event(pos);
__skb_queue_tail(&temp, pos);
}
if (!event && pos != (struct sk_buff *)lobby) {
cevent = (struct sctp_ulpevent *)pos->cb;
csid = cevent->stream;
cmid = cevent->mid;
if (csid == sid && cmid == sctp_mid_peek(stream, in, csid)) {
sctp_mid_next(stream, in, csid);
__skb_unlink(pos, lobby);
__skb_queue_tail(&temp, pos);
event = sctp_skb2event(pos);
}
}
if (event) {
sctp_intl_retrieve_ordered(ulpq, event);
sctp_enqueue_event(ulpq, &temp);
}
}
static void sctp_intl_abort_pd(struct sctp_ulpq *ulpq, gfp_t gfp)
{
struct sctp_stream *stream = &ulpq->asoc->stream;
__u16 sid;
for (sid = 0; sid < stream->incnt; sid++) {
struct sctp_stream_in *sin = SCTP_SI(stream, sid);
__u32 mid;
if (sin->pd_mode_uo) {
sin->pd_mode_uo = 0;
mid = sin->mid_uo;
sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x1, gfp);
}
if (sin->pd_mode) {
sin->pd_mode = 0;
mid = sin->mid;
sctp_intl_stream_abort_pd(ulpq, sid, mid, 0, gfp);
sctp_mid_skip(stream, in, sid, mid);
sctp_intl_reap_ordered(ulpq, sid);
}
}
/* intl abort pd happens only when all data needs to be cleaned */
sctp_ulpq_flush(ulpq);
}
static inline int sctp_get_skip_pos(struct sctp_ifwdtsn_skip *skiplist,
int nskips, __be16 stream, __u8 flags)
{
int i;
for (i = 0; i < nskips; i++)
if (skiplist[i].stream == stream &&
skiplist[i].flags == flags)
return i;
return i;
}
#define SCTP_FTSN_U_BIT 0x1
static void sctp_generate_iftsn(struct sctp_outq *q, __u32 ctsn)
{
struct sctp_ifwdtsn_skip ftsn_skip_arr[10];
struct sctp_association *asoc = q->asoc;
struct sctp_chunk *ftsn_chunk = NULL;
struct list_head *lchunk, *temp;
int nskips = 0, skip_pos;
struct sctp_chunk *chunk;
__u32 tsn;
if (!asoc->peer.prsctp_capable)
return;
if (TSN_lt(asoc->adv_peer_ack_point, ctsn))
asoc->adv_peer_ack_point = ctsn;
list_for_each_safe(lchunk, temp, &q->abandoned) {
chunk = list_entry(lchunk, struct sctp_chunk, transmitted_list);
tsn = ntohl(chunk->subh.data_hdr->tsn);
if (TSN_lte(tsn, ctsn)) {
list_del_init(lchunk);
sctp_chunk_free(chunk);
} else if (TSN_lte(tsn, asoc->adv_peer_ack_point + 1)) {
__be16 sid = chunk->subh.idata_hdr->stream;
__be32 mid = chunk->subh.idata_hdr->mid;
__u8 flags = 0;
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED)
flags |= SCTP_FTSN_U_BIT;
asoc->adv_peer_ack_point = tsn;
skip_pos = sctp_get_skip_pos(&ftsn_skip_arr[0], nskips,
sid, flags);
ftsn_skip_arr[skip_pos].stream = sid;
ftsn_skip_arr[skip_pos].reserved = 0;
ftsn_skip_arr[skip_pos].flags = flags;
ftsn_skip_arr[skip_pos].mid = mid;
if (skip_pos == nskips)
nskips++;
if (nskips == 10)
break;
} else {
break;
}
}
if (asoc->adv_peer_ack_point > ctsn)
ftsn_chunk = sctp_make_ifwdtsn(asoc, asoc->adv_peer_ack_point,
nskips, &ftsn_skip_arr[0]);
if (ftsn_chunk) {
list_add_tail(&ftsn_chunk->list, &q->control_chunk_list);
SCTP_INC_STATS(asoc->base.net, SCTP_MIB_OUTCTRLCHUNKS);
}
}
#define _sctp_walk_ifwdtsn(pos, chunk, end) \
for (pos = (void *)(chunk->subh.ifwdtsn_hdr + 1); \
(void *)pos <= (void *)(chunk->subh.ifwdtsn_hdr + 1) + (end) - \
sizeof(struct sctp_ifwdtsn_skip); pos++)
#define sctp_walk_ifwdtsn(pos, ch) \
_sctp_walk_ifwdtsn((pos), (ch), ntohs((ch)->chunk_hdr->length) - \
sizeof(struct sctp_ifwdtsn_chunk))
static bool sctp_validate_fwdtsn(struct sctp_chunk *chunk)
{
struct sctp_fwdtsn_skip *skip;
__u16 incnt;
if (chunk->chunk_hdr->type != SCTP_CID_FWD_TSN)
return false;
incnt = chunk->asoc->stream.incnt;
sctp_walk_fwdtsn(skip, chunk)
if (ntohs(skip->stream) >= incnt)
return false;
return true;
}
static bool sctp_validate_iftsn(struct sctp_chunk *chunk)
{
struct sctp_ifwdtsn_skip *skip;
__u16 incnt;
if (chunk->chunk_hdr->type != SCTP_CID_I_FWD_TSN)
return false;
incnt = chunk->asoc->stream.incnt;
sctp_walk_ifwdtsn(skip, chunk)
if (ntohs(skip->stream) >= incnt)
return false;
return true;
}
static void sctp_report_fwdtsn(struct sctp_ulpq *ulpq, __u32 ftsn)
{
/* Move the Cumulattive TSN Ack ahead. */
sctp_tsnmap_skip(&ulpq->asoc->peer.tsn_map, ftsn);
/* purge the fragmentation queue */
sctp_ulpq_reasm_flushtsn(ulpq, ftsn);
/* Abort any in progress partial delivery. */
sctp_ulpq_abort_pd(ulpq, GFP_ATOMIC);
}
static void sctp_intl_reasm_flushtsn(struct sctp_ulpq *ulpq, __u32 ftsn)
{
struct sk_buff *pos, *tmp;
skb_queue_walk_safe(&ulpq->reasm, pos, tmp) {
struct sctp_ulpevent *event = sctp_skb2event(pos);
__u32 tsn = event->tsn;
if (TSN_lte(tsn, ftsn)) {
__skb_unlink(pos, &ulpq->reasm);
sctp_ulpevent_free(event);
}
}
skb_queue_walk_safe(&ulpq->reasm_uo, pos, tmp) {
struct sctp_ulpevent *event = sctp_skb2event(pos);
__u32 tsn = event->tsn;
if (TSN_lte(tsn, ftsn)) {
__skb_unlink(pos, &ulpq->reasm_uo);
sctp_ulpevent_free(event);
}
}
}
static void sctp_report_iftsn(struct sctp_ulpq *ulpq, __u32 ftsn)
{
/* Move the Cumulattive TSN Ack ahead. */
sctp_tsnmap_skip(&ulpq->asoc->peer.tsn_map, ftsn);
/* purge the fragmentation queue */
sctp_intl_reasm_flushtsn(ulpq, ftsn);
/* abort only when it's for all data */
if (ftsn == sctp_tsnmap_get_max_tsn_seen(&ulpq->asoc->peer.tsn_map))
sctp_intl_abort_pd(ulpq, GFP_ATOMIC);
}
static void sctp_handle_fwdtsn(struct sctp_ulpq *ulpq, struct sctp_chunk *chunk)
{
struct sctp_fwdtsn_skip *skip;
/* Walk through all the skipped SSNs */
sctp_walk_fwdtsn(skip, chunk)
sctp_ulpq_skip(ulpq, ntohs(skip->stream), ntohs(skip->ssn));
}
static void sctp_intl_skip(struct sctp_ulpq *ulpq, __u16 sid, __u32 mid,
__u8 flags)
{
struct sctp_stream_in *sin = sctp_stream_in(&ulpq->asoc->stream, sid);
struct sctp_stream *stream = &ulpq->asoc->stream;
if (flags & SCTP_FTSN_U_BIT) {
if (sin->pd_mode_uo && MID_lt(sin->mid_uo, mid)) {
sin->pd_mode_uo = 0;
sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x1,
GFP_ATOMIC);
}
return;
}
if (MID_lt(mid, sctp_mid_peek(stream, in, sid)))
return;
if (sin->pd_mode) {
sin->pd_mode = 0;
sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x0, GFP_ATOMIC);
}
sctp_mid_skip(stream, in, sid, mid);
sctp_intl_reap_ordered(ulpq, sid);
}
static void sctp_handle_iftsn(struct sctp_ulpq *ulpq, struct sctp_chunk *chunk)
{
struct sctp_ifwdtsn_skip *skip;
/* Walk through all the skipped MIDs and abort stream pd if possible */
sctp_walk_ifwdtsn(skip, chunk)
sctp_intl_skip(ulpq, ntohs(skip->stream),
ntohl(skip->mid), skip->flags);
}
static int do_ulpq_tail_event(struct sctp_ulpq *ulpq, struct sctp_ulpevent *event)
{
struct sk_buff_head temp;
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
return sctp_ulpq_tail_event(ulpq, &temp);
}
static struct sctp_stream_interleave sctp_stream_interleave_0 = {
.data_chunk_len = sizeof(struct sctp_data_chunk),
.ftsn_chunk_len = sizeof(struct sctp_fwdtsn_chunk),
/* DATA process functions */
.make_datafrag = sctp_make_datafrag_empty,
.assign_number = sctp_chunk_assign_ssn,
.validate_data = sctp_validate_data,
.ulpevent_data = sctp_ulpq_tail_data,
.enqueue_event = do_ulpq_tail_event,
.renege_events = sctp_ulpq_renege,
.start_pd = sctp_ulpq_partial_delivery,
.abort_pd = sctp_ulpq_abort_pd,
/* FORWARD-TSN process functions */
.generate_ftsn = sctp_generate_fwdtsn,
.validate_ftsn = sctp_validate_fwdtsn,
.report_ftsn = sctp_report_fwdtsn,
.handle_ftsn = sctp_handle_fwdtsn,
};
static int do_sctp_enqueue_event(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sk_buff_head temp;
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
return sctp_enqueue_event(ulpq, &temp);
}
static struct sctp_stream_interleave sctp_stream_interleave_1 = {
.data_chunk_len = sizeof(struct sctp_idata_chunk),
.ftsn_chunk_len = sizeof(struct sctp_ifwdtsn_chunk),
/* I-DATA process functions */
.make_datafrag = sctp_make_idatafrag_empty,
.assign_number = sctp_chunk_assign_mid,
.validate_data = sctp_validate_idata,
.ulpevent_data = sctp_ulpevent_idata,
.enqueue_event = do_sctp_enqueue_event,
.renege_events = sctp_renege_events,
.start_pd = sctp_intl_start_pd,
.abort_pd = sctp_intl_abort_pd,
/* I-FORWARD-TSN process functions */
.generate_ftsn = sctp_generate_iftsn,
.validate_ftsn = sctp_validate_iftsn,
.report_ftsn = sctp_report_iftsn,
.handle_ftsn = sctp_handle_iftsn,
};
void sctp_stream_interleave_init(struct sctp_stream *stream)
{
struct sctp_association *asoc;
asoc = container_of(stream, struct sctp_association, stream);
stream->si = asoc->peer.intl_capable ? &sctp_stream_interleave_1
: &sctp_stream_interleave_0;
}
| linux-master | net/sctp/stream_interleave.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
*
* This file is part of the SCTP kernel implementation
*
* This file converts numerical ID value to alphabetical names for SCTP
* terms such as chunk type, parameter time, event type, etc.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Xingang Guo <[email protected]>
* Jon Grimm <[email protected]>
* Daisy Chang <[email protected]>
* Sridhar Samudrala <[email protected]>
*/
#include <net/sctp/sctp.h>
/* These are printable forms of Chunk ID's from section 3.1. */
static const char *const sctp_cid_tbl[SCTP_NUM_BASE_CHUNK_TYPES] = {
"DATA",
"INIT",
"INIT_ACK",
"SACK",
"HEARTBEAT",
"HEARTBEAT_ACK",
"ABORT",
"SHUTDOWN",
"SHUTDOWN_ACK",
"ERROR",
"COOKIE_ECHO",
"COOKIE_ACK",
"ECN_ECNE",
"ECN_CWR",
"SHUTDOWN_COMPLETE",
};
/* Lookup "chunk type" debug name. */
const char *sctp_cname(const union sctp_subtype cid)
{
if (cid.chunk <= SCTP_CID_BASE_MAX)
return sctp_cid_tbl[cid.chunk];
switch (cid.chunk) {
case SCTP_CID_ASCONF:
return "ASCONF";
case SCTP_CID_ASCONF_ACK:
return "ASCONF_ACK";
case SCTP_CID_FWD_TSN:
return "FWD_TSN";
case SCTP_CID_AUTH:
return "AUTH";
case SCTP_CID_RECONF:
return "RECONF";
case SCTP_CID_I_DATA:
return "I_DATA";
case SCTP_CID_I_FWD_TSN:
return "I_FWD_TSN";
default:
break;
}
return "unknown chunk";
}
/* These are printable forms of the states. */
const char *const sctp_state_tbl[SCTP_STATE_NUM_STATES] = {
"STATE_CLOSED",
"STATE_COOKIE_WAIT",
"STATE_COOKIE_ECHOED",
"STATE_ESTABLISHED",
"STATE_SHUTDOWN_PENDING",
"STATE_SHUTDOWN_SENT",
"STATE_SHUTDOWN_RECEIVED",
"STATE_SHUTDOWN_ACK_SENT",
};
/* Events that could change the state of an association. */
const char *const sctp_evttype_tbl[] = {
"EVENT_T_unknown",
"EVENT_T_CHUNK",
"EVENT_T_TIMEOUT",
"EVENT_T_OTHER",
"EVENT_T_PRIMITIVE"
};
/* Return value of a state function */
const char *const sctp_status_tbl[] = {
"DISPOSITION_DISCARD",
"DISPOSITION_CONSUME",
"DISPOSITION_NOMEM",
"DISPOSITION_DELETE_TCB",
"DISPOSITION_ABORT",
"DISPOSITION_VIOLATION",
"DISPOSITION_NOT_IMPL",
"DISPOSITION_ERROR",
"DISPOSITION_BUG"
};
/* Printable forms of primitives */
static const char *const sctp_primitive_tbl[SCTP_NUM_PRIMITIVE_TYPES] = {
"PRIMITIVE_ASSOCIATE",
"PRIMITIVE_SHUTDOWN",
"PRIMITIVE_ABORT",
"PRIMITIVE_SEND",
"PRIMITIVE_REQUESTHEARTBEAT",
"PRIMITIVE_ASCONF",
};
/* Lookup primitive debug name. */
const char *sctp_pname(const union sctp_subtype id)
{
if (id.primitive <= SCTP_EVENT_PRIMITIVE_MAX)
return sctp_primitive_tbl[id.primitive];
return "unknown_primitive";
}
static const char *const sctp_other_tbl[] = {
"NO_PENDING_TSN",
"ICMP_PROTO_UNREACH",
};
/* Lookup "other" debug name. */
const char *sctp_oname(const union sctp_subtype id)
{
if (id.other <= SCTP_EVENT_OTHER_MAX)
return sctp_other_tbl[id.other];
return "unknown 'other' event";
}
static const char *const sctp_timer_tbl[] = {
"TIMEOUT_NONE",
"TIMEOUT_T1_COOKIE",
"TIMEOUT_T1_INIT",
"TIMEOUT_T2_SHUTDOWN",
"TIMEOUT_T3_RTX",
"TIMEOUT_T4_RTO",
"TIMEOUT_T5_SHUTDOWN_GUARD",
"TIMEOUT_HEARTBEAT",
"TIMEOUT_RECONF",
"TIMEOUT_PROBE",
"TIMEOUT_SACK",
"TIMEOUT_AUTOCLOSE",
};
/* Lookup timer debug name. */
const char *sctp_tname(const union sctp_subtype id)
{
BUILD_BUG_ON(SCTP_EVENT_TIMEOUT_MAX + 1 != ARRAY_SIZE(sctp_timer_tbl));
if (id.timeout < ARRAY_SIZE(sctp_timer_tbl))
return sctp_timer_tbl[id.timeout];
return "unknown_timer";
}
| linux-master | net/sctp/debug.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2003 International Business Machines, Corp.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 Nokia, Inc.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This file is part of the SCTP kernel implementation
*
* These functions handle all input from the IP layer into SCTP.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Xingang Guo <[email protected]>
* Jon Grimm <[email protected]>
* Hui Huang <[email protected]>
* Daisy Chang <[email protected]>
* Sridhar Samudrala <[email protected]>
* Ardelle Fan <[email protected]>
*/
#include <linux/types.h>
#include <linux/list.h> /* For struct list_head */
#include <linux/socket.h>
#include <linux/ip.h>
#include <linux/time.h> /* For struct timeval */
#include <linux/slab.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/snmp.h>
#include <net/sock.h>
#include <net/xfrm.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/checksum.h>
#include <net/net_namespace.h>
#include <linux/rhashtable.h>
#include <net/sock_reuseport.h>
/* Forward declarations for internal helpers. */
static int sctp_rcv_ootb(struct sk_buff *);
static struct sctp_association *__sctp_rcv_lookup(struct net *net,
struct sk_buff *skb,
const union sctp_addr *paddr,
const union sctp_addr *laddr,
struct sctp_transport **transportp,
int dif, int sdif);
static struct sctp_endpoint *__sctp_rcv_lookup_endpoint(
struct net *net, struct sk_buff *skb,
const union sctp_addr *laddr,
const union sctp_addr *daddr,
int dif, int sdif);
static struct sctp_association *__sctp_lookup_association(
struct net *net,
const union sctp_addr *local,
const union sctp_addr *peer,
struct sctp_transport **pt,
int dif, int sdif);
static int sctp_add_backlog(struct sock *sk, struct sk_buff *skb);
/* Calculate the SCTP checksum of an SCTP packet. */
static inline int sctp_rcv_checksum(struct net *net, struct sk_buff *skb)
{
struct sctphdr *sh = sctp_hdr(skb);
__le32 cmp = sh->checksum;
__le32 val = sctp_compute_cksum(skb, 0);
if (val != cmp) {
/* CRC failure, dump it. */
__SCTP_INC_STATS(net, SCTP_MIB_CHECKSUMERRORS);
return -1;
}
return 0;
}
/*
* This is the routine which IP calls when receiving an SCTP packet.
*/
int sctp_rcv(struct sk_buff *skb)
{
struct sock *sk;
struct sctp_association *asoc;
struct sctp_endpoint *ep = NULL;
struct sctp_ep_common *rcvr;
struct sctp_transport *transport = NULL;
struct sctp_chunk *chunk;
union sctp_addr src;
union sctp_addr dest;
int family;
struct sctp_af *af;
struct net *net = dev_net(skb->dev);
bool is_gso = skb_is_gso(skb) && skb_is_gso_sctp(skb);
int dif, sdif;
if (skb->pkt_type != PACKET_HOST)
goto discard_it;
__SCTP_INC_STATS(net, SCTP_MIB_INSCTPPACKS);
/* If packet is too small to contain a single chunk, let's not
* waste time on it anymore.
*/
if (skb->len < sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr) +
skb_transport_offset(skb))
goto discard_it;
/* If the packet is fragmented and we need to do crc checking,
* it's better to just linearize it otherwise crc computing
* takes longer.
*/
if ((!is_gso && skb_linearize(skb)) ||
!pskb_may_pull(skb, sizeof(struct sctphdr)))
goto discard_it;
/* Pull up the IP header. */
__skb_pull(skb, skb_transport_offset(skb));
skb->csum_valid = 0; /* Previous value not applicable */
if (skb_csum_unnecessary(skb))
__skb_decr_checksum_unnecessary(skb);
else if (!sctp_checksum_disable &&
!is_gso &&
sctp_rcv_checksum(net, skb) < 0)
goto discard_it;
skb->csum_valid = 1;
__skb_pull(skb, sizeof(struct sctphdr));
family = ipver2af(ip_hdr(skb)->version);
af = sctp_get_af_specific(family);
if (unlikely(!af))
goto discard_it;
SCTP_INPUT_CB(skb)->af = af;
/* Initialize local addresses for lookups. */
af->from_skb(&src, skb, 1);
af->from_skb(&dest, skb, 0);
dif = af->skb_iif(skb);
sdif = af->skb_sdif(skb);
/* If the packet is to or from a non-unicast address,
* silently discard the packet.
*
* This is not clearly defined in the RFC except in section
* 8.4 - OOTB handling. However, based on the book "Stream Control
* Transmission Protocol" 2.1, "It is important to note that the
* IP address of an SCTP transport address must be a routable
* unicast address. In other words, IP multicast addresses and
* IP broadcast addresses cannot be used in an SCTP transport
* address."
*/
if (!af->addr_valid(&src, NULL, skb) ||
!af->addr_valid(&dest, NULL, skb))
goto discard_it;
asoc = __sctp_rcv_lookup(net, skb, &src, &dest, &transport, dif, sdif);
if (!asoc)
ep = __sctp_rcv_lookup_endpoint(net, skb, &dest, &src, dif, sdif);
/* Retrieve the common input handling substructure. */
rcvr = asoc ? &asoc->base : &ep->base;
sk = rcvr->sk;
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets.
* An SCTP packet is called an "out of the blue" (OOTB)
* packet if it is correctly formed, i.e., passed the
* receiver's checksum check, but the receiver is not
* able to identify the association to which this
* packet belongs.
*/
if (!asoc) {
if (sctp_rcv_ootb(skb)) {
__SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
goto discard_release;
}
}
if (!xfrm_policy_check(sk, XFRM_POLICY_IN, skb, family))
goto discard_release;
nf_reset_ct(skb);
if (sk_filter(sk, skb))
goto discard_release;
/* Create an SCTP packet structure. */
chunk = sctp_chunkify(skb, asoc, sk, GFP_ATOMIC);
if (!chunk)
goto discard_release;
SCTP_INPUT_CB(skb)->chunk = chunk;
/* Remember what endpoint is to handle this packet. */
chunk->rcvr = rcvr;
/* Remember the SCTP header. */
chunk->sctp_hdr = sctp_hdr(skb);
/* Set the source and destination addresses of the incoming chunk. */
sctp_init_addrs(chunk, &src, &dest);
/* Remember where we came from. */
chunk->transport = transport;
/* Acquire access to the sock lock. Note: We are safe from other
* bottom halves on this lock, but a user may be in the lock too,
* so check if it is busy.
*/
bh_lock_sock(sk);
if (sk != rcvr->sk) {
/* Our cached sk is different from the rcvr->sk. This is
* because migrate()/accept() may have moved the association
* to a new socket and released all the sockets. So now we
* are holding a lock on the old socket while the user may
* be doing something with the new socket. Switch our veiw
* of the current sk.
*/
bh_unlock_sock(sk);
sk = rcvr->sk;
bh_lock_sock(sk);
}
if (sock_owned_by_user(sk) || !sctp_newsk_ready(sk)) {
if (sctp_add_backlog(sk, skb)) {
bh_unlock_sock(sk);
sctp_chunk_free(chunk);
skb = NULL; /* sctp_chunk_free already freed the skb */
goto discard_release;
}
__SCTP_INC_STATS(net, SCTP_MIB_IN_PKT_BACKLOG);
} else {
__SCTP_INC_STATS(net, SCTP_MIB_IN_PKT_SOFTIRQ);
sctp_inq_push(&chunk->rcvr->inqueue, chunk);
}
bh_unlock_sock(sk);
/* Release the asoc/ep ref we took in the lookup calls. */
if (transport)
sctp_transport_put(transport);
else
sctp_endpoint_put(ep);
return 0;
discard_it:
__SCTP_INC_STATS(net, SCTP_MIB_IN_PKT_DISCARDS);
kfree_skb(skb);
return 0;
discard_release:
/* Release the asoc/ep ref we took in the lookup calls. */
if (transport)
sctp_transport_put(transport);
else
sctp_endpoint_put(ep);
goto discard_it;
}
/* Process the backlog queue of the socket. Every skb on
* the backlog holds a ref on an association or endpoint.
* We hold this ref throughout the state machine to make
* sure that the structure we need is still around.
*/
int sctp_backlog_rcv(struct sock *sk, struct sk_buff *skb)
{
struct sctp_chunk *chunk = SCTP_INPUT_CB(skb)->chunk;
struct sctp_inq *inqueue = &chunk->rcvr->inqueue;
struct sctp_transport *t = chunk->transport;
struct sctp_ep_common *rcvr = NULL;
int backloged = 0;
rcvr = chunk->rcvr;
/* If the rcvr is dead then the association or endpoint
* has been deleted and we can safely drop the chunk
* and refs that we are holding.
*/
if (rcvr->dead) {
sctp_chunk_free(chunk);
goto done;
}
if (unlikely(rcvr->sk != sk)) {
/* In this case, the association moved from one socket to
* another. We are currently sitting on the backlog of the
* old socket, so we need to move.
* However, since we are here in the process context we
* need to take make sure that the user doesn't own
* the new socket when we process the packet.
* If the new socket is user-owned, queue the chunk to the
* backlog of the new socket without dropping any refs.
* Otherwise, we can safely push the chunk on the inqueue.
*/
sk = rcvr->sk;
local_bh_disable();
bh_lock_sock(sk);
if (sock_owned_by_user(sk) || !sctp_newsk_ready(sk)) {
if (sk_add_backlog(sk, skb, READ_ONCE(sk->sk_rcvbuf)))
sctp_chunk_free(chunk);
else
backloged = 1;
} else
sctp_inq_push(inqueue, chunk);
bh_unlock_sock(sk);
local_bh_enable();
/* If the chunk was backloged again, don't drop refs */
if (backloged)
return 0;
} else {
if (!sctp_newsk_ready(sk)) {
if (!sk_add_backlog(sk, skb, READ_ONCE(sk->sk_rcvbuf)))
return 0;
sctp_chunk_free(chunk);
} else {
sctp_inq_push(inqueue, chunk);
}
}
done:
/* Release the refs we took in sctp_add_backlog */
if (SCTP_EP_TYPE_ASSOCIATION == rcvr->type)
sctp_transport_put(t);
else if (SCTP_EP_TYPE_SOCKET == rcvr->type)
sctp_endpoint_put(sctp_ep(rcvr));
else
BUG();
return 0;
}
static int sctp_add_backlog(struct sock *sk, struct sk_buff *skb)
{
struct sctp_chunk *chunk = SCTP_INPUT_CB(skb)->chunk;
struct sctp_transport *t = chunk->transport;
struct sctp_ep_common *rcvr = chunk->rcvr;
int ret;
ret = sk_add_backlog(sk, skb, READ_ONCE(sk->sk_rcvbuf));
if (!ret) {
/* Hold the assoc/ep while hanging on the backlog queue.
* This way, we know structures we need will not disappear
* from us
*/
if (SCTP_EP_TYPE_ASSOCIATION == rcvr->type)
sctp_transport_hold(t);
else if (SCTP_EP_TYPE_SOCKET == rcvr->type)
sctp_endpoint_hold(sctp_ep(rcvr));
else
BUG();
}
return ret;
}
/* Handle icmp frag needed error. */
void sctp_icmp_frag_needed(struct sock *sk, struct sctp_association *asoc,
struct sctp_transport *t, __u32 pmtu)
{
if (!t ||
(t->pathmtu <= pmtu &&
t->pl.probe_size + sctp_transport_pl_hlen(t) <= pmtu))
return;
if (sock_owned_by_user(sk)) {
atomic_set(&t->mtu_info, pmtu);
asoc->pmtu_pending = 1;
t->pmtu_pending = 1;
return;
}
if (!(t->param_flags & SPP_PMTUD_ENABLE))
/* We can't allow retransmitting in such case, as the
* retransmission would be sized just as before, and thus we
* would get another icmp, and retransmit again.
*/
return;
/* Update transports view of the MTU. Return if no update was needed.
* If an update wasn't needed/possible, it also doesn't make sense to
* try to retransmit now.
*/
if (!sctp_transport_update_pmtu(t, pmtu))
return;
/* Update association pmtu. */
sctp_assoc_sync_pmtu(asoc);
/* Retransmit with the new pmtu setting. */
sctp_retransmit(&asoc->outqueue, t, SCTP_RTXR_PMTUD);
}
void sctp_icmp_redirect(struct sock *sk, struct sctp_transport *t,
struct sk_buff *skb)
{
struct dst_entry *dst;
if (sock_owned_by_user(sk) || !t)
return;
dst = sctp_transport_dst_check(t);
if (dst)
dst->ops->redirect(dst, sk, skb);
}
/*
* SCTP Implementer's Guide, 2.37 ICMP handling procedures
*
* ICMP8) If the ICMP code is a "Unrecognized next header type encountered"
* or a "Protocol Unreachable" treat this message as an abort
* with the T bit set.
*
* This function sends an event to the state machine, which will abort the
* association.
*
*/
void sctp_icmp_proto_unreachable(struct sock *sk,
struct sctp_association *asoc,
struct sctp_transport *t)
{
if (sock_owned_by_user(sk)) {
if (timer_pending(&t->proto_unreach_timer))
return;
else {
if (!mod_timer(&t->proto_unreach_timer,
jiffies + (HZ/20)))
sctp_transport_hold(t);
}
} else {
struct net *net = sock_net(sk);
pr_debug("%s: unrecognized next header type "
"encountered!\n", __func__);
if (del_timer(&t->proto_unreach_timer))
sctp_transport_put(t);
sctp_do_sm(net, SCTP_EVENT_T_OTHER,
SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH),
asoc->state, asoc->ep, asoc, t,
GFP_ATOMIC);
}
}
/* Common lookup code for icmp/icmpv6 error handler. */
struct sock *sctp_err_lookup(struct net *net, int family, struct sk_buff *skb,
struct sctphdr *sctphdr,
struct sctp_association **app,
struct sctp_transport **tpp)
{
struct sctp_init_chunk *chunkhdr, _chunkhdr;
union sctp_addr saddr;
union sctp_addr daddr;
struct sctp_af *af;
struct sock *sk = NULL;
struct sctp_association *asoc;
struct sctp_transport *transport = NULL;
__u32 vtag = ntohl(sctphdr->vtag);
int sdif = inet_sdif(skb);
int dif = inet_iif(skb);
*app = NULL; *tpp = NULL;
af = sctp_get_af_specific(family);
if (unlikely(!af)) {
return NULL;
}
/* Initialize local addresses for lookups. */
af->from_skb(&saddr, skb, 1);
af->from_skb(&daddr, skb, 0);
/* Look for an association that matches the incoming ICMP error
* packet.
*/
asoc = __sctp_lookup_association(net, &saddr, &daddr, &transport, dif, sdif);
if (!asoc)
return NULL;
sk = asoc->base.sk;
/* RFC 4960, Appendix C. ICMP Handling
*
* ICMP6) An implementation MUST validate that the Verification Tag
* contained in the ICMP message matches the Verification Tag of
* the peer. If the Verification Tag is not 0 and does NOT
* match, discard the ICMP message. If it is 0 and the ICMP
* message contains enough bytes to verify that the chunk type is
* an INIT chunk and that the Initiate Tag matches the tag of the
* peer, continue with ICMP7. If the ICMP message is too short
* or the chunk type or the Initiate Tag does not match, silently
* discard the packet.
*/
if (vtag == 0) {
/* chunk header + first 4 octects of init header */
chunkhdr = skb_header_pointer(skb, skb_transport_offset(skb) +
sizeof(struct sctphdr),
sizeof(struct sctp_chunkhdr) +
sizeof(__be32), &_chunkhdr);
if (!chunkhdr ||
chunkhdr->chunk_hdr.type != SCTP_CID_INIT ||
ntohl(chunkhdr->init_hdr.init_tag) != asoc->c.my_vtag)
goto out;
} else if (vtag != asoc->c.peer_vtag) {
goto out;
}
bh_lock_sock(sk);
/* If too many ICMPs get dropped on busy
* servers this needs to be solved differently.
*/
if (sock_owned_by_user(sk))
__NET_INC_STATS(net, LINUX_MIB_LOCKDROPPEDICMPS);
*app = asoc;
*tpp = transport;
return sk;
out:
sctp_transport_put(transport);
return NULL;
}
/* Common cleanup code for icmp/icmpv6 error handler. */
void sctp_err_finish(struct sock *sk, struct sctp_transport *t)
__releases(&((__sk)->sk_lock.slock))
{
bh_unlock_sock(sk);
sctp_transport_put(t);
}
static void sctp_v4_err_handle(struct sctp_transport *t, struct sk_buff *skb,
__u8 type, __u8 code, __u32 info)
{
struct sctp_association *asoc = t->asoc;
struct sock *sk = asoc->base.sk;
int err = 0;
switch (type) {
case ICMP_PARAMETERPROB:
err = EPROTO;
break;
case ICMP_DEST_UNREACH:
if (code > NR_ICMP_UNREACH)
return;
if (code == ICMP_FRAG_NEEDED) {
sctp_icmp_frag_needed(sk, asoc, t, SCTP_TRUNC4(info));
return;
}
if (code == ICMP_PROT_UNREACH) {
sctp_icmp_proto_unreachable(sk, asoc, t);
return;
}
err = icmp_err_convert[code].errno;
break;
case ICMP_TIME_EXCEEDED:
if (code == ICMP_EXC_FRAGTIME)
return;
err = EHOSTUNREACH;
break;
case ICMP_REDIRECT:
sctp_icmp_redirect(sk, t, skb);
return;
default:
return;
}
if (!sock_owned_by_user(sk) && inet_test_bit(RECVERR, sk)) {
sk->sk_err = err;
sk_error_report(sk);
} else { /* Only an error on timeout */
WRITE_ONCE(sk->sk_err_soft, err);
}
}
/*
* This routine is called by the ICMP module when it gets some
* sort of error condition. If err < 0 then the socket should
* be closed and the error returned to the user. If err > 0
* it's just the icmp type << 8 | icmp code. After adjustment
* header points to the first 8 bytes of the sctp header. We need
* to find the appropriate port.
*
* The locking strategy used here is very "optimistic". When
* someone else accesses the socket the ICMP is just dropped
* and for some paths there is no check at all.
* A more general error queue to queue errors for later handling
* is probably better.
*
*/
int sctp_v4_err(struct sk_buff *skb, __u32 info)
{
const struct iphdr *iph = (const struct iphdr *)skb->data;
const int type = icmp_hdr(skb)->type;
const int code = icmp_hdr(skb)->code;
struct net *net = dev_net(skb->dev);
struct sctp_transport *transport;
struct sctp_association *asoc;
__u16 saveip, savesctp;
struct sock *sk;
/* Fix up skb to look at the embedded net header. */
saveip = skb->network_header;
savesctp = skb->transport_header;
skb_reset_network_header(skb);
skb_set_transport_header(skb, iph->ihl * 4);
sk = sctp_err_lookup(net, AF_INET, skb, sctp_hdr(skb), &asoc, &transport);
/* Put back, the original values. */
skb->network_header = saveip;
skb->transport_header = savesctp;
if (!sk) {
__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
return -ENOENT;
}
sctp_v4_err_handle(transport, skb, type, code, info);
sctp_err_finish(sk, transport);
return 0;
}
int sctp_udp_v4_err(struct sock *sk, struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
struct sctp_association *asoc;
struct sctp_transport *t;
struct icmphdr *hdr;
__u32 info = 0;
skb->transport_header += sizeof(struct udphdr);
sk = sctp_err_lookup(net, AF_INET, skb, sctp_hdr(skb), &asoc, &t);
if (!sk) {
__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
return -ENOENT;
}
skb->transport_header -= sizeof(struct udphdr);
hdr = (struct icmphdr *)(skb_network_header(skb) - sizeof(struct icmphdr));
if (hdr->type == ICMP_REDIRECT) {
/* can't be handled without outer iphdr known, leave it to udp_err */
sctp_err_finish(sk, t);
return 0;
}
if (hdr->type == ICMP_DEST_UNREACH && hdr->code == ICMP_FRAG_NEEDED)
info = ntohs(hdr->un.frag.mtu);
sctp_v4_err_handle(t, skb, hdr->type, hdr->code, info);
sctp_err_finish(sk, t);
return 1;
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets.
*
* This function scans all the chunks in the OOTB packet to determine if
* the packet should be discarded right away. If a response might be needed
* for this packet, or, if further processing is possible, the packet will
* be queued to a proper inqueue for the next phase of handling.
*
* Output:
* Return 0 - If further processing is needed.
* Return 1 - If the packet can be discarded right away.
*/
static int sctp_rcv_ootb(struct sk_buff *skb)
{
struct sctp_chunkhdr *ch, _ch;
int ch_end, offset = 0;
/* Scan through all the chunks in the packet. */
do {
/* Make sure we have at least the header there */
if (offset + sizeof(_ch) > skb->len)
break;
ch = skb_header_pointer(skb, offset, sizeof(*ch), &_ch);
/* Break out if chunk length is less then minimal. */
if (!ch || ntohs(ch->length) < sizeof(_ch))
break;
ch_end = offset + SCTP_PAD4(ntohs(ch->length));
if (ch_end > skb->len)
break;
/* RFC 8.4, 2) If the OOTB packet contains an ABORT chunk, the
* receiver MUST silently discard the OOTB packet and take no
* further action.
*/
if (SCTP_CID_ABORT == ch->type)
goto discard;
/* RFC 8.4, 6) If the packet contains a SHUTDOWN COMPLETE
* chunk, the receiver should silently discard the packet
* and take no further action.
*/
if (SCTP_CID_SHUTDOWN_COMPLETE == ch->type)
goto discard;
/* RFC 4460, 2.11.2
* This will discard packets with INIT chunk bundled as
* subsequent chunks in the packet. When INIT is first,
* the normal INIT processing will discard the chunk.
*/
if (SCTP_CID_INIT == ch->type && (void *)ch != skb->data)
goto discard;
offset = ch_end;
} while (ch_end < skb->len);
return 0;
discard:
return 1;
}
/* Insert endpoint into the hash table. */
static int __sctp_hash_endpoint(struct sctp_endpoint *ep)
{
struct sock *sk = ep->base.sk;
struct net *net = sock_net(sk);
struct sctp_hashbucket *head;
ep->hashent = sctp_ep_hashfn(net, ep->base.bind_addr.port);
head = &sctp_ep_hashtable[ep->hashent];
if (sk->sk_reuseport) {
bool any = sctp_is_ep_boundall(sk);
struct sctp_endpoint *ep2;
struct list_head *list;
int cnt = 0, err = 1;
list_for_each(list, &ep->base.bind_addr.address_list)
cnt++;
sctp_for_each_hentry(ep2, &head->chain) {
struct sock *sk2 = ep2->base.sk;
if (!net_eq(sock_net(sk2), net) || sk2 == sk ||
!uid_eq(sock_i_uid(sk2), sock_i_uid(sk)) ||
!sk2->sk_reuseport)
continue;
err = sctp_bind_addrs_check(sctp_sk(sk2),
sctp_sk(sk), cnt);
if (!err) {
err = reuseport_add_sock(sk, sk2, any);
if (err)
return err;
break;
} else if (err < 0) {
return err;
}
}
if (err) {
err = reuseport_alloc(sk, any);
if (err)
return err;
}
}
write_lock(&head->lock);
hlist_add_head(&ep->node, &head->chain);
write_unlock(&head->lock);
return 0;
}
/* Add an endpoint to the hash. Local BH-safe. */
int sctp_hash_endpoint(struct sctp_endpoint *ep)
{
int err;
local_bh_disable();
err = __sctp_hash_endpoint(ep);
local_bh_enable();
return err;
}
/* Remove endpoint from the hash table. */
static void __sctp_unhash_endpoint(struct sctp_endpoint *ep)
{
struct sock *sk = ep->base.sk;
struct sctp_hashbucket *head;
ep->hashent = sctp_ep_hashfn(sock_net(sk), ep->base.bind_addr.port);
head = &sctp_ep_hashtable[ep->hashent];
if (rcu_access_pointer(sk->sk_reuseport_cb))
reuseport_detach_sock(sk);
write_lock(&head->lock);
hlist_del_init(&ep->node);
write_unlock(&head->lock);
}
/* Remove endpoint from the hash. Local BH-safe. */
void sctp_unhash_endpoint(struct sctp_endpoint *ep)
{
local_bh_disable();
__sctp_unhash_endpoint(ep);
local_bh_enable();
}
static inline __u32 sctp_hashfn(const struct net *net, __be16 lport,
const union sctp_addr *paddr, __u32 seed)
{
__u32 addr;
if (paddr->sa.sa_family == AF_INET6)
addr = jhash(&paddr->v6.sin6_addr, 16, seed);
else
addr = (__force __u32)paddr->v4.sin_addr.s_addr;
return jhash_3words(addr, ((__force __u32)paddr->v4.sin_port) << 16 |
(__force __u32)lport, net_hash_mix(net), seed);
}
/* Look up an endpoint. */
static struct sctp_endpoint *__sctp_rcv_lookup_endpoint(
struct net *net, struct sk_buff *skb,
const union sctp_addr *laddr,
const union sctp_addr *paddr,
int dif, int sdif)
{
struct sctp_hashbucket *head;
struct sctp_endpoint *ep;
struct sock *sk;
__be16 lport;
int hash;
lport = laddr->v4.sin_port;
hash = sctp_ep_hashfn(net, ntohs(lport));
head = &sctp_ep_hashtable[hash];
read_lock(&head->lock);
sctp_for_each_hentry(ep, &head->chain) {
if (sctp_endpoint_is_match(ep, net, laddr, dif, sdif))
goto hit;
}
ep = sctp_sk(net->sctp.ctl_sock)->ep;
hit:
sk = ep->base.sk;
if (sk->sk_reuseport) {
__u32 phash = sctp_hashfn(net, lport, paddr, 0);
sk = reuseport_select_sock(sk, phash, skb,
sizeof(struct sctphdr));
if (sk)
ep = sctp_sk(sk)->ep;
}
sctp_endpoint_hold(ep);
read_unlock(&head->lock);
return ep;
}
/* rhashtable for transport */
struct sctp_hash_cmp_arg {
const union sctp_addr *paddr;
const struct net *net;
__be16 lport;
};
static inline int sctp_hash_cmp(struct rhashtable_compare_arg *arg,
const void *ptr)
{
struct sctp_transport *t = (struct sctp_transport *)ptr;
const struct sctp_hash_cmp_arg *x = arg->key;
int err = 1;
if (!sctp_cmp_addr_exact(&t->ipaddr, x->paddr))
return err;
if (!sctp_transport_hold(t))
return err;
if (!net_eq(t->asoc->base.net, x->net))
goto out;
if (x->lport != htons(t->asoc->base.bind_addr.port))
goto out;
err = 0;
out:
sctp_transport_put(t);
return err;
}
static inline __u32 sctp_hash_obj(const void *data, u32 len, u32 seed)
{
const struct sctp_transport *t = data;
return sctp_hashfn(t->asoc->base.net,
htons(t->asoc->base.bind_addr.port),
&t->ipaddr, seed);
}
static inline __u32 sctp_hash_key(const void *data, u32 len, u32 seed)
{
const struct sctp_hash_cmp_arg *x = data;
return sctp_hashfn(x->net, x->lport, x->paddr, seed);
}
static const struct rhashtable_params sctp_hash_params = {
.head_offset = offsetof(struct sctp_transport, node),
.hashfn = sctp_hash_key,
.obj_hashfn = sctp_hash_obj,
.obj_cmpfn = sctp_hash_cmp,
.automatic_shrinking = true,
};
int sctp_transport_hashtable_init(void)
{
return rhltable_init(&sctp_transport_hashtable, &sctp_hash_params);
}
void sctp_transport_hashtable_destroy(void)
{
rhltable_destroy(&sctp_transport_hashtable);
}
int sctp_hash_transport(struct sctp_transport *t)
{
struct sctp_transport *transport;
struct rhlist_head *tmp, *list;
struct sctp_hash_cmp_arg arg;
int err;
if (t->asoc->temp)
return 0;
arg.net = t->asoc->base.net;
arg.paddr = &t->ipaddr;
arg.lport = htons(t->asoc->base.bind_addr.port);
rcu_read_lock();
list = rhltable_lookup(&sctp_transport_hashtable, &arg,
sctp_hash_params);
rhl_for_each_entry_rcu(transport, tmp, list, node)
if (transport->asoc->ep == t->asoc->ep) {
rcu_read_unlock();
return -EEXIST;
}
rcu_read_unlock();
err = rhltable_insert_key(&sctp_transport_hashtable, &arg,
&t->node, sctp_hash_params);
if (err)
pr_err_once("insert transport fail, errno %d\n", err);
return err;
}
void sctp_unhash_transport(struct sctp_transport *t)
{
if (t->asoc->temp)
return;
rhltable_remove(&sctp_transport_hashtable, &t->node,
sctp_hash_params);
}
bool sctp_sk_bound_dev_eq(struct net *net, int bound_dev_if, int dif, int sdif)
{
bool l3mdev_accept = true;
#if IS_ENABLED(CONFIG_NET_L3_MASTER_DEV)
l3mdev_accept = !!READ_ONCE(net->sctp.l3mdev_accept);
#endif
return inet_bound_dev_eq(l3mdev_accept, bound_dev_if, dif, sdif);
}
/* return a transport with holding it */
struct sctp_transport *sctp_addrs_lookup_transport(
struct net *net,
const union sctp_addr *laddr,
const union sctp_addr *paddr,
int dif, int sdif)
{
struct rhlist_head *tmp, *list;
struct sctp_transport *t;
int bound_dev_if;
struct sctp_hash_cmp_arg arg = {
.paddr = paddr,
.net = net,
.lport = laddr->v4.sin_port,
};
list = rhltable_lookup(&sctp_transport_hashtable, &arg,
sctp_hash_params);
rhl_for_each_entry_rcu(t, tmp, list, node) {
if (!sctp_transport_hold(t))
continue;
bound_dev_if = READ_ONCE(t->asoc->base.sk->sk_bound_dev_if);
if (sctp_sk_bound_dev_eq(net, bound_dev_if, dif, sdif) &&
sctp_bind_addr_match(&t->asoc->base.bind_addr,
laddr, sctp_sk(t->asoc->base.sk)))
return t;
sctp_transport_put(t);
}
return NULL;
}
/* return a transport without holding it, as it's only used under sock lock */
struct sctp_transport *sctp_epaddr_lookup_transport(
const struct sctp_endpoint *ep,
const union sctp_addr *paddr)
{
struct rhlist_head *tmp, *list;
struct sctp_transport *t;
struct sctp_hash_cmp_arg arg = {
.paddr = paddr,
.net = ep->base.net,
.lport = htons(ep->base.bind_addr.port),
};
list = rhltable_lookup(&sctp_transport_hashtable, &arg,
sctp_hash_params);
rhl_for_each_entry_rcu(t, tmp, list, node)
if (ep == t->asoc->ep)
return t;
return NULL;
}
/* Look up an association. */
static struct sctp_association *__sctp_lookup_association(
struct net *net,
const union sctp_addr *local,
const union sctp_addr *peer,
struct sctp_transport **pt,
int dif, int sdif)
{
struct sctp_transport *t;
struct sctp_association *asoc = NULL;
t = sctp_addrs_lookup_transport(net, local, peer, dif, sdif);
if (!t)
goto out;
asoc = t->asoc;
*pt = t;
out:
return asoc;
}
/* Look up an association. protected by RCU read lock */
static
struct sctp_association *sctp_lookup_association(struct net *net,
const union sctp_addr *laddr,
const union sctp_addr *paddr,
struct sctp_transport **transportp,
int dif, int sdif)
{
struct sctp_association *asoc;
rcu_read_lock();
asoc = __sctp_lookup_association(net, laddr, paddr, transportp, dif, sdif);
rcu_read_unlock();
return asoc;
}
/* Is there an association matching the given local and peer addresses? */
bool sctp_has_association(struct net *net,
const union sctp_addr *laddr,
const union sctp_addr *paddr,
int dif, int sdif)
{
struct sctp_transport *transport;
if (sctp_lookup_association(net, laddr, paddr, &transport, dif, sdif)) {
sctp_transport_put(transport);
return true;
}
return false;
}
/*
* SCTP Implementors Guide, 2.18 Handling of address
* parameters within the INIT or INIT-ACK.
*
* D) When searching for a matching TCB upon reception of an INIT
* or INIT-ACK chunk the receiver SHOULD use not only the
* source address of the packet (containing the INIT or
* INIT-ACK) but the receiver SHOULD also use all valid
* address parameters contained within the chunk.
*
* 2.18.3 Solution description
*
* This new text clearly specifies to an implementor the need
* to look within the INIT or INIT-ACK. Any implementation that
* does not do this, may not be able to establish associations
* in certain circumstances.
*
*/
static struct sctp_association *__sctp_rcv_init_lookup(struct net *net,
struct sk_buff *skb,
const union sctp_addr *laddr, struct sctp_transport **transportp,
int dif, int sdif)
{
struct sctp_association *asoc;
union sctp_addr addr;
union sctp_addr *paddr = &addr;
struct sctphdr *sh = sctp_hdr(skb);
union sctp_params params;
struct sctp_init_chunk *init;
struct sctp_af *af;
/*
* This code will NOT touch anything inside the chunk--it is
* strictly READ-ONLY.
*
* RFC 2960 3 SCTP packet Format
*
* Multiple chunks can be bundled into one SCTP packet up to
* the MTU size, except for the INIT, INIT ACK, and SHUTDOWN
* COMPLETE chunks. These chunks MUST NOT be bundled with any
* other chunk in a packet. See Section 6.10 for more details
* on chunk bundling.
*/
/* Find the start of the TLVs and the end of the chunk. This is
* the region we search for address parameters.
*/
init = (struct sctp_init_chunk *)skb->data;
/* Walk the parameters looking for embedded addresses. */
sctp_walk_params(params, init) {
/* Note: Ignoring hostname addresses. */
af = sctp_get_af_specific(param_type2af(params.p->type));
if (!af)
continue;
if (!af->from_addr_param(paddr, params.addr, sh->source, 0))
continue;
asoc = __sctp_lookup_association(net, laddr, paddr, transportp, dif, sdif);
if (asoc)
return asoc;
}
return NULL;
}
/* ADD-IP, Section 5.2
* When an endpoint receives an ASCONF Chunk from the remote peer
* special procedures may be needed to identify the association the
* ASCONF Chunk is associated with. To properly find the association
* the following procedures SHOULD be followed:
*
* D2) If the association is not found, use the address found in the
* Address Parameter TLV combined with the port number found in the
* SCTP common header. If found proceed to rule D4.
*
* D2-ext) If more than one ASCONF Chunks are packed together, use the
* address found in the ASCONF Address Parameter TLV of each of the
* subsequent ASCONF Chunks. If found, proceed to rule D4.
*/
static struct sctp_association *__sctp_rcv_asconf_lookup(
struct net *net,
struct sctp_chunkhdr *ch,
const union sctp_addr *laddr,
__be16 peer_port,
struct sctp_transport **transportp,
int dif, int sdif)
{
struct sctp_addip_chunk *asconf = (struct sctp_addip_chunk *)ch;
struct sctp_af *af;
union sctp_addr_param *param;
union sctp_addr paddr;
if (ntohs(ch->length) < sizeof(*asconf) + sizeof(struct sctp_paramhdr))
return NULL;
/* Skip over the ADDIP header and find the Address parameter */
param = (union sctp_addr_param *)(asconf + 1);
af = sctp_get_af_specific(param_type2af(param->p.type));
if (unlikely(!af))
return NULL;
if (!af->from_addr_param(&paddr, param, peer_port, 0))
return NULL;
return __sctp_lookup_association(net, laddr, &paddr, transportp, dif, sdif);
}
/* SCTP-AUTH, Section 6.3:
* If the receiver does not find a STCB for a packet containing an AUTH
* chunk as the first chunk and not a COOKIE-ECHO chunk as the second
* chunk, it MUST use the chunks after the AUTH chunk to look up an existing
* association.
*
* This means that any chunks that can help us identify the association need
* to be looked at to find this association.
*/
static struct sctp_association *__sctp_rcv_walk_lookup(struct net *net,
struct sk_buff *skb,
const union sctp_addr *laddr,
struct sctp_transport **transportp,
int dif, int sdif)
{
struct sctp_association *asoc = NULL;
struct sctp_chunkhdr *ch;
int have_auth = 0;
unsigned int chunk_num = 1;
__u8 *ch_end;
/* Walk through the chunks looking for AUTH or ASCONF chunks
* to help us find the association.
*/
ch = (struct sctp_chunkhdr *)skb->data;
do {
/* Break out if chunk length is less then minimal. */
if (ntohs(ch->length) < sizeof(*ch))
break;
ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
break;
switch (ch->type) {
case SCTP_CID_AUTH:
have_auth = chunk_num;
break;
case SCTP_CID_COOKIE_ECHO:
/* If a packet arrives containing an AUTH chunk as
* a first chunk, a COOKIE-ECHO chunk as the second
* chunk, and possibly more chunks after them, and
* the receiver does not have an STCB for that
* packet, then authentication is based on
* the contents of the COOKIE- ECHO chunk.
*/
if (have_auth == 1 && chunk_num == 2)
return NULL;
break;
case SCTP_CID_ASCONF:
if (have_auth || net->sctp.addip_noauth)
asoc = __sctp_rcv_asconf_lookup(
net, ch, laddr,
sctp_hdr(skb)->source,
transportp, dif, sdif);
break;
default:
break;
}
if (asoc)
break;
ch = (struct sctp_chunkhdr *)ch_end;
chunk_num++;
} while (ch_end + sizeof(*ch) < skb_tail_pointer(skb));
return asoc;
}
/*
* There are circumstances when we need to look inside the SCTP packet
* for information to help us find the association. Examples
* include looking inside of INIT/INIT-ACK chunks or after the AUTH
* chunks.
*/
static struct sctp_association *__sctp_rcv_lookup_harder(struct net *net,
struct sk_buff *skb,
const union sctp_addr *laddr,
struct sctp_transport **transportp,
int dif, int sdif)
{
struct sctp_chunkhdr *ch;
/* We do not allow GSO frames here as we need to linearize and
* then cannot guarantee frame boundaries. This shouldn't be an
* issue as packets hitting this are mostly INIT or INIT-ACK and
* those cannot be on GSO-style anyway.
*/
if (skb_is_gso(skb) && skb_is_gso_sctp(skb))
return NULL;
ch = (struct sctp_chunkhdr *)skb->data;
/* The code below will attempt to walk the chunk and extract
* parameter information. Before we do that, we need to verify
* that the chunk length doesn't cause overflow. Otherwise, we'll
* walk off the end.
*/
if (SCTP_PAD4(ntohs(ch->length)) > skb->len)
return NULL;
/* If this is INIT/INIT-ACK look inside the chunk too. */
if (ch->type == SCTP_CID_INIT || ch->type == SCTP_CID_INIT_ACK)
return __sctp_rcv_init_lookup(net, skb, laddr, transportp, dif, sdif);
return __sctp_rcv_walk_lookup(net, skb, laddr, transportp, dif, sdif);
}
/* Lookup an association for an inbound skb. */
static struct sctp_association *__sctp_rcv_lookup(struct net *net,
struct sk_buff *skb,
const union sctp_addr *paddr,
const union sctp_addr *laddr,
struct sctp_transport **transportp,
int dif, int sdif)
{
struct sctp_association *asoc;
asoc = __sctp_lookup_association(net, laddr, paddr, transportp, dif, sdif);
if (asoc)
goto out;
/* Further lookup for INIT/INIT-ACK packets.
* SCTP Implementors Guide, 2.18 Handling of address
* parameters within the INIT or INIT-ACK.
*/
asoc = __sctp_rcv_lookup_harder(net, skb, laddr, transportp, dif, sdif);
if (asoc)
goto out;
if (paddr->sa.sa_family == AF_INET)
pr_debug("sctp: asoc not found for src:%pI4:%d dst:%pI4:%d\n",
&laddr->v4.sin_addr, ntohs(laddr->v4.sin_port),
&paddr->v4.sin_addr, ntohs(paddr->v4.sin_port));
else
pr_debug("sctp: asoc not found for src:%pI6:%d dst:%pI6:%d\n",
&laddr->v6.sin6_addr, ntohs(laddr->v6.sin6_port),
&paddr->v6.sin6_addr, ntohs(paddr->v6.sin6_port));
out:
return asoc;
}
| linux-master | net/sctp/input.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2003
* Copyright (c) Cisco 1999,2000
* Copyright (c) Motorola 1999,2000,2001
* Copyright (c) La Monte H.P. Yarroll 2001
*
* This file is part of the SCTP kernel implementation.
*
* A collection class to handle the storage of transport addresses.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Jon Grimm <[email protected]>
* Daisy Chang <[email protected]>
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <net/sock.h>
#include <net/ipv6.h>
#include <net/if_inet6.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
/* Forward declarations for internal helpers. */
static int sctp_copy_one_addr(struct net *net, struct sctp_bind_addr *dest,
union sctp_addr *addr, enum sctp_scope scope,
gfp_t gfp, int flags);
static void sctp_bind_addr_clean(struct sctp_bind_addr *);
/* First Level Abstractions. */
/* Copy 'src' to 'dest' taking 'scope' into account. Omit addresses
* in 'src' which have a broader scope than 'scope'.
*/
int sctp_bind_addr_copy(struct net *net, struct sctp_bind_addr *dest,
const struct sctp_bind_addr *src,
enum sctp_scope scope, gfp_t gfp,
int flags)
{
struct sctp_sockaddr_entry *addr;
int error = 0;
/* All addresses share the same port. */
dest->port = src->port;
/* Extract the addresses which are relevant for this scope. */
list_for_each_entry(addr, &src->address_list, list) {
error = sctp_copy_one_addr(net, dest, &addr->a, scope,
gfp, flags);
if (error < 0)
goto out;
}
/* If there are no addresses matching the scope and
* this is global scope, try to get a link scope address, with
* the assumption that we must be sitting behind a NAT.
*/
if (list_empty(&dest->address_list) && (SCTP_SCOPE_GLOBAL == scope)) {
list_for_each_entry(addr, &src->address_list, list) {
error = sctp_copy_one_addr(net, dest, &addr->a,
SCTP_SCOPE_LINK, gfp,
flags);
if (error < 0)
goto out;
}
}
/* If somehow no addresses were found that can be used with this
* scope, it's an error.
*/
if (list_empty(&dest->address_list))
error = -ENETUNREACH;
out:
if (error)
sctp_bind_addr_clean(dest);
return error;
}
/* Exactly duplicate the address lists. This is necessary when doing
* peer-offs and accepts. We don't want to put all the current system
* addresses into the endpoint. That's useless. But we do want duplicat
* the list of bound addresses that the older endpoint used.
*/
int sctp_bind_addr_dup(struct sctp_bind_addr *dest,
const struct sctp_bind_addr *src,
gfp_t gfp)
{
struct sctp_sockaddr_entry *addr;
int error = 0;
/* All addresses share the same port. */
dest->port = src->port;
list_for_each_entry(addr, &src->address_list, list) {
error = sctp_add_bind_addr(dest, &addr->a, sizeof(addr->a),
1, gfp);
if (error < 0)
break;
}
return error;
}
/* Initialize the SCTP_bind_addr structure for either an endpoint or
* an association.
*/
void sctp_bind_addr_init(struct sctp_bind_addr *bp, __u16 port)
{
INIT_LIST_HEAD(&bp->address_list);
bp->port = port;
}
/* Dispose of the address list. */
static void sctp_bind_addr_clean(struct sctp_bind_addr *bp)
{
struct sctp_sockaddr_entry *addr, *temp;
/* Empty the bind address list. */
list_for_each_entry_safe(addr, temp, &bp->address_list, list) {
list_del_rcu(&addr->list);
kfree_rcu(addr, rcu);
SCTP_DBG_OBJCNT_DEC(addr);
}
}
/* Dispose of an SCTP_bind_addr structure */
void sctp_bind_addr_free(struct sctp_bind_addr *bp)
{
/* Empty the bind address list. */
sctp_bind_addr_clean(bp);
}
/* Add an address to the bind address list in the SCTP_bind_addr structure. */
int sctp_add_bind_addr(struct sctp_bind_addr *bp, union sctp_addr *new,
int new_size, __u8 addr_state, gfp_t gfp)
{
struct sctp_sockaddr_entry *addr;
/* Add the address to the bind address list. */
addr = kzalloc(sizeof(*addr), gfp);
if (!addr)
return -ENOMEM;
memcpy(&addr->a, new, min_t(size_t, sizeof(*new), new_size));
/* Fix up the port if it has not yet been set.
* Both v4 and v6 have the port at the same offset.
*/
if (!addr->a.v4.sin_port)
addr->a.v4.sin_port = htons(bp->port);
addr->state = addr_state;
addr->valid = 1;
INIT_LIST_HEAD(&addr->list);
/* We always hold a socket lock when calling this function,
* and that acts as a writer synchronizing lock.
*/
list_add_tail_rcu(&addr->list, &bp->address_list);
SCTP_DBG_OBJCNT_INC(addr);
return 0;
}
/* Delete an address from the bind address list in the SCTP_bind_addr
* structure.
*/
int sctp_del_bind_addr(struct sctp_bind_addr *bp, union sctp_addr *del_addr)
{
struct sctp_sockaddr_entry *addr, *temp;
int found = 0;
/* We hold the socket lock when calling this function,
* and that acts as a writer synchronizing lock.
*/
list_for_each_entry_safe(addr, temp, &bp->address_list, list) {
if (sctp_cmp_addr_exact(&addr->a, del_addr)) {
/* Found the exact match. */
found = 1;
addr->valid = 0;
list_del_rcu(&addr->list);
break;
}
}
if (found) {
kfree_rcu(addr, rcu);
SCTP_DBG_OBJCNT_DEC(addr);
return 0;
}
return -EINVAL;
}
/* Create a network byte-order representation of all the addresses
* formated as SCTP parameters.
*
* The second argument is the return value for the length.
*/
union sctp_params sctp_bind_addrs_to_raw(const struct sctp_bind_addr *bp,
int *addrs_len,
gfp_t gfp)
{
union sctp_params addrparms;
union sctp_params retval;
int addrparms_len;
union sctp_addr_param rawaddr;
int len;
struct sctp_sockaddr_entry *addr;
struct list_head *pos;
struct sctp_af *af;
addrparms_len = 0;
len = 0;
/* Allocate enough memory at once. */
list_for_each(pos, &bp->address_list) {
len += sizeof(union sctp_addr_param);
}
/* Don't even bother embedding an address if there
* is only one.
*/
if (len == sizeof(union sctp_addr_param)) {
retval.v = NULL;
goto end_raw;
}
retval.v = kmalloc(len, gfp);
if (!retval.v)
goto end_raw;
addrparms = retval;
list_for_each_entry(addr, &bp->address_list, list) {
af = sctp_get_af_specific(addr->a.v4.sin_family);
len = af->to_addr_param(&addr->a, &rawaddr);
memcpy(addrparms.v, &rawaddr, len);
addrparms.v += len;
addrparms_len += len;
}
end_raw:
*addrs_len = addrparms_len;
return retval;
}
/*
* Create an address list out of the raw address list format (IPv4 and IPv6
* address parameters).
*/
int sctp_raw_to_bind_addrs(struct sctp_bind_addr *bp, __u8 *raw_addr_list,
int addrs_len, __u16 port, gfp_t gfp)
{
union sctp_addr_param *rawaddr;
struct sctp_paramhdr *param;
union sctp_addr addr;
int retval = 0;
int len;
struct sctp_af *af;
/* Convert the raw address to standard address format */
while (addrs_len) {
param = (struct sctp_paramhdr *)raw_addr_list;
rawaddr = (union sctp_addr_param *)raw_addr_list;
af = sctp_get_af_specific(param_type2af(param->type));
if (unlikely(!af) ||
!af->from_addr_param(&addr, rawaddr, htons(port), 0)) {
retval = -EINVAL;
goto out_err;
}
if (sctp_bind_addr_state(bp, &addr) != -1)
goto next;
retval = sctp_add_bind_addr(bp, &addr, sizeof(addr),
SCTP_ADDR_SRC, gfp);
if (retval)
/* Can't finish building the list, clean up. */
goto out_err;
next:
len = ntohs(param->length);
addrs_len -= len;
raw_addr_list += len;
}
return retval;
out_err:
if (retval)
sctp_bind_addr_clean(bp);
return retval;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* Does this contain a specified address? Allow wildcarding. */
int sctp_bind_addr_match(struct sctp_bind_addr *bp,
const union sctp_addr *addr,
struct sctp_sock *opt)
{
struct sctp_sockaddr_entry *laddr;
int match = 0;
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
if (!laddr->valid)
continue;
if (opt->pf->cmp_addr(&laddr->a, addr, opt)) {
match = 1;
break;
}
}
rcu_read_unlock();
return match;
}
int sctp_bind_addrs_check(struct sctp_sock *sp,
struct sctp_sock *sp2, int cnt2)
{
struct sctp_bind_addr *bp2 = &sp2->ep->base.bind_addr;
struct sctp_bind_addr *bp = &sp->ep->base.bind_addr;
struct sctp_sockaddr_entry *laddr, *laddr2;
bool exist = false;
int cnt = 0;
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
list_for_each_entry_rcu(laddr2, &bp2->address_list, list) {
if (sp->pf->af->cmp_addr(&laddr->a, &laddr2->a) &&
laddr->valid && laddr2->valid) {
exist = true;
goto next;
}
}
cnt = 0;
break;
next:
cnt++;
}
rcu_read_unlock();
return (cnt == cnt2) ? 0 : (exist ? -EEXIST : 1);
}
/* Does the address 'addr' conflict with any addresses in
* the bp.
*/
int sctp_bind_addr_conflict(struct sctp_bind_addr *bp,
const union sctp_addr *addr,
struct sctp_sock *bp_sp,
struct sctp_sock *addr_sp)
{
struct sctp_sockaddr_entry *laddr;
int conflict = 0;
struct sctp_sock *sp;
/* Pick the IPv6 socket as the basis of comparison
* since it's usually a superset of the IPv4.
* If there is no IPv6 socket, then default to bind_addr.
*/
if (sctp_opt2sk(bp_sp)->sk_family == AF_INET6)
sp = bp_sp;
else if (sctp_opt2sk(addr_sp)->sk_family == AF_INET6)
sp = addr_sp;
else
sp = bp_sp;
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
if (!laddr->valid)
continue;
conflict = sp->pf->cmp_addr(&laddr->a, addr, sp);
if (conflict)
break;
}
rcu_read_unlock();
return conflict;
}
/* Get the state of the entry in the bind_addr_list */
int sctp_bind_addr_state(const struct sctp_bind_addr *bp,
const union sctp_addr *addr)
{
struct sctp_sockaddr_entry *laddr;
struct sctp_af *af;
af = sctp_get_af_specific(addr->sa.sa_family);
if (unlikely(!af))
return -1;
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
if (!laddr->valid)
continue;
if (af->cmp_addr(&laddr->a, addr))
return laddr->state;
}
return -1;
}
/* Find the first address in the bind address list that is not present in
* the addrs packed array.
*/
union sctp_addr *sctp_find_unmatch_addr(struct sctp_bind_addr *bp,
const union sctp_addr *addrs,
int addrcnt,
struct sctp_sock *opt)
{
struct sctp_sockaddr_entry *laddr;
union sctp_addr *addr;
void *addr_buf;
struct sctp_af *af;
int i;
/* This is only called sctp_send_asconf_del_ip() and we hold
* the socket lock in that code patch, so that address list
* can't change.
*/
list_for_each_entry(laddr, &bp->address_list, list) {
addr_buf = (union sctp_addr *)addrs;
for (i = 0; i < addrcnt; i++) {
addr = addr_buf;
af = sctp_get_af_specific(addr->v4.sin_family);
if (!af)
break;
if (opt->pf->cmp_addr(&laddr->a, addr, opt))
break;
addr_buf += af->sockaddr_len;
}
if (i == addrcnt)
return &laddr->a;
}
return NULL;
}
/* Copy out addresses from the global local address list. */
static int sctp_copy_one_addr(struct net *net, struct sctp_bind_addr *dest,
union sctp_addr *addr, enum sctp_scope scope,
gfp_t gfp, int flags)
{
int error = 0;
if (sctp_is_any(NULL, addr)) {
error = sctp_copy_local_addr_list(net, dest, scope, gfp, flags);
} else if (sctp_in_scope(net, addr, scope)) {
/* Now that the address is in scope, check to see if
* the address type is supported by local sock as
* well as the remote peer.
*/
if ((((AF_INET == addr->sa.sa_family) &&
(flags & SCTP_ADDR4_ALLOWED) &&
(flags & SCTP_ADDR4_PEERSUPP))) ||
(((AF_INET6 == addr->sa.sa_family) &&
(flags & SCTP_ADDR6_ALLOWED) &&
(flags & SCTP_ADDR6_PEERSUPP))))
error = sctp_add_bind_addr(dest, addr, sizeof(*addr),
SCTP_ADDR_SRC, gfp);
}
return error;
}
/* Is this a wildcard address? */
int sctp_is_any(struct sock *sk, const union sctp_addr *addr)
{
unsigned short fam = 0;
struct sctp_af *af;
/* Try to get the right address family */
if (addr->sa.sa_family != AF_UNSPEC)
fam = addr->sa.sa_family;
else if (sk)
fam = sk->sk_family;
af = sctp_get_af_specific(fam);
if (!af)
return 0;
return af->is_any(addr);
}
/* Is 'addr' valid for 'scope'? */
int sctp_in_scope(struct net *net, const union sctp_addr *addr,
enum sctp_scope scope)
{
enum sctp_scope addr_scope = sctp_scope(addr);
/* The unusable SCTP addresses will not be considered with
* any defined scopes.
*/
if (SCTP_SCOPE_UNUSABLE == addr_scope)
return 0;
/*
* For INIT and INIT-ACK address list, let L be the level of
* requested destination address, sender and receiver
* SHOULD include all of its addresses with level greater
* than or equal to L.
*
* Address scoping can be selectively controlled via sysctl
* option
*/
switch (net->sctp.scope_policy) {
case SCTP_SCOPE_POLICY_DISABLE:
return 1;
case SCTP_SCOPE_POLICY_ENABLE:
if (addr_scope <= scope)
return 1;
break;
case SCTP_SCOPE_POLICY_PRIVATE:
if (addr_scope <= scope || SCTP_SCOPE_PRIVATE == addr_scope)
return 1;
break;
case SCTP_SCOPE_POLICY_LINK:
if (addr_scope <= scope || SCTP_SCOPE_LINK == addr_scope)
return 1;
break;
default:
break;
}
return 0;
}
int sctp_is_ep_boundall(struct sock *sk)
{
struct sctp_bind_addr *bp;
struct sctp_sockaddr_entry *addr;
bp = &sctp_sk(sk)->ep->base.bind_addr;
if (sctp_list_single_entry(&bp->address_list)) {
addr = list_entry(bp->address_list.next,
struct sctp_sockaddr_entry, list);
if (sctp_is_any(sk, &addr->a))
return 1;
}
return 0;
}
/********************************************************************
* 3rd Level Abstractions
********************************************************************/
/* What is the scope of 'addr'? */
enum sctp_scope sctp_scope(const union sctp_addr *addr)
{
struct sctp_af *af;
af = sctp_get_af_specific(addr->sa.sa_family);
if (!af)
return SCTP_SCOPE_UNUSABLE;
return af->scope((union sctp_addr *)addr);
}
| linux-master | net/sctp/bind_addr.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
*
* This file is part of the SCTP kernel implementation
*
* These functions implement the SCTP primitive functions from Section 10.
*
* Note that the descriptions from the specification are USER level
* functions--this file is the functions which populate the struct proto
* for SCTP which is the BOTTOM of the sockets interface.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Narasimha Budihal <[email protected]>
* Karl Knutson <[email protected]>
* Ardelle Fan <[email protected]>
* Kevin Gao <[email protected]>
*/
#include <linux/types.h>
#include <linux/list.h> /* For struct list_head */
#include <linux/socket.h>
#include <linux/ip.h>
#include <linux/time.h> /* For struct timeval */
#include <linux/gfp.h>
#include <net/sock.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#define DECLARE_PRIMITIVE(name) \
/* This is called in the code as sctp_primitive_ ## name. */ \
int sctp_primitive_ ## name(struct net *net, struct sctp_association *asoc, \
void *arg) { \
int error = 0; \
enum sctp_event_type event_type; union sctp_subtype subtype; \
enum sctp_state state; \
struct sctp_endpoint *ep; \
\
event_type = SCTP_EVENT_T_PRIMITIVE; \
subtype = SCTP_ST_PRIMITIVE(SCTP_PRIMITIVE_ ## name); \
state = asoc ? asoc->state : SCTP_STATE_CLOSED; \
ep = asoc ? asoc->ep : NULL; \
\
error = sctp_do_sm(net, event_type, subtype, state, ep, asoc, \
arg, GFP_KERNEL); \
return error; \
}
/* 10.1 ULP-to-SCTP
* B) Associate
*
* Format: ASSOCIATE(local SCTP instance name, destination transport addr,
* outbound stream count)
* -> association id [,destination transport addr list] [,outbound stream
* count]
*
* This primitive allows the upper layer to initiate an association to a
* specific peer endpoint.
*
* This version assumes that asoc is fully populated with the initial
* parameters. We then return a traditional kernel indicator of
* success or failure.
*/
/* This is called in the code as sctp_primitive_ASSOCIATE. */
DECLARE_PRIMITIVE(ASSOCIATE)
/* 10.1 ULP-to-SCTP
* C) Shutdown
*
* Format: SHUTDOWN(association id)
* -> result
*
* Gracefully closes an association. Any locally queued user data
* will be delivered to the peer. The association will be terminated only
* after the peer acknowledges all the SCTP packets sent. A success code
* will be returned on successful termination of the association. If
* attempting to terminate the association results in a failure, an error
* code shall be returned.
*/
DECLARE_PRIMITIVE(SHUTDOWN);
/* 10.1 ULP-to-SCTP
* C) Abort
*
* Format: Abort(association id [, cause code])
* -> result
*
* Ungracefully closes an association. Any locally queued user data
* will be discarded and an ABORT chunk is sent to the peer. A success
* code will be returned on successful abortion of the association. If
* attempting to abort the association results in a failure, an error
* code shall be returned.
*/
DECLARE_PRIMITIVE(ABORT);
/* 10.1 ULP-to-SCTP
* E) Send
*
* Format: SEND(association id, buffer address, byte count [,context]
* [,stream id] [,life time] [,destination transport address]
* [,unorder flag] [,no-bundle flag] [,payload protocol-id] )
* -> result
*
* This is the main method to send user data via SCTP.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o buffer address - the location where the user message to be
* transmitted is stored;
*
* o byte count - The size of the user data in number of bytes;
*
* Optional attributes:
*
* o context - an optional 32 bit integer that will be carried in the
* sending failure notification to the ULP if the transportation of
* this User Message fails.
*
* o stream id - to indicate which stream to send the data on. If not
* specified, stream 0 will be used.
*
* o life time - specifies the life time of the user data. The user data
* will not be sent by SCTP after the life time expires. This
* parameter can be used to avoid efforts to transmit stale
* user messages. SCTP notifies the ULP if the data cannot be
* initiated to transport (i.e. sent to the destination via SCTP's
* send primitive) within the life time variable. However, the
* user data will be transmitted if SCTP has attempted to transmit a
* chunk before the life time expired.
*
* o destination transport address - specified as one of the destination
* transport addresses of the peer endpoint to which this packet
* should be sent. Whenever possible, SCTP should use this destination
* transport address for sending the packets, instead of the current
* primary path.
*
* o unorder flag - this flag, if present, indicates that the user
* would like the data delivered in an unordered fashion to the peer
* (i.e., the U flag is set to 1 on all DATA chunks carrying this
* message).
*
* o no-bundle flag - instructs SCTP not to bundle this user data with
* other outbound DATA chunks. SCTP MAY still bundle even when
* this flag is present, when faced with network congestion.
*
* o payload protocol-id - A 32 bit unsigned integer that is to be
* passed to the peer indicating the type of payload protocol data
* being transmitted. This value is passed as opaque data by SCTP.
*/
DECLARE_PRIMITIVE(SEND);
/* 10.1 ULP-to-SCTP
* J) Request Heartbeat
*
* Format: REQUESTHEARTBEAT(association id, destination transport address)
*
* -> result
*
* Instructs the local endpoint to perform a HeartBeat on the specified
* destination transport address of the given association. The returned
* result should indicate whether the transmission of the HEARTBEAT
* chunk to the destination address is successful.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o destination transport address - the transport address of the
* association on which a heartbeat should be issued.
*/
DECLARE_PRIMITIVE(REQUESTHEARTBEAT);
/* ADDIP
* 3.1.1 Address Configuration Change Chunk (ASCONF)
*
* This chunk is used to communicate to the remote endpoint one of the
* configuration change requests that MUST be acknowledged. The
* information carried in the ASCONF Chunk uses the form of a
* Type-Length-Value (TLV), as described in "3.2.1 Optional/
* Variable-length Parameter Format" in RFC2960 [5], forall variable
* parameters.
*/
DECLARE_PRIMITIVE(ASCONF);
/* RE-CONFIG 5.1 */
DECLARE_PRIMITIVE(RECONF);
| linux-master | net/sctp/primitive.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 Nokia, Inc.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This file is part of the SCTP kernel implementation
*
* Initialization/cleanup for SCTP protocol support.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Jon Grimm <[email protected]>
* Sridhar Samudrala <[email protected]>
* Daisy Chang <[email protected]>
* Ardelle Fan <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/inetdevice.h>
#include <linux/seq_file.h>
#include <linux/memblock.h>
#include <linux/highmem.h>
#include <linux/slab.h>
#include <net/net_namespace.h>
#include <net/protocol.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/route.h>
#include <net/sctp/sctp.h>
#include <net/addrconf.h>
#include <net/inet_common.h>
#include <net/inet_ecn.h>
#include <net/udp_tunnel.h>
#define MAX_SCTP_PORT_HASH_ENTRIES (64 * 1024)
/* Global data structures. */
struct sctp_globals sctp_globals __read_mostly;
struct idr sctp_assocs_id;
DEFINE_SPINLOCK(sctp_assocs_id_lock);
static struct sctp_pf *sctp_pf_inet6_specific;
static struct sctp_pf *sctp_pf_inet_specific;
static struct sctp_af *sctp_af_v4_specific;
static struct sctp_af *sctp_af_v6_specific;
struct kmem_cache *sctp_chunk_cachep __read_mostly;
struct kmem_cache *sctp_bucket_cachep __read_mostly;
long sysctl_sctp_mem[3];
int sysctl_sctp_rmem[3];
int sysctl_sctp_wmem[3];
/* Private helper to extract ipv4 address and stash them in
* the protocol structure.
*/
static void sctp_v4_copy_addrlist(struct list_head *addrlist,
struct net_device *dev)
{
struct in_device *in_dev;
struct in_ifaddr *ifa;
struct sctp_sockaddr_entry *addr;
rcu_read_lock();
if ((in_dev = __in_dev_get_rcu(dev)) == NULL) {
rcu_read_unlock();
return;
}
in_dev_for_each_ifa_rcu(ifa, in_dev) {
/* Add the address to the local list. */
addr = kzalloc(sizeof(*addr), GFP_ATOMIC);
if (addr) {
addr->a.v4.sin_family = AF_INET;
addr->a.v4.sin_addr.s_addr = ifa->ifa_local;
addr->valid = 1;
INIT_LIST_HEAD(&addr->list);
list_add_tail(&addr->list, addrlist);
}
}
rcu_read_unlock();
}
/* Extract our IP addresses from the system and stash them in the
* protocol structure.
*/
static void sctp_get_local_addr_list(struct net *net)
{
struct net_device *dev;
struct list_head *pos;
struct sctp_af *af;
rcu_read_lock();
for_each_netdev_rcu(net, dev) {
list_for_each(pos, &sctp_address_families) {
af = list_entry(pos, struct sctp_af, list);
af->copy_addrlist(&net->sctp.local_addr_list, dev);
}
}
rcu_read_unlock();
}
/* Free the existing local addresses. */
static void sctp_free_local_addr_list(struct net *net)
{
struct sctp_sockaddr_entry *addr;
struct list_head *pos, *temp;
list_for_each_safe(pos, temp, &net->sctp.local_addr_list) {
addr = list_entry(pos, struct sctp_sockaddr_entry, list);
list_del(pos);
kfree(addr);
}
}
/* Copy the local addresses which are valid for 'scope' into 'bp'. */
int sctp_copy_local_addr_list(struct net *net, struct sctp_bind_addr *bp,
enum sctp_scope scope, gfp_t gfp, int copy_flags)
{
struct sctp_sockaddr_entry *addr;
union sctp_addr laddr;
int error = 0;
rcu_read_lock();
list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) {
if (!addr->valid)
continue;
if (!sctp_in_scope(net, &addr->a, scope))
continue;
/* Now that the address is in scope, check to see if
* the address type is really supported by the local
* sock as well as the remote peer.
*/
if (addr->a.sa.sa_family == AF_INET &&
(!(copy_flags & SCTP_ADDR4_ALLOWED) ||
!(copy_flags & SCTP_ADDR4_PEERSUPP)))
continue;
if (addr->a.sa.sa_family == AF_INET6 &&
(!(copy_flags & SCTP_ADDR6_ALLOWED) ||
!(copy_flags & SCTP_ADDR6_PEERSUPP)))
continue;
laddr = addr->a;
/* also works for setting ipv6 address port */
laddr.v4.sin_port = htons(bp->port);
if (sctp_bind_addr_state(bp, &laddr) != -1)
continue;
error = sctp_add_bind_addr(bp, &addr->a, sizeof(addr->a),
SCTP_ADDR_SRC, GFP_ATOMIC);
if (error)
break;
}
rcu_read_unlock();
return error;
}
/* Copy over any ip options */
static void sctp_v4_copy_ip_options(struct sock *sk, struct sock *newsk)
{
struct inet_sock *newinet, *inet = inet_sk(sk);
struct ip_options_rcu *inet_opt, *newopt = NULL;
newinet = inet_sk(newsk);
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt) {
newopt = sock_kmalloc(newsk, sizeof(*inet_opt) +
inet_opt->opt.optlen, GFP_ATOMIC);
if (newopt)
memcpy(newopt, inet_opt, sizeof(*inet_opt) +
inet_opt->opt.optlen);
else
pr_err("%s: Failed to copy ip options\n", __func__);
}
RCU_INIT_POINTER(newinet->inet_opt, newopt);
rcu_read_unlock();
}
/* Account for the IP options */
static int sctp_v4_ip_options_len(struct sock *sk)
{
struct inet_sock *inet = inet_sk(sk);
struct ip_options_rcu *inet_opt;
int len = 0;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt)
len = inet_opt->opt.optlen;
rcu_read_unlock();
return len;
}
/* Initialize a sctp_addr from in incoming skb. */
static void sctp_v4_from_skb(union sctp_addr *addr, struct sk_buff *skb,
int is_saddr)
{
/* Always called on head skb, so this is safe */
struct sctphdr *sh = sctp_hdr(skb);
struct sockaddr_in *sa = &addr->v4;
addr->v4.sin_family = AF_INET;
if (is_saddr) {
sa->sin_port = sh->source;
sa->sin_addr.s_addr = ip_hdr(skb)->saddr;
} else {
sa->sin_port = sh->dest;
sa->sin_addr.s_addr = ip_hdr(skb)->daddr;
}
memset(sa->sin_zero, 0, sizeof(sa->sin_zero));
}
/* Initialize an sctp_addr from a socket. */
static void sctp_v4_from_sk(union sctp_addr *addr, struct sock *sk)
{
addr->v4.sin_family = AF_INET;
addr->v4.sin_port = 0;
addr->v4.sin_addr.s_addr = inet_sk(sk)->inet_rcv_saddr;
memset(addr->v4.sin_zero, 0, sizeof(addr->v4.sin_zero));
}
/* Initialize sk->sk_rcv_saddr from sctp_addr. */
static void sctp_v4_to_sk_saddr(union sctp_addr *addr, struct sock *sk)
{
inet_sk(sk)->inet_rcv_saddr = addr->v4.sin_addr.s_addr;
}
/* Initialize sk->sk_daddr from sctp_addr. */
static void sctp_v4_to_sk_daddr(union sctp_addr *addr, struct sock *sk)
{
inet_sk(sk)->inet_daddr = addr->v4.sin_addr.s_addr;
}
/* Initialize a sctp_addr from an address parameter. */
static bool sctp_v4_from_addr_param(union sctp_addr *addr,
union sctp_addr_param *param,
__be16 port, int iif)
{
if (ntohs(param->v4.param_hdr.length) < sizeof(struct sctp_ipv4addr_param))
return false;
addr->v4.sin_family = AF_INET;
addr->v4.sin_port = port;
addr->v4.sin_addr.s_addr = param->v4.addr.s_addr;
memset(addr->v4.sin_zero, 0, sizeof(addr->v4.sin_zero));
return true;
}
/* Initialize an address parameter from a sctp_addr and return the length
* of the address parameter.
*/
static int sctp_v4_to_addr_param(const union sctp_addr *addr,
union sctp_addr_param *param)
{
int length = sizeof(struct sctp_ipv4addr_param);
param->v4.param_hdr.type = SCTP_PARAM_IPV4_ADDRESS;
param->v4.param_hdr.length = htons(length);
param->v4.addr.s_addr = addr->v4.sin_addr.s_addr;
return length;
}
/* Initialize a sctp_addr from a dst_entry. */
static void sctp_v4_dst_saddr(union sctp_addr *saddr, struct flowi4 *fl4,
__be16 port)
{
saddr->v4.sin_family = AF_INET;
saddr->v4.sin_port = port;
saddr->v4.sin_addr.s_addr = fl4->saddr;
memset(saddr->v4.sin_zero, 0, sizeof(saddr->v4.sin_zero));
}
/* Compare two addresses exactly. */
static int sctp_v4_cmp_addr(const union sctp_addr *addr1,
const union sctp_addr *addr2)
{
if (addr1->sa.sa_family != addr2->sa.sa_family)
return 0;
if (addr1->v4.sin_port != addr2->v4.sin_port)
return 0;
if (addr1->v4.sin_addr.s_addr != addr2->v4.sin_addr.s_addr)
return 0;
return 1;
}
/* Initialize addr struct to INADDR_ANY. */
static void sctp_v4_inaddr_any(union sctp_addr *addr, __be16 port)
{
addr->v4.sin_family = AF_INET;
addr->v4.sin_addr.s_addr = htonl(INADDR_ANY);
addr->v4.sin_port = port;
memset(addr->v4.sin_zero, 0, sizeof(addr->v4.sin_zero));
}
/* Is this a wildcard address? */
static int sctp_v4_is_any(const union sctp_addr *addr)
{
return htonl(INADDR_ANY) == addr->v4.sin_addr.s_addr;
}
/* This function checks if the address is a valid address to be used for
* SCTP binding.
*
* Output:
* Return 0 - If the address is a non-unicast or an illegal address.
* Return 1 - If the address is a unicast.
*/
static int sctp_v4_addr_valid(union sctp_addr *addr,
struct sctp_sock *sp,
const struct sk_buff *skb)
{
/* IPv4 addresses not allowed */
if (sp && ipv6_only_sock(sctp_opt2sk(sp)))
return 0;
/* Is this a non-unicast address or a unusable SCTP address? */
if (IS_IPV4_UNUSABLE_ADDRESS(addr->v4.sin_addr.s_addr))
return 0;
/* Is this a broadcast address? */
if (skb && skb_rtable(skb)->rt_flags & RTCF_BROADCAST)
return 0;
return 1;
}
/* Should this be available for binding? */
static int sctp_v4_available(union sctp_addr *addr, struct sctp_sock *sp)
{
struct sock *sk = &sp->inet.sk;
struct net *net = sock_net(sk);
int tb_id = RT_TABLE_LOCAL;
int ret;
tb_id = l3mdev_fib_table_by_index(net, sk->sk_bound_dev_if) ?: tb_id;
ret = inet_addr_type_table(net, addr->v4.sin_addr.s_addr, tb_id);
if (addr->v4.sin_addr.s_addr != htonl(INADDR_ANY) &&
ret != RTN_LOCAL &&
!inet_test_bit(FREEBIND, sk) &&
!READ_ONCE(net->ipv4.sysctl_ip_nonlocal_bind))
return 0;
if (ipv6_only_sock(sctp_opt2sk(sp)))
return 0;
return 1;
}
/* Checking the loopback, private and other address scopes as defined in
* RFC 1918. The IPv4 scoping is based on the draft for SCTP IPv4
* scoping <draft-stewart-tsvwg-sctp-ipv4-00.txt>.
*
* Level 0 - unusable SCTP addresses
* Level 1 - loopback address
* Level 2 - link-local addresses
* Level 3 - private addresses.
* Level 4 - global addresses
* For INIT and INIT-ACK address list, let L be the level of
* requested destination address, sender and receiver
* SHOULD include all of its addresses with level greater
* than or equal to L.
*
* IPv4 scoping can be controlled through sysctl option
* net.sctp.addr_scope_policy
*/
static enum sctp_scope sctp_v4_scope(union sctp_addr *addr)
{
enum sctp_scope retval;
/* Check for unusable SCTP addresses. */
if (IS_IPV4_UNUSABLE_ADDRESS(addr->v4.sin_addr.s_addr)) {
retval = SCTP_SCOPE_UNUSABLE;
} else if (ipv4_is_loopback(addr->v4.sin_addr.s_addr)) {
retval = SCTP_SCOPE_LOOPBACK;
} else if (ipv4_is_linklocal_169(addr->v4.sin_addr.s_addr)) {
retval = SCTP_SCOPE_LINK;
} else if (ipv4_is_private_10(addr->v4.sin_addr.s_addr) ||
ipv4_is_private_172(addr->v4.sin_addr.s_addr) ||
ipv4_is_private_192(addr->v4.sin_addr.s_addr) ||
ipv4_is_test_198(addr->v4.sin_addr.s_addr)) {
retval = SCTP_SCOPE_PRIVATE;
} else {
retval = SCTP_SCOPE_GLOBAL;
}
return retval;
}
/* Returns a valid dst cache entry for the given source and destination ip
* addresses. If an association is passed, trys to get a dst entry with a
* source address that matches an address in the bind address list.
*/
static void sctp_v4_get_dst(struct sctp_transport *t, union sctp_addr *saddr,
struct flowi *fl, struct sock *sk)
{
struct sctp_association *asoc = t->asoc;
struct rtable *rt;
struct flowi _fl;
struct flowi4 *fl4 = &_fl.u.ip4;
struct sctp_bind_addr *bp;
struct sctp_sockaddr_entry *laddr;
struct dst_entry *dst = NULL;
union sctp_addr *daddr = &t->ipaddr;
union sctp_addr dst_saddr;
__u8 tos = inet_sk(sk)->tos;
if (t->dscp & SCTP_DSCP_SET_MASK)
tos = t->dscp & SCTP_DSCP_VAL_MASK;
memset(&_fl, 0x0, sizeof(_fl));
fl4->daddr = daddr->v4.sin_addr.s_addr;
fl4->fl4_dport = daddr->v4.sin_port;
fl4->flowi4_proto = IPPROTO_SCTP;
if (asoc) {
fl4->flowi4_tos = RT_TOS(tos);
fl4->flowi4_scope = ip_sock_rt_scope(asoc->base.sk);
fl4->flowi4_oif = asoc->base.sk->sk_bound_dev_if;
fl4->fl4_sport = htons(asoc->base.bind_addr.port);
}
if (saddr) {
fl4->saddr = saddr->v4.sin_addr.s_addr;
if (!fl4->fl4_sport)
fl4->fl4_sport = saddr->v4.sin_port;
}
pr_debug("%s: dst:%pI4, src:%pI4 - ", __func__, &fl4->daddr,
&fl4->saddr);
rt = ip_route_output_key(sock_net(sk), fl4);
if (!IS_ERR(rt)) {
dst = &rt->dst;
t->dst = dst;
memcpy(fl, &_fl, sizeof(_fl));
}
/* If there is no association or if a source address is passed, no
* more validation is required.
*/
if (!asoc || saddr)
goto out;
bp = &asoc->base.bind_addr;
if (dst) {
/* Walk through the bind address list and look for a bind
* address that matches the source address of the returned dst.
*/
sctp_v4_dst_saddr(&dst_saddr, fl4, htons(bp->port));
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
if (!laddr->valid || (laddr->state == SCTP_ADDR_DEL) ||
(laddr->state != SCTP_ADDR_SRC &&
!asoc->src_out_of_asoc_ok))
continue;
if (sctp_v4_cmp_addr(&dst_saddr, &laddr->a))
goto out_unlock;
}
rcu_read_unlock();
/* None of the bound addresses match the source address of the
* dst. So release it.
*/
dst_release(dst);
dst = NULL;
}
/* Walk through the bind address list and try to get a dst that
* matches a bind address as the source address.
*/
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
struct net_device *odev;
if (!laddr->valid)
continue;
if (laddr->state != SCTP_ADDR_SRC ||
AF_INET != laddr->a.sa.sa_family)
continue;
fl4->fl4_sport = laddr->a.v4.sin_port;
flowi4_update_output(fl4, asoc->base.sk->sk_bound_dev_if,
daddr->v4.sin_addr.s_addr,
laddr->a.v4.sin_addr.s_addr);
rt = ip_route_output_key(sock_net(sk), fl4);
if (IS_ERR(rt))
continue;
/* Ensure the src address belongs to the output
* interface.
*/
odev = __ip_dev_find(sock_net(sk), laddr->a.v4.sin_addr.s_addr,
false);
if (!odev || odev->ifindex != fl4->flowi4_oif) {
if (!dst) {
dst = &rt->dst;
t->dst = dst;
memcpy(fl, &_fl, sizeof(_fl));
} else {
dst_release(&rt->dst);
}
continue;
}
dst_release(dst);
dst = &rt->dst;
t->dst = dst;
memcpy(fl, &_fl, sizeof(_fl));
break;
}
out_unlock:
rcu_read_unlock();
out:
if (dst) {
pr_debug("rt_dst:%pI4, rt_src:%pI4\n",
&fl->u.ip4.daddr, &fl->u.ip4.saddr);
} else {
t->dst = NULL;
pr_debug("no route\n");
}
}
/* For v4, the source address is cached in the route entry(dst). So no need
* to cache it separately and hence this is an empty routine.
*/
static void sctp_v4_get_saddr(struct sctp_sock *sk,
struct sctp_transport *t,
struct flowi *fl)
{
union sctp_addr *saddr = &t->saddr;
struct rtable *rt = (struct rtable *)t->dst;
if (rt) {
saddr->v4.sin_family = AF_INET;
saddr->v4.sin_addr.s_addr = fl->u.ip4.saddr;
}
}
/* What interface did this skb arrive on? */
static int sctp_v4_skb_iif(const struct sk_buff *skb)
{
return inet_iif(skb);
}
static int sctp_v4_skb_sdif(const struct sk_buff *skb)
{
return inet_sdif(skb);
}
/* Was this packet marked by Explicit Congestion Notification? */
static int sctp_v4_is_ce(const struct sk_buff *skb)
{
return INET_ECN_is_ce(ip_hdr(skb)->tos);
}
/* Create and initialize a new sk for the socket returned by accept(). */
static struct sock *sctp_v4_create_accept_sk(struct sock *sk,
struct sctp_association *asoc,
bool kern)
{
struct sock *newsk = sk_alloc(sock_net(sk), PF_INET, GFP_KERNEL,
sk->sk_prot, kern);
struct inet_sock *newinet;
if (!newsk)
goto out;
sock_init_data(NULL, newsk);
sctp_copy_sock(newsk, sk, asoc);
sock_reset_flag(newsk, SOCK_ZAPPED);
sctp_v4_copy_ip_options(sk, newsk);
newinet = inet_sk(newsk);
newinet->inet_daddr = asoc->peer.primary_addr.v4.sin_addr.s_addr;
if (newsk->sk_prot->init(newsk)) {
sk_common_release(newsk);
newsk = NULL;
}
out:
return newsk;
}
static int sctp_v4_addr_to_user(struct sctp_sock *sp, union sctp_addr *addr)
{
/* No address mapping for V4 sockets */
memset(addr->v4.sin_zero, 0, sizeof(addr->v4.sin_zero));
return sizeof(struct sockaddr_in);
}
/* Dump the v4 addr to the seq file. */
static void sctp_v4_seq_dump_addr(struct seq_file *seq, union sctp_addr *addr)
{
seq_printf(seq, "%pI4 ", &addr->v4.sin_addr);
}
static void sctp_v4_ecn_capable(struct sock *sk)
{
INET_ECN_xmit(sk);
}
static void sctp_addr_wq_timeout_handler(struct timer_list *t)
{
struct net *net = from_timer(net, t, sctp.addr_wq_timer);
struct sctp_sockaddr_entry *addrw, *temp;
struct sctp_sock *sp;
spin_lock_bh(&net->sctp.addr_wq_lock);
list_for_each_entry_safe(addrw, temp, &net->sctp.addr_waitq, list) {
pr_debug("%s: the first ent in wq:%p is addr:%pISc for cmd:%d at "
"entry:%p\n", __func__, &net->sctp.addr_waitq, &addrw->a.sa,
addrw->state, addrw);
#if IS_ENABLED(CONFIG_IPV6)
/* Now we send an ASCONF for each association */
/* Note. we currently don't handle link local IPv6 addressees */
if (addrw->a.sa.sa_family == AF_INET6) {
struct in6_addr *in6;
if (ipv6_addr_type(&addrw->a.v6.sin6_addr) &
IPV6_ADDR_LINKLOCAL)
goto free_next;
in6 = (struct in6_addr *)&addrw->a.v6.sin6_addr;
if (ipv6_chk_addr(net, in6, NULL, 0) == 0 &&
addrw->state == SCTP_ADDR_NEW) {
unsigned long timeo_val;
pr_debug("%s: this is on DAD, trying %d sec "
"later\n", __func__,
SCTP_ADDRESS_TICK_DELAY);
timeo_val = jiffies;
timeo_val += msecs_to_jiffies(SCTP_ADDRESS_TICK_DELAY);
mod_timer(&net->sctp.addr_wq_timer, timeo_val);
break;
}
}
#endif
list_for_each_entry(sp, &net->sctp.auto_asconf_splist, auto_asconf_list) {
struct sock *sk;
sk = sctp_opt2sk(sp);
/* ignore bound-specific endpoints */
if (!sctp_is_ep_boundall(sk))
continue;
bh_lock_sock(sk);
if (sctp_asconf_mgmt(sp, addrw) < 0)
pr_debug("%s: sctp_asconf_mgmt failed\n", __func__);
bh_unlock_sock(sk);
}
#if IS_ENABLED(CONFIG_IPV6)
free_next:
#endif
list_del(&addrw->list);
kfree(addrw);
}
spin_unlock_bh(&net->sctp.addr_wq_lock);
}
static void sctp_free_addr_wq(struct net *net)
{
struct sctp_sockaddr_entry *addrw;
struct sctp_sockaddr_entry *temp;
spin_lock_bh(&net->sctp.addr_wq_lock);
del_timer(&net->sctp.addr_wq_timer);
list_for_each_entry_safe(addrw, temp, &net->sctp.addr_waitq, list) {
list_del(&addrw->list);
kfree(addrw);
}
spin_unlock_bh(&net->sctp.addr_wq_lock);
}
/* lookup the entry for the same address in the addr_waitq
* sctp_addr_wq MUST be locked
*/
static struct sctp_sockaddr_entry *sctp_addr_wq_lookup(struct net *net,
struct sctp_sockaddr_entry *addr)
{
struct sctp_sockaddr_entry *addrw;
list_for_each_entry(addrw, &net->sctp.addr_waitq, list) {
if (addrw->a.sa.sa_family != addr->a.sa.sa_family)
continue;
if (addrw->a.sa.sa_family == AF_INET) {
if (addrw->a.v4.sin_addr.s_addr ==
addr->a.v4.sin_addr.s_addr)
return addrw;
} else if (addrw->a.sa.sa_family == AF_INET6) {
if (ipv6_addr_equal(&addrw->a.v6.sin6_addr,
&addr->a.v6.sin6_addr))
return addrw;
}
}
return NULL;
}
void sctp_addr_wq_mgmt(struct net *net, struct sctp_sockaddr_entry *addr, int cmd)
{
struct sctp_sockaddr_entry *addrw;
unsigned long timeo_val;
/* first, we check if an opposite message already exist in the queue.
* If we found such message, it is removed.
* This operation is a bit stupid, but the DHCP client attaches the
* new address after a couple of addition and deletion of that address
*/
spin_lock_bh(&net->sctp.addr_wq_lock);
/* Offsets existing events in addr_wq */
addrw = sctp_addr_wq_lookup(net, addr);
if (addrw) {
if (addrw->state != cmd) {
pr_debug("%s: offsets existing entry for %d, addr:%pISc "
"in wq:%p\n", __func__, addrw->state, &addrw->a.sa,
&net->sctp.addr_waitq);
list_del(&addrw->list);
kfree(addrw);
}
spin_unlock_bh(&net->sctp.addr_wq_lock);
return;
}
/* OK, we have to add the new address to the wait queue */
addrw = kmemdup(addr, sizeof(struct sctp_sockaddr_entry), GFP_ATOMIC);
if (addrw == NULL) {
spin_unlock_bh(&net->sctp.addr_wq_lock);
return;
}
addrw->state = cmd;
list_add_tail(&addrw->list, &net->sctp.addr_waitq);
pr_debug("%s: add new entry for cmd:%d, addr:%pISc in wq:%p\n",
__func__, addrw->state, &addrw->a.sa, &net->sctp.addr_waitq);
if (!timer_pending(&net->sctp.addr_wq_timer)) {
timeo_val = jiffies;
timeo_val += msecs_to_jiffies(SCTP_ADDRESS_TICK_DELAY);
mod_timer(&net->sctp.addr_wq_timer, timeo_val);
}
spin_unlock_bh(&net->sctp.addr_wq_lock);
}
/* Event handler for inet address addition/deletion events.
* The sctp_local_addr_list needs to be protocted by a spin lock since
* multiple notifiers (say IPv4 and IPv6) may be running at the same
* time and thus corrupt the list.
* The reader side is protected with RCU.
*/
static int sctp_inetaddr_event(struct notifier_block *this, unsigned long ev,
void *ptr)
{
struct in_ifaddr *ifa = (struct in_ifaddr *)ptr;
struct sctp_sockaddr_entry *addr = NULL;
struct sctp_sockaddr_entry *temp;
struct net *net = dev_net(ifa->ifa_dev->dev);
int found = 0;
switch (ev) {
case NETDEV_UP:
addr = kzalloc(sizeof(*addr), GFP_ATOMIC);
if (addr) {
addr->a.v4.sin_family = AF_INET;
addr->a.v4.sin_addr.s_addr = ifa->ifa_local;
addr->valid = 1;
spin_lock_bh(&net->sctp.local_addr_lock);
list_add_tail_rcu(&addr->list, &net->sctp.local_addr_list);
sctp_addr_wq_mgmt(net, addr, SCTP_ADDR_NEW);
spin_unlock_bh(&net->sctp.local_addr_lock);
}
break;
case NETDEV_DOWN:
spin_lock_bh(&net->sctp.local_addr_lock);
list_for_each_entry_safe(addr, temp,
&net->sctp.local_addr_list, list) {
if (addr->a.sa.sa_family == AF_INET &&
addr->a.v4.sin_addr.s_addr ==
ifa->ifa_local) {
sctp_addr_wq_mgmt(net, addr, SCTP_ADDR_DEL);
found = 1;
addr->valid = 0;
list_del_rcu(&addr->list);
break;
}
}
spin_unlock_bh(&net->sctp.local_addr_lock);
if (found)
kfree_rcu(addr, rcu);
break;
}
return NOTIFY_DONE;
}
/*
* Initialize the control inode/socket with a control endpoint data
* structure. This endpoint is reserved exclusively for the OOTB processing.
*/
static int sctp_ctl_sock_init(struct net *net)
{
int err;
sa_family_t family = PF_INET;
if (sctp_get_pf_specific(PF_INET6))
family = PF_INET6;
err = inet_ctl_sock_create(&net->sctp.ctl_sock, family,
SOCK_SEQPACKET, IPPROTO_SCTP, net);
/* If IPv6 socket could not be created, try the IPv4 socket */
if (err < 0 && family == PF_INET6)
err = inet_ctl_sock_create(&net->sctp.ctl_sock, AF_INET,
SOCK_SEQPACKET, IPPROTO_SCTP,
net);
if (err < 0) {
pr_err("Failed to create the SCTP control socket\n");
return err;
}
return 0;
}
static int sctp_udp_rcv(struct sock *sk, struct sk_buff *skb)
{
SCTP_INPUT_CB(skb)->encap_port = udp_hdr(skb)->source;
skb_set_transport_header(skb, sizeof(struct udphdr));
sctp_rcv(skb);
return 0;
}
int sctp_udp_sock_start(struct net *net)
{
struct udp_tunnel_sock_cfg tuncfg = {NULL};
struct udp_port_cfg udp_conf = {0};
struct socket *sock;
int err;
udp_conf.family = AF_INET;
udp_conf.local_ip.s_addr = htonl(INADDR_ANY);
udp_conf.local_udp_port = htons(net->sctp.udp_port);
err = udp_sock_create(net, &udp_conf, &sock);
if (err) {
pr_err("Failed to create the SCTP UDP tunneling v4 sock\n");
return err;
}
tuncfg.encap_type = 1;
tuncfg.encap_rcv = sctp_udp_rcv;
tuncfg.encap_err_lookup = sctp_udp_v4_err;
setup_udp_tunnel_sock(net, sock, &tuncfg);
net->sctp.udp4_sock = sock->sk;
#if IS_ENABLED(CONFIG_IPV6)
memset(&udp_conf, 0, sizeof(udp_conf));
udp_conf.family = AF_INET6;
udp_conf.local_ip6 = in6addr_any;
udp_conf.local_udp_port = htons(net->sctp.udp_port);
udp_conf.use_udp6_rx_checksums = true;
udp_conf.ipv6_v6only = true;
err = udp_sock_create(net, &udp_conf, &sock);
if (err) {
pr_err("Failed to create the SCTP UDP tunneling v6 sock\n");
udp_tunnel_sock_release(net->sctp.udp4_sock->sk_socket);
net->sctp.udp4_sock = NULL;
return err;
}
tuncfg.encap_type = 1;
tuncfg.encap_rcv = sctp_udp_rcv;
tuncfg.encap_err_lookup = sctp_udp_v6_err;
setup_udp_tunnel_sock(net, sock, &tuncfg);
net->sctp.udp6_sock = sock->sk;
#endif
return 0;
}
void sctp_udp_sock_stop(struct net *net)
{
if (net->sctp.udp4_sock) {
udp_tunnel_sock_release(net->sctp.udp4_sock->sk_socket);
net->sctp.udp4_sock = NULL;
}
if (net->sctp.udp6_sock) {
udp_tunnel_sock_release(net->sctp.udp6_sock->sk_socket);
net->sctp.udp6_sock = NULL;
}
}
/* Register address family specific functions. */
int sctp_register_af(struct sctp_af *af)
{
switch (af->sa_family) {
case AF_INET:
if (sctp_af_v4_specific)
return 0;
sctp_af_v4_specific = af;
break;
case AF_INET6:
if (sctp_af_v6_specific)
return 0;
sctp_af_v6_specific = af;
break;
default:
return 0;
}
INIT_LIST_HEAD(&af->list);
list_add_tail(&af->list, &sctp_address_families);
return 1;
}
/* Get the table of functions for manipulating a particular address
* family.
*/
struct sctp_af *sctp_get_af_specific(sa_family_t family)
{
switch (family) {
case AF_INET:
return sctp_af_v4_specific;
case AF_INET6:
return sctp_af_v6_specific;
default:
return NULL;
}
}
/* Common code to initialize a AF_INET msg_name. */
static void sctp_inet_msgname(char *msgname, int *addr_len)
{
struct sockaddr_in *sin;
sin = (struct sockaddr_in *)msgname;
*addr_len = sizeof(struct sockaddr_in);
sin->sin_family = AF_INET;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
}
/* Copy the primary address of the peer primary address as the msg_name. */
static void sctp_inet_event_msgname(struct sctp_ulpevent *event, char *msgname,
int *addr_len)
{
struct sockaddr_in *sin, *sinfrom;
if (msgname) {
struct sctp_association *asoc;
asoc = event->asoc;
sctp_inet_msgname(msgname, addr_len);
sin = (struct sockaddr_in *)msgname;
sinfrom = &asoc->peer.primary_addr.v4;
sin->sin_port = htons(asoc->peer.port);
sin->sin_addr.s_addr = sinfrom->sin_addr.s_addr;
}
}
/* Initialize and copy out a msgname from an inbound skb. */
static void sctp_inet_skb_msgname(struct sk_buff *skb, char *msgname, int *len)
{
if (msgname) {
struct sctphdr *sh = sctp_hdr(skb);
struct sockaddr_in *sin = (struct sockaddr_in *)msgname;
sctp_inet_msgname(msgname, len);
sin->sin_port = sh->source;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
}
}
/* Do we support this AF? */
static int sctp_inet_af_supported(sa_family_t family, struct sctp_sock *sp)
{
/* PF_INET only supports AF_INET addresses. */
return AF_INET == family;
}
/* Address matching with wildcards allowed. */
static int sctp_inet_cmp_addr(const union sctp_addr *addr1,
const union sctp_addr *addr2,
struct sctp_sock *opt)
{
/* PF_INET only supports AF_INET addresses. */
if (addr1->sa.sa_family != addr2->sa.sa_family)
return 0;
if (htonl(INADDR_ANY) == addr1->v4.sin_addr.s_addr ||
htonl(INADDR_ANY) == addr2->v4.sin_addr.s_addr)
return 1;
if (addr1->v4.sin_addr.s_addr == addr2->v4.sin_addr.s_addr)
return 1;
return 0;
}
/* Verify that provided sockaddr looks bindable. Common verification has
* already been taken care of.
*/
static int sctp_inet_bind_verify(struct sctp_sock *opt, union sctp_addr *addr)
{
return sctp_v4_available(addr, opt);
}
/* Verify that sockaddr looks sendable. Common verification has already
* been taken care of.
*/
static int sctp_inet_send_verify(struct sctp_sock *opt, union sctp_addr *addr)
{
return 1;
}
/* Fill in Supported Address Type information for INIT and INIT-ACK
* chunks. Returns number of addresses supported.
*/
static int sctp_inet_supported_addrs(const struct sctp_sock *opt,
__be16 *types)
{
types[0] = SCTP_PARAM_IPV4_ADDRESS;
return 1;
}
/* Wrapper routine that calls the ip transmit routine. */
static inline int sctp_v4_xmit(struct sk_buff *skb, struct sctp_transport *t)
{
struct dst_entry *dst = dst_clone(t->dst);
struct flowi4 *fl4 = &t->fl.u.ip4;
struct sock *sk = skb->sk;
struct inet_sock *inet = inet_sk(sk);
__u8 dscp = inet->tos;
__be16 df = 0;
pr_debug("%s: skb:%p, len:%d, src:%pI4, dst:%pI4\n", __func__, skb,
skb->len, &fl4->saddr, &fl4->daddr);
if (t->dscp & SCTP_DSCP_SET_MASK)
dscp = t->dscp & SCTP_DSCP_VAL_MASK;
inet->pmtudisc = t->param_flags & SPP_PMTUD_ENABLE ? IP_PMTUDISC_DO
: IP_PMTUDISC_DONT;
SCTP_INC_STATS(sock_net(sk), SCTP_MIB_OUTSCTPPACKS);
if (!t->encap_port || !sctp_sk(sk)->udp_port) {
skb_dst_set(skb, dst);
return __ip_queue_xmit(sk, skb, &t->fl, dscp);
}
if (skb_is_gso(skb))
skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_TUNNEL_CSUM;
if (ip_dont_fragment(sk, dst) && !skb->ignore_df)
df = htons(IP_DF);
skb->encapsulation = 1;
skb_reset_inner_mac_header(skb);
skb_reset_inner_transport_header(skb);
skb_set_inner_ipproto(skb, IPPROTO_SCTP);
udp_tunnel_xmit_skb((struct rtable *)dst, sk, skb, fl4->saddr,
fl4->daddr, dscp, ip4_dst_hoplimit(dst), df,
sctp_sk(sk)->udp_port, t->encap_port, false, false);
return 0;
}
static struct sctp_af sctp_af_inet;
static struct sctp_pf sctp_pf_inet = {
.event_msgname = sctp_inet_event_msgname,
.skb_msgname = sctp_inet_skb_msgname,
.af_supported = sctp_inet_af_supported,
.cmp_addr = sctp_inet_cmp_addr,
.bind_verify = sctp_inet_bind_verify,
.send_verify = sctp_inet_send_verify,
.supported_addrs = sctp_inet_supported_addrs,
.create_accept_sk = sctp_v4_create_accept_sk,
.addr_to_user = sctp_v4_addr_to_user,
.to_sk_saddr = sctp_v4_to_sk_saddr,
.to_sk_daddr = sctp_v4_to_sk_daddr,
.copy_ip_options = sctp_v4_copy_ip_options,
.af = &sctp_af_inet
};
/* Notifier for inetaddr addition/deletion events. */
static struct notifier_block sctp_inetaddr_notifier = {
.notifier_call = sctp_inetaddr_event,
};
/* Socket operations. */
static const struct proto_ops inet_seqpacket_ops = {
.family = PF_INET,
.owner = THIS_MODULE,
.release = inet_release, /* Needs to be wrapped... */
.bind = inet_bind,
.connect = sctp_inet_connect,
.socketpair = sock_no_socketpair,
.accept = inet_accept,
.getname = inet_getname, /* Semantics are different. */
.poll = sctp_poll,
.ioctl = inet_ioctl,
.gettstamp = sock_gettstamp,
.listen = sctp_inet_listen,
.shutdown = inet_shutdown, /* Looks harmless. */
.setsockopt = sock_common_setsockopt, /* IP_SOL IP_OPTION is a problem */
.getsockopt = sock_common_getsockopt,
.sendmsg = inet_sendmsg,
.recvmsg = inet_recvmsg,
.mmap = sock_no_mmap,
};
/* Registration with AF_INET family. */
static struct inet_protosw sctp_seqpacket_protosw = {
.type = SOCK_SEQPACKET,
.protocol = IPPROTO_SCTP,
.prot = &sctp_prot,
.ops = &inet_seqpacket_ops,
.flags = SCTP_PROTOSW_FLAG
};
static struct inet_protosw sctp_stream_protosw = {
.type = SOCK_STREAM,
.protocol = IPPROTO_SCTP,
.prot = &sctp_prot,
.ops = &inet_seqpacket_ops,
.flags = SCTP_PROTOSW_FLAG
};
static int sctp4_rcv(struct sk_buff *skb)
{
SCTP_INPUT_CB(skb)->encap_port = 0;
return sctp_rcv(skb);
}
/* Register with IP layer. */
static const struct net_protocol sctp_protocol = {
.handler = sctp4_rcv,
.err_handler = sctp_v4_err,
.no_policy = 1,
.icmp_strict_tag_validation = 1,
};
/* IPv4 address related functions. */
static struct sctp_af sctp_af_inet = {
.sa_family = AF_INET,
.sctp_xmit = sctp_v4_xmit,
.setsockopt = ip_setsockopt,
.getsockopt = ip_getsockopt,
.get_dst = sctp_v4_get_dst,
.get_saddr = sctp_v4_get_saddr,
.copy_addrlist = sctp_v4_copy_addrlist,
.from_skb = sctp_v4_from_skb,
.from_sk = sctp_v4_from_sk,
.from_addr_param = sctp_v4_from_addr_param,
.to_addr_param = sctp_v4_to_addr_param,
.cmp_addr = sctp_v4_cmp_addr,
.addr_valid = sctp_v4_addr_valid,
.inaddr_any = sctp_v4_inaddr_any,
.is_any = sctp_v4_is_any,
.available = sctp_v4_available,
.scope = sctp_v4_scope,
.skb_iif = sctp_v4_skb_iif,
.skb_sdif = sctp_v4_skb_sdif,
.is_ce = sctp_v4_is_ce,
.seq_dump_addr = sctp_v4_seq_dump_addr,
.ecn_capable = sctp_v4_ecn_capable,
.net_header_len = sizeof(struct iphdr),
.sockaddr_len = sizeof(struct sockaddr_in),
.ip_options_len = sctp_v4_ip_options_len,
};
struct sctp_pf *sctp_get_pf_specific(sa_family_t family)
{
switch (family) {
case PF_INET:
return sctp_pf_inet_specific;
case PF_INET6:
return sctp_pf_inet6_specific;
default:
return NULL;
}
}
/* Register the PF specific function table. */
int sctp_register_pf(struct sctp_pf *pf, sa_family_t family)
{
switch (family) {
case PF_INET:
if (sctp_pf_inet_specific)
return 0;
sctp_pf_inet_specific = pf;
break;
case PF_INET6:
if (sctp_pf_inet6_specific)
return 0;
sctp_pf_inet6_specific = pf;
break;
default:
return 0;
}
return 1;
}
static inline int init_sctp_mibs(struct net *net)
{
net->sctp.sctp_statistics = alloc_percpu(struct sctp_mib);
if (!net->sctp.sctp_statistics)
return -ENOMEM;
return 0;
}
static inline void cleanup_sctp_mibs(struct net *net)
{
free_percpu(net->sctp.sctp_statistics);
}
static void sctp_v4_pf_init(void)
{
/* Initialize the SCTP specific PF functions. */
sctp_register_pf(&sctp_pf_inet, PF_INET);
sctp_register_af(&sctp_af_inet);
}
static void sctp_v4_pf_exit(void)
{
list_del(&sctp_af_inet.list);
}
static int sctp_v4_protosw_init(void)
{
int rc;
rc = proto_register(&sctp_prot, 1);
if (rc)
return rc;
/* Register SCTP(UDP and TCP style) with socket layer. */
inet_register_protosw(&sctp_seqpacket_protosw);
inet_register_protosw(&sctp_stream_protosw);
return 0;
}
static void sctp_v4_protosw_exit(void)
{
inet_unregister_protosw(&sctp_stream_protosw);
inet_unregister_protosw(&sctp_seqpacket_protosw);
proto_unregister(&sctp_prot);
}
static int sctp_v4_add_protocol(void)
{
/* Register notifier for inet address additions/deletions. */
register_inetaddr_notifier(&sctp_inetaddr_notifier);
/* Register SCTP with inet layer. */
if (inet_add_protocol(&sctp_protocol, IPPROTO_SCTP) < 0)
return -EAGAIN;
return 0;
}
static void sctp_v4_del_protocol(void)
{
inet_del_protocol(&sctp_protocol, IPPROTO_SCTP);
unregister_inetaddr_notifier(&sctp_inetaddr_notifier);
}
static int __net_init sctp_defaults_init(struct net *net)
{
int status;
/*
* 14. Suggested SCTP Protocol Parameter Values
*/
/* The following protocol parameters are RECOMMENDED: */
/* RTO.Initial - 3 seconds */
net->sctp.rto_initial = SCTP_RTO_INITIAL;
/* RTO.Min - 1 second */
net->sctp.rto_min = SCTP_RTO_MIN;
/* RTO.Max - 60 seconds */
net->sctp.rto_max = SCTP_RTO_MAX;
/* RTO.Alpha - 1/8 */
net->sctp.rto_alpha = SCTP_RTO_ALPHA;
/* RTO.Beta - 1/4 */
net->sctp.rto_beta = SCTP_RTO_BETA;
/* Valid.Cookie.Life - 60 seconds */
net->sctp.valid_cookie_life = SCTP_DEFAULT_COOKIE_LIFE;
/* Whether Cookie Preservative is enabled(1) or not(0) */
net->sctp.cookie_preserve_enable = 1;
/* Default sctp sockets to use md5 as their hmac alg */
#if defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_MD5)
net->sctp.sctp_hmac_alg = "md5";
#elif defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_SHA1)
net->sctp.sctp_hmac_alg = "sha1";
#else
net->sctp.sctp_hmac_alg = NULL;
#endif
/* Max.Burst - 4 */
net->sctp.max_burst = SCTP_DEFAULT_MAX_BURST;
/* Disable of Primary Path Switchover by default */
net->sctp.ps_retrans = SCTP_PS_RETRANS_MAX;
/* Enable pf state by default */
net->sctp.pf_enable = 1;
/* Ignore pf exposure feature by default */
net->sctp.pf_expose = SCTP_PF_EXPOSE_UNSET;
/* Association.Max.Retrans - 10 attempts
* Path.Max.Retrans - 5 attempts (per destination address)
* Max.Init.Retransmits - 8 attempts
*/
net->sctp.max_retrans_association = 10;
net->sctp.max_retrans_path = 5;
net->sctp.max_retrans_init = 8;
/* Sendbuffer growth - do per-socket accounting */
net->sctp.sndbuf_policy = 0;
/* Rcvbuffer growth - do per-socket accounting */
net->sctp.rcvbuf_policy = 0;
/* HB.interval - 30 seconds */
net->sctp.hb_interval = SCTP_DEFAULT_TIMEOUT_HEARTBEAT;
/* delayed SACK timeout */
net->sctp.sack_timeout = SCTP_DEFAULT_TIMEOUT_SACK;
/* Disable ADDIP by default. */
net->sctp.addip_enable = 0;
net->sctp.addip_noauth = 0;
net->sctp.default_auto_asconf = 0;
/* Enable PR-SCTP by default. */
net->sctp.prsctp_enable = 1;
/* Disable RECONF by default. */
net->sctp.reconf_enable = 0;
/* Disable AUTH by default. */
net->sctp.auth_enable = 0;
/* Enable ECN by default. */
net->sctp.ecn_enable = 1;
/* Set UDP tunneling listening port to 0 by default */
net->sctp.udp_port = 0;
/* Set remote encap port to 0 by default */
net->sctp.encap_port = 0;
/* Set SCOPE policy to enabled */
net->sctp.scope_policy = SCTP_SCOPE_POLICY_ENABLE;
/* Set the default rwnd update threshold */
net->sctp.rwnd_upd_shift = SCTP_DEFAULT_RWND_SHIFT;
/* Initialize maximum autoclose timeout. */
net->sctp.max_autoclose = INT_MAX / HZ;
#ifdef CONFIG_NET_L3_MASTER_DEV
net->sctp.l3mdev_accept = 1;
#endif
status = sctp_sysctl_net_register(net);
if (status)
goto err_sysctl_register;
/* Allocate and initialise sctp mibs. */
status = init_sctp_mibs(net);
if (status)
goto err_init_mibs;
#ifdef CONFIG_PROC_FS
/* Initialize proc fs directory. */
status = sctp_proc_init(net);
if (status)
goto err_init_proc;
#endif
sctp_dbg_objcnt_init(net);
/* Initialize the local address list. */
INIT_LIST_HEAD(&net->sctp.local_addr_list);
spin_lock_init(&net->sctp.local_addr_lock);
sctp_get_local_addr_list(net);
/* Initialize the address event list */
INIT_LIST_HEAD(&net->sctp.addr_waitq);
INIT_LIST_HEAD(&net->sctp.auto_asconf_splist);
spin_lock_init(&net->sctp.addr_wq_lock);
net->sctp.addr_wq_timer.expires = 0;
timer_setup(&net->sctp.addr_wq_timer, sctp_addr_wq_timeout_handler, 0);
return 0;
#ifdef CONFIG_PROC_FS
err_init_proc:
cleanup_sctp_mibs(net);
#endif
err_init_mibs:
sctp_sysctl_net_unregister(net);
err_sysctl_register:
return status;
}
static void __net_exit sctp_defaults_exit(struct net *net)
{
/* Free the local address list */
sctp_free_addr_wq(net);
sctp_free_local_addr_list(net);
#ifdef CONFIG_PROC_FS
remove_proc_subtree("sctp", net->proc_net);
net->sctp.proc_net_sctp = NULL;
#endif
cleanup_sctp_mibs(net);
sctp_sysctl_net_unregister(net);
}
static struct pernet_operations sctp_defaults_ops = {
.init = sctp_defaults_init,
.exit = sctp_defaults_exit,
};
static int __net_init sctp_ctrlsock_init(struct net *net)
{
int status;
/* Initialize the control inode/socket for handling OOTB packets. */
status = sctp_ctl_sock_init(net);
if (status)
pr_err("Failed to initialize the SCTP control sock\n");
return status;
}
static void __net_exit sctp_ctrlsock_exit(struct net *net)
{
/* Free the control endpoint. */
inet_ctl_sock_destroy(net->sctp.ctl_sock);
}
static struct pernet_operations sctp_ctrlsock_ops = {
.init = sctp_ctrlsock_init,
.exit = sctp_ctrlsock_exit,
};
/* Initialize the universe into something sensible. */
static __init int sctp_init(void)
{
unsigned long nr_pages = totalram_pages();
unsigned long limit;
unsigned long goal;
int max_entry_order;
int num_entries;
int max_share;
int status;
int order;
int i;
sock_skb_cb_check_size(sizeof(struct sctp_ulpevent));
/* Allocate bind_bucket and chunk caches. */
status = -ENOBUFS;
sctp_bucket_cachep = kmem_cache_create("sctp_bind_bucket",
sizeof(struct sctp_bind_bucket),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!sctp_bucket_cachep)
goto out;
sctp_chunk_cachep = kmem_cache_create("sctp_chunk",
sizeof(struct sctp_chunk),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!sctp_chunk_cachep)
goto err_chunk_cachep;
status = percpu_counter_init(&sctp_sockets_allocated, 0, GFP_KERNEL);
if (status)
goto err_percpu_counter_init;
/* Implementation specific variables. */
/* Initialize default stream count setup information. */
sctp_max_instreams = SCTP_DEFAULT_INSTREAMS;
sctp_max_outstreams = SCTP_DEFAULT_OUTSTREAMS;
/* Initialize handle used for association ids. */
idr_init(&sctp_assocs_id);
limit = nr_free_buffer_pages() / 8;
limit = max(limit, 128UL);
sysctl_sctp_mem[0] = limit / 4 * 3;
sysctl_sctp_mem[1] = limit;
sysctl_sctp_mem[2] = sysctl_sctp_mem[0] * 2;
/* Set per-socket limits to no more than 1/128 the pressure threshold*/
limit = (sysctl_sctp_mem[1]) << (PAGE_SHIFT - 7);
max_share = min(4UL*1024*1024, limit);
sysctl_sctp_rmem[0] = PAGE_SIZE; /* give each asoc 1 page min */
sysctl_sctp_rmem[1] = 1500 * SKB_TRUESIZE(1);
sysctl_sctp_rmem[2] = max(sysctl_sctp_rmem[1], max_share);
sysctl_sctp_wmem[0] = PAGE_SIZE;
sysctl_sctp_wmem[1] = 16*1024;
sysctl_sctp_wmem[2] = max(64*1024, max_share);
/* Size and allocate the association hash table.
* The methodology is similar to that of the tcp hash tables.
* Though not identical. Start by getting a goal size
*/
if (nr_pages >= (128 * 1024))
goal = nr_pages >> (22 - PAGE_SHIFT);
else
goal = nr_pages >> (24 - PAGE_SHIFT);
/* Then compute the page order for said goal */
order = get_order(goal);
/* Now compute the required page order for the maximum sized table we
* want to create
*/
max_entry_order = get_order(MAX_SCTP_PORT_HASH_ENTRIES *
sizeof(struct sctp_bind_hashbucket));
/* Limit the page order by that maximum hash table size */
order = min(order, max_entry_order);
/* Allocate and initialize the endpoint hash table. */
sctp_ep_hashsize = 64;
sctp_ep_hashtable =
kmalloc_array(64, sizeof(struct sctp_hashbucket), GFP_KERNEL);
if (!sctp_ep_hashtable) {
pr_err("Failed endpoint_hash alloc\n");
status = -ENOMEM;
goto err_ehash_alloc;
}
for (i = 0; i < sctp_ep_hashsize; i++) {
rwlock_init(&sctp_ep_hashtable[i].lock);
INIT_HLIST_HEAD(&sctp_ep_hashtable[i].chain);
}
/* Allocate and initialize the SCTP port hash table.
* Note that order is initalized to start at the max sized
* table we want to support. If we can't get that many pages
* reduce the order and try again
*/
do {
sctp_port_hashtable = (struct sctp_bind_hashbucket *)
__get_free_pages(GFP_KERNEL | __GFP_NOWARN, order);
} while (!sctp_port_hashtable && --order > 0);
if (!sctp_port_hashtable) {
pr_err("Failed bind hash alloc\n");
status = -ENOMEM;
goto err_bhash_alloc;
}
/* Now compute the number of entries that will fit in the
* port hash space we allocated
*/
num_entries = (1UL << order) * PAGE_SIZE /
sizeof(struct sctp_bind_hashbucket);
/* And finish by rounding it down to the nearest power of two.
* This wastes some memory of course, but it's needed because
* the hash function operates based on the assumption that
* the number of entries is a power of two.
*/
sctp_port_hashsize = rounddown_pow_of_two(num_entries);
for (i = 0; i < sctp_port_hashsize; i++) {
spin_lock_init(&sctp_port_hashtable[i].lock);
INIT_HLIST_HEAD(&sctp_port_hashtable[i].chain);
}
status = sctp_transport_hashtable_init();
if (status)
goto err_thash_alloc;
pr_info("Hash tables configured (bind %d/%d)\n", sctp_port_hashsize,
num_entries);
sctp_sysctl_register();
INIT_LIST_HEAD(&sctp_address_families);
sctp_v4_pf_init();
sctp_v6_pf_init();
sctp_sched_ops_init();
status = register_pernet_subsys(&sctp_defaults_ops);
if (status)
goto err_register_defaults;
status = sctp_v4_protosw_init();
if (status)
goto err_protosw_init;
status = sctp_v6_protosw_init();
if (status)
goto err_v6_protosw_init;
status = register_pernet_subsys(&sctp_ctrlsock_ops);
if (status)
goto err_register_ctrlsock;
status = sctp_v4_add_protocol();
if (status)
goto err_add_protocol;
/* Register SCTP with inet6 layer. */
status = sctp_v6_add_protocol();
if (status)
goto err_v6_add_protocol;
if (sctp_offload_init() < 0)
pr_crit("%s: Cannot add SCTP protocol offload\n", __func__);
out:
return status;
err_v6_add_protocol:
sctp_v4_del_protocol();
err_add_protocol:
unregister_pernet_subsys(&sctp_ctrlsock_ops);
err_register_ctrlsock:
sctp_v6_protosw_exit();
err_v6_protosw_init:
sctp_v4_protosw_exit();
err_protosw_init:
unregister_pernet_subsys(&sctp_defaults_ops);
err_register_defaults:
sctp_v4_pf_exit();
sctp_v6_pf_exit();
sctp_sysctl_unregister();
free_pages((unsigned long)sctp_port_hashtable,
get_order(sctp_port_hashsize *
sizeof(struct sctp_bind_hashbucket)));
err_bhash_alloc:
sctp_transport_hashtable_destroy();
err_thash_alloc:
kfree(sctp_ep_hashtable);
err_ehash_alloc:
percpu_counter_destroy(&sctp_sockets_allocated);
err_percpu_counter_init:
kmem_cache_destroy(sctp_chunk_cachep);
err_chunk_cachep:
kmem_cache_destroy(sctp_bucket_cachep);
goto out;
}
/* Exit handler for the SCTP protocol. */
static __exit void sctp_exit(void)
{
/* BUG. This should probably do something useful like clean
* up all the remaining associations and all that memory.
*/
/* Unregister with inet6/inet layers. */
sctp_v6_del_protocol();
sctp_v4_del_protocol();
unregister_pernet_subsys(&sctp_ctrlsock_ops);
/* Free protosw registrations */
sctp_v6_protosw_exit();
sctp_v4_protosw_exit();
unregister_pernet_subsys(&sctp_defaults_ops);
/* Unregister with socket layer. */
sctp_v6_pf_exit();
sctp_v4_pf_exit();
sctp_sysctl_unregister();
free_pages((unsigned long)sctp_port_hashtable,
get_order(sctp_port_hashsize *
sizeof(struct sctp_bind_hashbucket)));
kfree(sctp_ep_hashtable);
sctp_transport_hashtable_destroy();
percpu_counter_destroy(&sctp_sockets_allocated);
rcu_barrier(); /* Wait for completion of call_rcu()'s */
kmem_cache_destroy(sctp_chunk_cachep);
kmem_cache_destroy(sctp_bucket_cachep);
}
module_init(sctp_init);
module_exit(sctp_exit);
/*
* __stringify doesn't likes enums, so use IPPROTO_SCTP value (132) directly.
*/
MODULE_ALIAS("net-pf-" __stringify(PF_INET) "-proto-132");
MODULE_ALIAS("net-pf-" __stringify(PF_INET6) "-proto-132");
MODULE_AUTHOR("Linux Kernel SCTP developers <[email protected]>");
MODULE_DESCRIPTION("Support for the SCTP protocol (RFC2960)");
module_param_named(no_checksums, sctp_checksum_disable, bool, 0644);
MODULE_PARM_DESC(no_checksums, "Disable checksums computing and verification");
MODULE_LICENSE("GPL");
| linux-master | net/sctp/protocol.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2003, 2004
*
* This file is part of the SCTP kernel implementation
*
* This file contains the code relating the chunk abstraction.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Jon Grimm <[email protected]>
* Sridhar Samudrala <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
/* This file is mostly in anticipation of future work, but initially
* populate with fragment tracking for an outbound message.
*/
/* Initialize datamsg from memory. */
static void sctp_datamsg_init(struct sctp_datamsg *msg)
{
refcount_set(&msg->refcnt, 1);
msg->send_failed = 0;
msg->send_error = 0;
msg->can_delay = 1;
msg->abandoned = 0;
msg->expires_at = 0;
INIT_LIST_HEAD(&msg->chunks);
}
/* Allocate and initialize datamsg. */
static struct sctp_datamsg *sctp_datamsg_new(gfp_t gfp)
{
struct sctp_datamsg *msg;
msg = kmalloc(sizeof(struct sctp_datamsg), gfp);
if (msg) {
sctp_datamsg_init(msg);
SCTP_DBG_OBJCNT_INC(datamsg);
}
return msg;
}
void sctp_datamsg_free(struct sctp_datamsg *msg)
{
struct sctp_chunk *chunk;
/* This doesn't have to be a _safe vairant because
* sctp_chunk_free() only drops the refs.
*/
list_for_each_entry(chunk, &msg->chunks, frag_list)
sctp_chunk_free(chunk);
sctp_datamsg_put(msg);
}
/* Final destructruction of datamsg memory. */
static void sctp_datamsg_destroy(struct sctp_datamsg *msg)
{
struct sctp_association *asoc = NULL;
struct list_head *pos, *temp;
struct sctp_chunk *chunk;
struct sctp_ulpevent *ev;
int error, sent;
/* Release all references. */
list_for_each_safe(pos, temp, &msg->chunks) {
list_del_init(pos);
chunk = list_entry(pos, struct sctp_chunk, frag_list);
if (!msg->send_failed) {
sctp_chunk_put(chunk);
continue;
}
asoc = chunk->asoc;
error = msg->send_error ?: asoc->outqueue.error;
sent = chunk->has_tsn ? SCTP_DATA_SENT : SCTP_DATA_UNSENT;
if (sctp_ulpevent_type_enabled(asoc->subscribe,
SCTP_SEND_FAILED)) {
ev = sctp_ulpevent_make_send_failed(asoc, chunk, sent,
error, GFP_ATOMIC);
if (ev)
asoc->stream.si->enqueue_event(&asoc->ulpq, ev);
}
if (sctp_ulpevent_type_enabled(asoc->subscribe,
SCTP_SEND_FAILED_EVENT)) {
ev = sctp_ulpevent_make_send_failed_event(asoc, chunk,
sent, error,
GFP_ATOMIC);
if (ev)
asoc->stream.si->enqueue_event(&asoc->ulpq, ev);
}
sctp_chunk_put(chunk);
}
SCTP_DBG_OBJCNT_DEC(datamsg);
kfree(msg);
}
/* Hold a reference. */
static void sctp_datamsg_hold(struct sctp_datamsg *msg)
{
refcount_inc(&msg->refcnt);
}
/* Release a reference. */
void sctp_datamsg_put(struct sctp_datamsg *msg)
{
if (refcount_dec_and_test(&msg->refcnt))
sctp_datamsg_destroy(msg);
}
/* Assign a chunk to this datamsg. */
static void sctp_datamsg_assign(struct sctp_datamsg *msg, struct sctp_chunk *chunk)
{
sctp_datamsg_hold(msg);
chunk->msg = msg;
}
/* A data chunk can have a maximum payload of (2^16 - 20). Break
* down any such message into smaller chunks. Opportunistically, fragment
* the chunks down to the current MTU constraints. We may get refragmented
* later if the PMTU changes, but it is _much better_ to fragment immediately
* with a reasonable guess than always doing our fragmentation on the
* soft-interrupt.
*/
struct sctp_datamsg *sctp_datamsg_from_user(struct sctp_association *asoc,
struct sctp_sndrcvinfo *sinfo,
struct iov_iter *from)
{
size_t len, first_len, max_data, remaining;
size_t msg_len = iov_iter_count(from);
struct sctp_shared_key *shkey = NULL;
struct list_head *pos, *temp;
struct sctp_chunk *chunk;
struct sctp_datamsg *msg;
int err;
msg = sctp_datamsg_new(GFP_KERNEL);
if (!msg)
return ERR_PTR(-ENOMEM);
/* Note: Calculate this outside of the loop, so that all fragments
* have the same expiration.
*/
if (asoc->peer.prsctp_capable && sinfo->sinfo_timetolive &&
(SCTP_PR_TTL_ENABLED(sinfo->sinfo_flags) ||
!SCTP_PR_POLICY(sinfo->sinfo_flags)))
msg->expires_at = jiffies +
msecs_to_jiffies(sinfo->sinfo_timetolive);
/* This is the biggest possible DATA chunk that can fit into
* the packet
*/
max_data = asoc->frag_point;
if (unlikely(!max_data)) {
max_data = sctp_min_frag_point(sctp_sk(asoc->base.sk),
sctp_datachk_len(&asoc->stream));
pr_warn_ratelimited("%s: asoc:%p frag_point is zero, forcing max_data to default minimum (%zu)",
__func__, asoc, max_data);
}
/* If the peer requested that we authenticate DATA chunks
* we need to account for bundling of the AUTH chunks along with
* DATA.
*/
if (sctp_auth_send_cid(SCTP_CID_DATA, asoc)) {
struct sctp_hmac *hmac_desc = sctp_auth_asoc_get_hmac(asoc);
if (hmac_desc)
max_data -= SCTP_PAD4(sizeof(struct sctp_auth_chunk) +
hmac_desc->hmac_len);
if (sinfo->sinfo_tsn &&
sinfo->sinfo_ssn != asoc->active_key_id) {
shkey = sctp_auth_get_shkey(asoc, sinfo->sinfo_ssn);
if (!shkey) {
err = -EINVAL;
goto errout;
}
} else {
shkey = asoc->shkey;
}
}
/* Set first_len and then account for possible bundles on first frag */
first_len = max_data;
/* Check to see if we have a pending SACK and try to let it be bundled
* with this message. Do this if we don't have any data queued already.
* To check that, look at out_qlen and retransmit list.
* NOTE: we will not reduce to account for SACK, if the message would
* not have been fragmented.
*/
if (timer_pending(&asoc->timers[SCTP_EVENT_TIMEOUT_SACK]) &&
asoc->outqueue.out_qlen == 0 &&
list_empty(&asoc->outqueue.retransmit) &&
msg_len > max_data)
first_len -= SCTP_PAD4(sizeof(struct sctp_sack_chunk));
/* Encourage Cookie-ECHO bundling. */
if (asoc->state < SCTP_STATE_COOKIE_ECHOED)
first_len -= SCTP_ARBITRARY_COOKIE_ECHO_LEN;
/* Account for a different sized first fragment */
if (msg_len >= first_len) {
msg->can_delay = 0;
if (msg_len > first_len)
SCTP_INC_STATS(asoc->base.net,
SCTP_MIB_FRAGUSRMSGS);
} else {
/* Which may be the only one... */
first_len = msg_len;
}
/* Create chunks for all DATA chunks. */
for (remaining = msg_len; remaining; remaining -= len) {
u8 frag = SCTP_DATA_MIDDLE_FRAG;
if (remaining == msg_len) {
/* First frag, which may also be the last */
frag |= SCTP_DATA_FIRST_FRAG;
len = first_len;
} else {
/* Middle frags */
len = max_data;
}
if (len >= remaining) {
/* Last frag, which may also be the first */
len = remaining;
frag |= SCTP_DATA_LAST_FRAG;
/* The application requests to set the I-bit of the
* last DATA chunk of a user message when providing
* the user message to the SCTP implementation.
*/
if ((sinfo->sinfo_flags & SCTP_EOF) ||
(sinfo->sinfo_flags & SCTP_SACK_IMMEDIATELY))
frag |= SCTP_DATA_SACK_IMM;
}
chunk = asoc->stream.si->make_datafrag(asoc, sinfo, len, frag,
GFP_KERNEL);
if (!chunk) {
err = -ENOMEM;
goto errout;
}
err = sctp_user_addto_chunk(chunk, len, from);
if (err < 0)
goto errout_chunk_free;
chunk->shkey = shkey;
/* Put the chunk->skb back into the form expected by send. */
__skb_pull(chunk->skb, (__u8 *)chunk->chunk_hdr -
chunk->skb->data);
sctp_datamsg_assign(msg, chunk);
list_add_tail(&chunk->frag_list, &msg->chunks);
}
return msg;
errout_chunk_free:
sctp_chunk_free(chunk);
errout:
list_for_each_safe(pos, temp, &msg->chunks) {
list_del_init(pos);
chunk = list_entry(pos, struct sctp_chunk, frag_list);
sctp_chunk_free(chunk);
}
sctp_datamsg_put(msg);
return ERR_PTR(err);
}
/* Check whether this message has expired. */
int sctp_chunk_abandoned(struct sctp_chunk *chunk)
{
if (!chunk->asoc->peer.prsctp_capable)
return 0;
if (chunk->msg->abandoned)
return 1;
if (!chunk->has_tsn &&
!(chunk->chunk_hdr->flags & SCTP_DATA_FIRST_FRAG))
return 0;
if (SCTP_PR_TTL_ENABLED(chunk->sinfo.sinfo_flags) &&
time_after(jiffies, chunk->msg->expires_at)) {
struct sctp_stream_out *streamout =
SCTP_SO(&chunk->asoc->stream,
chunk->sinfo.sinfo_stream);
if (chunk->sent_count) {
chunk->asoc->abandoned_sent[SCTP_PR_INDEX(TTL)]++;
streamout->ext->abandoned_sent[SCTP_PR_INDEX(TTL)]++;
} else {
chunk->asoc->abandoned_unsent[SCTP_PR_INDEX(TTL)]++;
streamout->ext->abandoned_unsent[SCTP_PR_INDEX(TTL)]++;
}
chunk->msg->abandoned = 1;
return 1;
} else if (SCTP_PR_RTX_ENABLED(chunk->sinfo.sinfo_flags) &&
chunk->sent_count > chunk->sinfo.sinfo_timetolive) {
struct sctp_stream_out *streamout =
SCTP_SO(&chunk->asoc->stream,
chunk->sinfo.sinfo_stream);
chunk->asoc->abandoned_sent[SCTP_PR_INDEX(RTX)]++;
streamout->ext->abandoned_sent[SCTP_PR_INDEX(RTX)]++;
chunk->msg->abandoned = 1;
return 1;
} else if (!SCTP_PR_POLICY(chunk->sinfo.sinfo_flags) &&
chunk->msg->expires_at &&
time_after(jiffies, chunk->msg->expires_at)) {
chunk->msg->abandoned = 1;
return 1;
}
/* PRIO policy is processed by sendmsg, not here */
return 0;
}
/* This chunk (and consequently entire message) has failed in its sending. */
void sctp_chunk_fail(struct sctp_chunk *chunk, int error)
{
chunk->msg->send_failed = 1;
chunk->msg->send_error = error;
}
| linux-master | net/sctp/chunk.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright Red Hat Inc. 2017
*
* This file is part of the SCTP kernel implementation
*
* These functions manipulate sctp stream queue/scheduling.
*
* Please send any bug reports or fixes you make to the
* email addresched(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Marcelo Ricardo Leitner <[email protected]>
*/
#include <linux/list.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/stream_sched.h>
/* Priority handling
* RFC DRAFT ndata section 3.4
*/
static void sctp_sched_prio_unsched_all(struct sctp_stream *stream);
static struct sctp_stream_priorities *sctp_sched_prio_head_get(struct sctp_stream_priorities *p)
{
p->users++;
return p;
}
static void sctp_sched_prio_head_put(struct sctp_stream_priorities *p)
{
if (p && --p->users == 0)
kfree(p);
}
static struct sctp_stream_priorities *sctp_sched_prio_new_head(
struct sctp_stream *stream, int prio, gfp_t gfp)
{
struct sctp_stream_priorities *p;
p = kmalloc(sizeof(*p), gfp);
if (!p)
return NULL;
INIT_LIST_HEAD(&p->prio_sched);
INIT_LIST_HEAD(&p->active);
p->next = NULL;
p->prio = prio;
p->users = 1;
return p;
}
static struct sctp_stream_priorities *sctp_sched_prio_get_head(
struct sctp_stream *stream, int prio, gfp_t gfp)
{
struct sctp_stream_priorities *p;
int i;
/* Look into scheduled priorities first, as they are sorted and
* we can find it fast IF it's scheduled.
*/
list_for_each_entry(p, &stream->prio_list, prio_sched) {
if (p->prio == prio)
return sctp_sched_prio_head_get(p);
if (p->prio > prio)
break;
}
/* No luck. So we search on all streams now. */
for (i = 0; i < stream->outcnt; i++) {
if (!SCTP_SO(stream, i)->ext)
continue;
p = SCTP_SO(stream, i)->ext->prio_head;
if (!p)
/* Means all other streams won't be initialized
* as well.
*/
break;
if (p->prio == prio)
return sctp_sched_prio_head_get(p);
}
/* If not even there, allocate a new one. */
return sctp_sched_prio_new_head(stream, prio, gfp);
}
static void sctp_sched_prio_next_stream(struct sctp_stream_priorities *p)
{
struct list_head *pos;
pos = p->next->prio_list.next;
if (pos == &p->active)
pos = pos->next;
p->next = list_entry(pos, struct sctp_stream_out_ext, prio_list);
}
static bool sctp_sched_prio_unsched(struct sctp_stream_out_ext *soute)
{
bool scheduled = false;
if (!list_empty(&soute->prio_list)) {
struct sctp_stream_priorities *prio_head = soute->prio_head;
/* Scheduled */
scheduled = true;
if (prio_head->next == soute)
/* Try to move to the next stream */
sctp_sched_prio_next_stream(prio_head);
list_del_init(&soute->prio_list);
/* Also unsched the priority if this was the last stream */
if (list_empty(&prio_head->active)) {
list_del_init(&prio_head->prio_sched);
/* If there is no stream left, clear next */
prio_head->next = NULL;
}
}
return scheduled;
}
static void sctp_sched_prio_sched(struct sctp_stream *stream,
struct sctp_stream_out_ext *soute)
{
struct sctp_stream_priorities *prio, *prio_head;
prio_head = soute->prio_head;
/* Nothing to do if already scheduled */
if (!list_empty(&soute->prio_list))
return;
/* Schedule the stream. If there is a next, we schedule the new
* one before it, so it's the last in round robin order.
* If there isn't, we also have to schedule the priority.
*/
if (prio_head->next) {
list_add(&soute->prio_list, prio_head->next->prio_list.prev);
return;
}
list_add(&soute->prio_list, &prio_head->active);
prio_head->next = soute;
list_for_each_entry(prio, &stream->prio_list, prio_sched) {
if (prio->prio > prio_head->prio) {
list_add(&prio_head->prio_sched, prio->prio_sched.prev);
return;
}
}
list_add_tail(&prio_head->prio_sched, &stream->prio_list);
}
static int sctp_sched_prio_set(struct sctp_stream *stream, __u16 sid,
__u16 prio, gfp_t gfp)
{
struct sctp_stream_out *sout = SCTP_SO(stream, sid);
struct sctp_stream_out_ext *soute = sout->ext;
struct sctp_stream_priorities *prio_head, *old;
bool reschedule = false;
old = soute->prio_head;
if (old && old->prio == prio)
return 0;
prio_head = sctp_sched_prio_get_head(stream, prio, gfp);
if (!prio_head)
return -ENOMEM;
reschedule = sctp_sched_prio_unsched(soute);
soute->prio_head = prio_head;
if (reschedule)
sctp_sched_prio_sched(stream, soute);
sctp_sched_prio_head_put(old);
return 0;
}
static int sctp_sched_prio_get(struct sctp_stream *stream, __u16 sid,
__u16 *value)
{
*value = SCTP_SO(stream, sid)->ext->prio_head->prio;
return 0;
}
static int sctp_sched_prio_init(struct sctp_stream *stream)
{
INIT_LIST_HEAD(&stream->prio_list);
return 0;
}
static int sctp_sched_prio_init_sid(struct sctp_stream *stream, __u16 sid,
gfp_t gfp)
{
INIT_LIST_HEAD(&SCTP_SO(stream, sid)->ext->prio_list);
return sctp_sched_prio_set(stream, sid, 0, gfp);
}
static void sctp_sched_prio_free_sid(struct sctp_stream *stream, __u16 sid)
{
sctp_sched_prio_head_put(SCTP_SO(stream, sid)->ext->prio_head);
SCTP_SO(stream, sid)->ext->prio_head = NULL;
}
static void sctp_sched_prio_enqueue(struct sctp_outq *q,
struct sctp_datamsg *msg)
{
struct sctp_stream *stream;
struct sctp_chunk *ch;
__u16 sid;
ch = list_first_entry(&msg->chunks, struct sctp_chunk, frag_list);
sid = sctp_chunk_stream_no(ch);
stream = &q->asoc->stream;
sctp_sched_prio_sched(stream, SCTP_SO(stream, sid)->ext);
}
static struct sctp_chunk *sctp_sched_prio_dequeue(struct sctp_outq *q)
{
struct sctp_stream *stream = &q->asoc->stream;
struct sctp_stream_priorities *prio;
struct sctp_stream_out_ext *soute;
struct sctp_chunk *ch = NULL;
/* Bail out quickly if queue is empty */
if (list_empty(&q->out_chunk_list))
goto out;
/* Find which chunk is next. It's easy, it's either the current
* one or the first chunk on the next active stream.
*/
if (stream->out_curr) {
soute = stream->out_curr->ext;
} else {
prio = list_entry(stream->prio_list.next,
struct sctp_stream_priorities, prio_sched);
soute = prio->next;
}
ch = list_entry(soute->outq.next, struct sctp_chunk, stream_list);
sctp_sched_dequeue_common(q, ch);
out:
return ch;
}
static void sctp_sched_prio_dequeue_done(struct sctp_outq *q,
struct sctp_chunk *ch)
{
struct sctp_stream_priorities *prio;
struct sctp_stream_out_ext *soute;
__u16 sid;
/* Last chunk on that msg, move to the next stream on
* this priority.
*/
sid = sctp_chunk_stream_no(ch);
soute = SCTP_SO(&q->asoc->stream, sid)->ext;
prio = soute->prio_head;
sctp_sched_prio_next_stream(prio);
if (list_empty(&soute->outq))
sctp_sched_prio_unsched(soute);
}
static void sctp_sched_prio_sched_all(struct sctp_stream *stream)
{
struct sctp_association *asoc;
struct sctp_stream_out *sout;
struct sctp_chunk *ch;
asoc = container_of(stream, struct sctp_association, stream);
list_for_each_entry(ch, &asoc->outqueue.out_chunk_list, list) {
__u16 sid;
sid = sctp_chunk_stream_no(ch);
sout = SCTP_SO(stream, sid);
if (sout->ext)
sctp_sched_prio_sched(stream, sout->ext);
}
}
static void sctp_sched_prio_unsched_all(struct sctp_stream *stream)
{
struct sctp_stream_priorities *p, *tmp;
struct sctp_stream_out_ext *soute, *souttmp;
list_for_each_entry_safe(p, tmp, &stream->prio_list, prio_sched)
list_for_each_entry_safe(soute, souttmp, &p->active, prio_list)
sctp_sched_prio_unsched(soute);
}
static struct sctp_sched_ops sctp_sched_prio = {
.set = sctp_sched_prio_set,
.get = sctp_sched_prio_get,
.init = sctp_sched_prio_init,
.init_sid = sctp_sched_prio_init_sid,
.free_sid = sctp_sched_prio_free_sid,
.enqueue = sctp_sched_prio_enqueue,
.dequeue = sctp_sched_prio_dequeue,
.dequeue_done = sctp_sched_prio_dequeue_done,
.sched_all = sctp_sched_prio_sched_all,
.unsched_all = sctp_sched_prio_unsched_all,
};
void sctp_sched_ops_prio_init(void)
{
sctp_sched_ops_register(SCTP_SS_PRIO, &sctp_sched_prio);
}
| linux-master | net/sctp/stream_sched_prio.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2003 Intel Corp.
*
* This file is part of the SCTP kernel implementation
*
* These functions implement the sctp_outq class. The outqueue handles
* bundling and queueing of outgoing SCTP chunks.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Perry Melange <[email protected]>
* Xingang Guo <[email protected]>
* Hui Huang <[email protected]>
* Sridhar Samudrala <[email protected]>
* Jon Grimm <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/list.h> /* For struct list_head */
#include <linux/socket.h>
#include <linux/ip.h>
#include <linux/slab.h>
#include <net/sock.h> /* For skb_set_owner_w */
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/stream_sched.h>
#include <trace/events/sctp.h>
/* Declare internal functions here. */
static int sctp_acked(struct sctp_sackhdr *sack, __u32 tsn);
static void sctp_check_transmitted(struct sctp_outq *q,
struct list_head *transmitted_queue,
struct sctp_transport *transport,
union sctp_addr *saddr,
struct sctp_sackhdr *sack,
__u32 *highest_new_tsn);
static void sctp_mark_missing(struct sctp_outq *q,
struct list_head *transmitted_queue,
struct sctp_transport *transport,
__u32 highest_new_tsn,
int count_of_newacks);
static void sctp_outq_flush(struct sctp_outq *q, int rtx_timeout, gfp_t gfp);
/* Add data to the front of the queue. */
static inline void sctp_outq_head_data(struct sctp_outq *q,
struct sctp_chunk *ch)
{
struct sctp_stream_out_ext *oute;
__u16 stream;
list_add(&ch->list, &q->out_chunk_list);
q->out_qlen += ch->skb->len;
stream = sctp_chunk_stream_no(ch);
oute = SCTP_SO(&q->asoc->stream, stream)->ext;
list_add(&ch->stream_list, &oute->outq);
}
/* Take data from the front of the queue. */
static inline struct sctp_chunk *sctp_outq_dequeue_data(struct sctp_outq *q)
{
return q->sched->dequeue(q);
}
/* Add data chunk to the end of the queue. */
static inline void sctp_outq_tail_data(struct sctp_outq *q,
struct sctp_chunk *ch)
{
struct sctp_stream_out_ext *oute;
__u16 stream;
list_add_tail(&ch->list, &q->out_chunk_list);
q->out_qlen += ch->skb->len;
stream = sctp_chunk_stream_no(ch);
oute = SCTP_SO(&q->asoc->stream, stream)->ext;
list_add_tail(&ch->stream_list, &oute->outq);
}
/*
* SFR-CACC algorithm:
* D) If count_of_newacks is greater than or equal to 2
* and t was not sent to the current primary then the
* sender MUST NOT increment missing report count for t.
*/
static inline int sctp_cacc_skip_3_1_d(struct sctp_transport *primary,
struct sctp_transport *transport,
int count_of_newacks)
{
if (count_of_newacks >= 2 && transport != primary)
return 1;
return 0;
}
/*
* SFR-CACC algorithm:
* F) If count_of_newacks is less than 2, let d be the
* destination to which t was sent. If cacc_saw_newack
* is 0 for destination d, then the sender MUST NOT
* increment missing report count for t.
*/
static inline int sctp_cacc_skip_3_1_f(struct sctp_transport *transport,
int count_of_newacks)
{
if (count_of_newacks < 2 &&
(transport && !transport->cacc.cacc_saw_newack))
return 1;
return 0;
}
/*
* SFR-CACC algorithm:
* 3.1) If CYCLING_CHANGEOVER is 0, the sender SHOULD
* execute steps C, D, F.
*
* C has been implemented in sctp_outq_sack
*/
static inline int sctp_cacc_skip_3_1(struct sctp_transport *primary,
struct sctp_transport *transport,
int count_of_newacks)
{
if (!primary->cacc.cycling_changeover) {
if (sctp_cacc_skip_3_1_d(primary, transport, count_of_newacks))
return 1;
if (sctp_cacc_skip_3_1_f(transport, count_of_newacks))
return 1;
return 0;
}
return 0;
}
/*
* SFR-CACC algorithm:
* 3.2) Else if CYCLING_CHANGEOVER is 1, and t is less
* than next_tsn_at_change of the current primary, then
* the sender MUST NOT increment missing report count
* for t.
*/
static inline int sctp_cacc_skip_3_2(struct sctp_transport *primary, __u32 tsn)
{
if (primary->cacc.cycling_changeover &&
TSN_lt(tsn, primary->cacc.next_tsn_at_change))
return 1;
return 0;
}
/*
* SFR-CACC algorithm:
* 3) If the missing report count for TSN t is to be
* incremented according to [RFC2960] and
* [SCTP_STEWART-2002], and CHANGEOVER_ACTIVE is set,
* then the sender MUST further execute steps 3.1 and
* 3.2 to determine if the missing report count for
* TSN t SHOULD NOT be incremented.
*
* 3.3) If 3.1 and 3.2 do not dictate that the missing
* report count for t should not be incremented, then
* the sender SHOULD increment missing report count for
* t (according to [RFC2960] and [SCTP_STEWART_2002]).
*/
static inline int sctp_cacc_skip(struct sctp_transport *primary,
struct sctp_transport *transport,
int count_of_newacks,
__u32 tsn)
{
if (primary->cacc.changeover_active &&
(sctp_cacc_skip_3_1(primary, transport, count_of_newacks) ||
sctp_cacc_skip_3_2(primary, tsn)))
return 1;
return 0;
}
/* Initialize an existing sctp_outq. This does the boring stuff.
* You still need to define handlers if you really want to DO
* something with this structure...
*/
void sctp_outq_init(struct sctp_association *asoc, struct sctp_outq *q)
{
memset(q, 0, sizeof(struct sctp_outq));
q->asoc = asoc;
INIT_LIST_HEAD(&q->out_chunk_list);
INIT_LIST_HEAD(&q->control_chunk_list);
INIT_LIST_HEAD(&q->retransmit);
INIT_LIST_HEAD(&q->sacked);
INIT_LIST_HEAD(&q->abandoned);
sctp_sched_set_sched(asoc, sctp_sk(asoc->base.sk)->default_ss);
}
/* Free the outqueue structure and any related pending chunks.
*/
static void __sctp_outq_teardown(struct sctp_outq *q)
{
struct sctp_transport *transport;
struct list_head *lchunk, *temp;
struct sctp_chunk *chunk, *tmp;
/* Throw away unacknowledged chunks. */
list_for_each_entry(transport, &q->asoc->peer.transport_addr_list,
transports) {
while ((lchunk = sctp_list_dequeue(&transport->transmitted)) != NULL) {
chunk = list_entry(lchunk, struct sctp_chunk,
transmitted_list);
/* Mark as part of a failed message. */
sctp_chunk_fail(chunk, q->error);
sctp_chunk_free(chunk);
}
}
/* Throw away chunks that have been gap ACKed. */
list_for_each_safe(lchunk, temp, &q->sacked) {
list_del_init(lchunk);
chunk = list_entry(lchunk, struct sctp_chunk,
transmitted_list);
sctp_chunk_fail(chunk, q->error);
sctp_chunk_free(chunk);
}
/* Throw away any chunks in the retransmit queue. */
list_for_each_safe(lchunk, temp, &q->retransmit) {
list_del_init(lchunk);
chunk = list_entry(lchunk, struct sctp_chunk,
transmitted_list);
sctp_chunk_fail(chunk, q->error);
sctp_chunk_free(chunk);
}
/* Throw away any chunks that are in the abandoned queue. */
list_for_each_safe(lchunk, temp, &q->abandoned) {
list_del_init(lchunk);
chunk = list_entry(lchunk, struct sctp_chunk,
transmitted_list);
sctp_chunk_fail(chunk, q->error);
sctp_chunk_free(chunk);
}
/* Throw away any leftover data chunks. */
while ((chunk = sctp_outq_dequeue_data(q)) != NULL) {
sctp_sched_dequeue_done(q, chunk);
/* Mark as send failure. */
sctp_chunk_fail(chunk, q->error);
sctp_chunk_free(chunk);
}
/* Throw away any leftover control chunks. */
list_for_each_entry_safe(chunk, tmp, &q->control_chunk_list, list) {
list_del_init(&chunk->list);
sctp_chunk_free(chunk);
}
}
void sctp_outq_teardown(struct sctp_outq *q)
{
__sctp_outq_teardown(q);
sctp_outq_init(q->asoc, q);
}
/* Free the outqueue structure and any related pending chunks. */
void sctp_outq_free(struct sctp_outq *q)
{
/* Throw away leftover chunks. */
__sctp_outq_teardown(q);
}
/* Put a new chunk in an sctp_outq. */
void sctp_outq_tail(struct sctp_outq *q, struct sctp_chunk *chunk, gfp_t gfp)
{
struct net *net = q->asoc->base.net;
pr_debug("%s: outq:%p, chunk:%p[%s]\n", __func__, q, chunk,
chunk && chunk->chunk_hdr ?
sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)) :
"illegal chunk");
/* If it is data, queue it up, otherwise, send it
* immediately.
*/
if (sctp_chunk_is_data(chunk)) {
pr_debug("%s: outqueueing: outq:%p, chunk:%p[%s])\n",
__func__, q, chunk, chunk && chunk->chunk_hdr ?
sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)) :
"illegal chunk");
sctp_outq_tail_data(q, chunk);
if (chunk->asoc->peer.prsctp_capable &&
SCTP_PR_PRIO_ENABLED(chunk->sinfo.sinfo_flags))
chunk->asoc->sent_cnt_removable++;
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED)
SCTP_INC_STATS(net, SCTP_MIB_OUTUNORDERCHUNKS);
else
SCTP_INC_STATS(net, SCTP_MIB_OUTORDERCHUNKS);
} else {
list_add_tail(&chunk->list, &q->control_chunk_list);
SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS);
}
if (!q->cork)
sctp_outq_flush(q, 0, gfp);
}
/* Insert a chunk into the sorted list based on the TSNs. The retransmit list
* and the abandoned list are in ascending order.
*/
static void sctp_insert_list(struct list_head *head, struct list_head *new)
{
struct list_head *pos;
struct sctp_chunk *nchunk, *lchunk;
__u32 ntsn, ltsn;
int done = 0;
nchunk = list_entry(new, struct sctp_chunk, transmitted_list);
ntsn = ntohl(nchunk->subh.data_hdr->tsn);
list_for_each(pos, head) {
lchunk = list_entry(pos, struct sctp_chunk, transmitted_list);
ltsn = ntohl(lchunk->subh.data_hdr->tsn);
if (TSN_lt(ntsn, ltsn)) {
list_add(new, pos->prev);
done = 1;
break;
}
}
if (!done)
list_add_tail(new, head);
}
static int sctp_prsctp_prune_sent(struct sctp_association *asoc,
struct sctp_sndrcvinfo *sinfo,
struct list_head *queue, int msg_len)
{
struct sctp_chunk *chk, *temp;
list_for_each_entry_safe(chk, temp, queue, transmitted_list) {
struct sctp_stream_out *streamout;
if (!chk->msg->abandoned &&
(!SCTP_PR_PRIO_ENABLED(chk->sinfo.sinfo_flags) ||
chk->sinfo.sinfo_timetolive <= sinfo->sinfo_timetolive))
continue;
chk->msg->abandoned = 1;
list_del_init(&chk->transmitted_list);
sctp_insert_list(&asoc->outqueue.abandoned,
&chk->transmitted_list);
streamout = SCTP_SO(&asoc->stream, chk->sinfo.sinfo_stream);
asoc->sent_cnt_removable--;
asoc->abandoned_sent[SCTP_PR_INDEX(PRIO)]++;
streamout->ext->abandoned_sent[SCTP_PR_INDEX(PRIO)]++;
if (queue != &asoc->outqueue.retransmit &&
!chk->tsn_gap_acked) {
if (chk->transport)
chk->transport->flight_size -=
sctp_data_size(chk);
asoc->outqueue.outstanding_bytes -= sctp_data_size(chk);
}
msg_len -= chk->skb->truesize + sizeof(struct sctp_chunk);
if (msg_len <= 0)
break;
}
return msg_len;
}
static int sctp_prsctp_prune_unsent(struct sctp_association *asoc,
struct sctp_sndrcvinfo *sinfo, int msg_len)
{
struct sctp_outq *q = &asoc->outqueue;
struct sctp_chunk *chk, *temp;
struct sctp_stream_out *sout;
q->sched->unsched_all(&asoc->stream);
list_for_each_entry_safe(chk, temp, &q->out_chunk_list, list) {
if (!chk->msg->abandoned &&
(!(chk->chunk_hdr->flags & SCTP_DATA_FIRST_FRAG) ||
!SCTP_PR_PRIO_ENABLED(chk->sinfo.sinfo_flags) ||
chk->sinfo.sinfo_timetolive <= sinfo->sinfo_timetolive))
continue;
chk->msg->abandoned = 1;
sctp_sched_dequeue_common(q, chk);
asoc->sent_cnt_removable--;
asoc->abandoned_unsent[SCTP_PR_INDEX(PRIO)]++;
sout = SCTP_SO(&asoc->stream, chk->sinfo.sinfo_stream);
sout->ext->abandoned_unsent[SCTP_PR_INDEX(PRIO)]++;
/* clear out_curr if all frag chunks are pruned */
if (asoc->stream.out_curr == sout &&
list_is_last(&chk->frag_list, &chk->msg->chunks))
asoc->stream.out_curr = NULL;
msg_len -= chk->skb->truesize + sizeof(struct sctp_chunk);
sctp_chunk_free(chk);
if (msg_len <= 0)
break;
}
q->sched->sched_all(&asoc->stream);
return msg_len;
}
/* Abandon the chunks according their priorities */
void sctp_prsctp_prune(struct sctp_association *asoc,
struct sctp_sndrcvinfo *sinfo, int msg_len)
{
struct sctp_transport *transport;
if (!asoc->peer.prsctp_capable || !asoc->sent_cnt_removable)
return;
msg_len = sctp_prsctp_prune_sent(asoc, sinfo,
&asoc->outqueue.retransmit,
msg_len);
if (msg_len <= 0)
return;
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
msg_len = sctp_prsctp_prune_sent(asoc, sinfo,
&transport->transmitted,
msg_len);
if (msg_len <= 0)
return;
}
sctp_prsctp_prune_unsent(asoc, sinfo, msg_len);
}
/* Mark all the eligible packets on a transport for retransmission. */
void sctp_retransmit_mark(struct sctp_outq *q,
struct sctp_transport *transport,
__u8 reason)
{
struct list_head *lchunk, *ltemp;
struct sctp_chunk *chunk;
/* Walk through the specified transmitted queue. */
list_for_each_safe(lchunk, ltemp, &transport->transmitted) {
chunk = list_entry(lchunk, struct sctp_chunk,
transmitted_list);
/* If the chunk is abandoned, move it to abandoned list. */
if (sctp_chunk_abandoned(chunk)) {
list_del_init(lchunk);
sctp_insert_list(&q->abandoned, lchunk);
/* If this chunk has not been previousely acked,
* stop considering it 'outstanding'. Our peer
* will most likely never see it since it will
* not be retransmitted
*/
if (!chunk->tsn_gap_acked) {
if (chunk->transport)
chunk->transport->flight_size -=
sctp_data_size(chunk);
q->outstanding_bytes -= sctp_data_size(chunk);
q->asoc->peer.rwnd += sctp_data_size(chunk);
}
continue;
}
/* If we are doing retransmission due to a timeout or pmtu
* discovery, only the chunks that are not yet acked should
* be added to the retransmit queue.
*/
if ((reason == SCTP_RTXR_FAST_RTX &&
(chunk->fast_retransmit == SCTP_NEED_FRTX)) ||
(reason != SCTP_RTXR_FAST_RTX && !chunk->tsn_gap_acked)) {
/* RFC 2960 6.2.1 Processing a Received SACK
*
* C) Any time a DATA chunk is marked for
* retransmission (via either T3-rtx timer expiration
* (Section 6.3.3) or via fast retransmit
* (Section 7.2.4)), add the data size of those
* chunks to the rwnd.
*/
q->asoc->peer.rwnd += sctp_data_size(chunk);
q->outstanding_bytes -= sctp_data_size(chunk);
if (chunk->transport)
transport->flight_size -= sctp_data_size(chunk);
/* sctpimpguide-05 Section 2.8.2
* M5) If a T3-rtx timer expires, the
* 'TSN.Missing.Report' of all affected TSNs is set
* to 0.
*/
chunk->tsn_missing_report = 0;
/* If a chunk that is being used for RTT measurement
* has to be retransmitted, we cannot use this chunk
* anymore for RTT measurements. Reset rto_pending so
* that a new RTT measurement is started when a new
* data chunk is sent.
*/
if (chunk->rtt_in_progress) {
chunk->rtt_in_progress = 0;
transport->rto_pending = 0;
}
/* Move the chunk to the retransmit queue. The chunks
* on the retransmit queue are always kept in order.
*/
list_del_init(lchunk);
sctp_insert_list(&q->retransmit, lchunk);
}
}
pr_debug("%s: transport:%p, reason:%d, cwnd:%d, ssthresh:%d, "
"flight_size:%d, pba:%d\n", __func__, transport, reason,
transport->cwnd, transport->ssthresh, transport->flight_size,
transport->partial_bytes_acked);
}
/* Mark all the eligible packets on a transport for retransmission and force
* one packet out.
*/
void sctp_retransmit(struct sctp_outq *q, struct sctp_transport *transport,
enum sctp_retransmit_reason reason)
{
struct net *net = q->asoc->base.net;
switch (reason) {
case SCTP_RTXR_T3_RTX:
SCTP_INC_STATS(net, SCTP_MIB_T3_RETRANSMITS);
sctp_transport_lower_cwnd(transport, SCTP_LOWER_CWND_T3_RTX);
/* Update the retran path if the T3-rtx timer has expired for
* the current retran path.
*/
if (transport == transport->asoc->peer.retran_path)
sctp_assoc_update_retran_path(transport->asoc);
transport->asoc->rtx_data_chunks +=
transport->asoc->unack_data;
if (transport->pl.state == SCTP_PL_COMPLETE &&
transport->asoc->unack_data)
sctp_transport_reset_probe_timer(transport);
break;
case SCTP_RTXR_FAST_RTX:
SCTP_INC_STATS(net, SCTP_MIB_FAST_RETRANSMITS);
sctp_transport_lower_cwnd(transport, SCTP_LOWER_CWND_FAST_RTX);
q->fast_rtx = 1;
break;
case SCTP_RTXR_PMTUD:
SCTP_INC_STATS(net, SCTP_MIB_PMTUD_RETRANSMITS);
break;
case SCTP_RTXR_T1_RTX:
SCTP_INC_STATS(net, SCTP_MIB_T1_RETRANSMITS);
transport->asoc->init_retries++;
break;
default:
BUG();
}
sctp_retransmit_mark(q, transport, reason);
/* PR-SCTP A5) Any time the T3-rtx timer expires, on any destination,
* the sender SHOULD try to advance the "Advanced.Peer.Ack.Point" by
* following the procedures outlined in C1 - C5.
*/
if (reason == SCTP_RTXR_T3_RTX)
q->asoc->stream.si->generate_ftsn(q, q->asoc->ctsn_ack_point);
/* Flush the queues only on timeout, since fast_rtx is only
* triggered during sack processing and the queue
* will be flushed at the end.
*/
if (reason != SCTP_RTXR_FAST_RTX)
sctp_outq_flush(q, /* rtx_timeout */ 1, GFP_ATOMIC);
}
/*
* Transmit DATA chunks on the retransmit queue. Upon return from
* __sctp_outq_flush_rtx() the packet 'pkt' may contain chunks which
* need to be transmitted by the caller.
* We assume that pkt->transport has already been set.
*
* The return value is a normal kernel error return value.
*/
static int __sctp_outq_flush_rtx(struct sctp_outq *q, struct sctp_packet *pkt,
int rtx_timeout, int *start_timer, gfp_t gfp)
{
struct sctp_transport *transport = pkt->transport;
struct sctp_chunk *chunk, *chunk1;
struct list_head *lqueue;
enum sctp_xmit status;
int error = 0;
int timer = 0;
int done = 0;
int fast_rtx;
lqueue = &q->retransmit;
fast_rtx = q->fast_rtx;
/* This loop handles time-out retransmissions, fast retransmissions,
* and retransmissions due to opening of whindow.
*
* RFC 2960 6.3.3 Handle T3-rtx Expiration
*
* E3) Determine how many of the earliest (i.e., lowest TSN)
* outstanding DATA chunks for the address for which the
* T3-rtx has expired will fit into a single packet, subject
* to the MTU constraint for the path corresponding to the
* destination transport address to which the retransmission
* is being sent (this may be different from the address for
* which the timer expires [see Section 6.4]). Call this value
* K. Bundle and retransmit those K DATA chunks in a single
* packet to the destination endpoint.
*
* [Just to be painfully clear, if we are retransmitting
* because a timeout just happened, we should send only ONE
* packet of retransmitted data.]
*
* For fast retransmissions we also send only ONE packet. However,
* if we are just flushing the queue due to open window, we'll
* try to send as much as possible.
*/
list_for_each_entry_safe(chunk, chunk1, lqueue, transmitted_list) {
/* If the chunk is abandoned, move it to abandoned list. */
if (sctp_chunk_abandoned(chunk)) {
list_del_init(&chunk->transmitted_list);
sctp_insert_list(&q->abandoned,
&chunk->transmitted_list);
continue;
}
/* Make sure that Gap Acked TSNs are not retransmitted. A
* simple approach is just to move such TSNs out of the
* way and into a 'transmitted' queue and skip to the
* next chunk.
*/
if (chunk->tsn_gap_acked) {
list_move_tail(&chunk->transmitted_list,
&transport->transmitted);
continue;
}
/* If we are doing fast retransmit, ignore non-fast_rtransmit
* chunks
*/
if (fast_rtx && !chunk->fast_retransmit)
continue;
redo:
/* Attempt to append this chunk to the packet. */
status = sctp_packet_append_chunk(pkt, chunk);
switch (status) {
case SCTP_XMIT_PMTU_FULL:
if (!pkt->has_data && !pkt->has_cookie_echo) {
/* If this packet did not contain DATA then
* retransmission did not happen, so do it
* again. We'll ignore the error here since
* control chunks are already freed so there
* is nothing we can do.
*/
sctp_packet_transmit(pkt, gfp);
goto redo;
}
/* Send this packet. */
error = sctp_packet_transmit(pkt, gfp);
/* If we are retransmitting, we should only
* send a single packet.
* Otherwise, try appending this chunk again.
*/
if (rtx_timeout || fast_rtx)
done = 1;
else
goto redo;
/* Bundle next chunk in the next round. */
break;
case SCTP_XMIT_RWND_FULL:
/* Send this packet. */
error = sctp_packet_transmit(pkt, gfp);
/* Stop sending DATA as there is no more room
* at the receiver.
*/
done = 1;
break;
case SCTP_XMIT_DELAY:
/* Send this packet. */
error = sctp_packet_transmit(pkt, gfp);
/* Stop sending DATA because of nagle delay. */
done = 1;
break;
default:
/* The append was successful, so add this chunk to
* the transmitted list.
*/
list_move_tail(&chunk->transmitted_list,
&transport->transmitted);
/* Mark the chunk as ineligible for fast retransmit
* after it is retransmitted.
*/
if (chunk->fast_retransmit == SCTP_NEED_FRTX)
chunk->fast_retransmit = SCTP_DONT_FRTX;
q->asoc->stats.rtxchunks++;
break;
}
/* Set the timer if there were no errors */
if (!error && !timer)
timer = 1;
if (done)
break;
}
/* If we are here due to a retransmit timeout or a fast
* retransmit and if there are any chunks left in the retransmit
* queue that could not fit in the PMTU sized packet, they need
* to be marked as ineligible for a subsequent fast retransmit.
*/
if (rtx_timeout || fast_rtx) {
list_for_each_entry(chunk1, lqueue, transmitted_list) {
if (chunk1->fast_retransmit == SCTP_NEED_FRTX)
chunk1->fast_retransmit = SCTP_DONT_FRTX;
}
}
*start_timer = timer;
/* Clear fast retransmit hint */
if (fast_rtx)
q->fast_rtx = 0;
return error;
}
/* Cork the outqueue so queued chunks are really queued. */
void sctp_outq_uncork(struct sctp_outq *q, gfp_t gfp)
{
if (q->cork)
q->cork = 0;
sctp_outq_flush(q, 0, gfp);
}
static int sctp_packet_singleton(struct sctp_transport *transport,
struct sctp_chunk *chunk, gfp_t gfp)
{
const struct sctp_association *asoc = transport->asoc;
const __u16 sport = asoc->base.bind_addr.port;
const __u16 dport = asoc->peer.port;
const __u32 vtag = asoc->peer.i.init_tag;
struct sctp_packet singleton;
sctp_packet_init(&singleton, transport, sport, dport);
sctp_packet_config(&singleton, vtag, 0);
if (sctp_packet_append_chunk(&singleton, chunk) != SCTP_XMIT_OK) {
list_del_init(&chunk->list);
sctp_chunk_free(chunk);
return -ENOMEM;
}
return sctp_packet_transmit(&singleton, gfp);
}
/* Struct to hold the context during sctp outq flush */
struct sctp_flush_ctx {
struct sctp_outq *q;
/* Current transport being used. It's NOT the same as curr active one */
struct sctp_transport *transport;
/* These transports have chunks to send. */
struct list_head transport_list;
struct sctp_association *asoc;
/* Packet on the current transport above */
struct sctp_packet *packet;
gfp_t gfp;
};
/* transport: current transport */
static void sctp_outq_select_transport(struct sctp_flush_ctx *ctx,
struct sctp_chunk *chunk)
{
struct sctp_transport *new_transport = chunk->transport;
if (!new_transport) {
if (!sctp_chunk_is_data(chunk)) {
/* If we have a prior transport pointer, see if
* the destination address of the chunk
* matches the destination address of the
* current transport. If not a match, then
* try to look up the transport with a given
* destination address. We do this because
* after processing ASCONFs, we may have new
* transports created.
*/
if (ctx->transport && sctp_cmp_addr_exact(&chunk->dest,
&ctx->transport->ipaddr))
new_transport = ctx->transport;
else
new_transport = sctp_assoc_lookup_paddr(ctx->asoc,
&chunk->dest);
}
/* if we still don't have a new transport, then
* use the current active path.
*/
if (!new_transport)
new_transport = ctx->asoc->peer.active_path;
} else {
__u8 type;
switch (new_transport->state) {
case SCTP_INACTIVE:
case SCTP_UNCONFIRMED:
case SCTP_PF:
/* If the chunk is Heartbeat or Heartbeat Ack,
* send it to chunk->transport, even if it's
* inactive.
*
* 3.3.6 Heartbeat Acknowledgement:
* ...
* A HEARTBEAT ACK is always sent to the source IP
* address of the IP datagram containing the
* HEARTBEAT chunk to which this ack is responding.
* ...
*
* ASCONF_ACKs also must be sent to the source.
*/
type = chunk->chunk_hdr->type;
if (type != SCTP_CID_HEARTBEAT &&
type != SCTP_CID_HEARTBEAT_ACK &&
type != SCTP_CID_ASCONF_ACK)
new_transport = ctx->asoc->peer.active_path;
break;
default:
break;
}
}
/* Are we switching transports? Take care of transport locks. */
if (new_transport != ctx->transport) {
ctx->transport = new_transport;
ctx->packet = &ctx->transport->packet;
if (list_empty(&ctx->transport->send_ready))
list_add_tail(&ctx->transport->send_ready,
&ctx->transport_list);
sctp_packet_config(ctx->packet,
ctx->asoc->peer.i.init_tag,
ctx->asoc->peer.ecn_capable);
/* We've switched transports, so apply the
* Burst limit to the new transport.
*/
sctp_transport_burst_limited(ctx->transport);
}
}
static void sctp_outq_flush_ctrl(struct sctp_flush_ctx *ctx)
{
struct sctp_chunk *chunk, *tmp;
enum sctp_xmit status;
int one_packet, error;
list_for_each_entry_safe(chunk, tmp, &ctx->q->control_chunk_list, list) {
one_packet = 0;
/* RFC 5061, 5.3
* F1) This means that until such time as the ASCONF
* containing the add is acknowledged, the sender MUST
* NOT use the new IP address as a source for ANY SCTP
* packet except on carrying an ASCONF Chunk.
*/
if (ctx->asoc->src_out_of_asoc_ok &&
chunk->chunk_hdr->type != SCTP_CID_ASCONF)
continue;
list_del_init(&chunk->list);
/* Pick the right transport to use. Should always be true for
* the first chunk as we don't have a transport by then.
*/
sctp_outq_select_transport(ctx, chunk);
switch (chunk->chunk_hdr->type) {
/* 6.10 Bundling
* ...
* An endpoint MUST NOT bundle INIT, INIT ACK or SHUTDOWN
* COMPLETE with any other chunks. [Send them immediately.]
*/
case SCTP_CID_INIT:
case SCTP_CID_INIT_ACK:
case SCTP_CID_SHUTDOWN_COMPLETE:
error = sctp_packet_singleton(ctx->transport, chunk,
ctx->gfp);
if (error < 0) {
ctx->asoc->base.sk->sk_err = -error;
return;
}
ctx->asoc->stats.octrlchunks++;
break;
case SCTP_CID_ABORT:
if (sctp_test_T_bit(chunk))
ctx->packet->vtag = ctx->asoc->c.my_vtag;
fallthrough;
/* The following chunks are "response" chunks, i.e.
* they are generated in response to something we
* received. If we are sending these, then we can
* send only 1 packet containing these chunks.
*/
case SCTP_CID_HEARTBEAT_ACK:
case SCTP_CID_SHUTDOWN_ACK:
case SCTP_CID_COOKIE_ACK:
case SCTP_CID_COOKIE_ECHO:
case SCTP_CID_ERROR:
case SCTP_CID_ECN_CWR:
case SCTP_CID_ASCONF_ACK:
one_packet = 1;
fallthrough;
case SCTP_CID_HEARTBEAT:
if (chunk->pmtu_probe) {
error = sctp_packet_singleton(ctx->transport,
chunk, ctx->gfp);
if (!error)
ctx->asoc->stats.octrlchunks++;
break;
}
fallthrough;
case SCTP_CID_SACK:
case SCTP_CID_SHUTDOWN:
case SCTP_CID_ECN_ECNE:
case SCTP_CID_ASCONF:
case SCTP_CID_FWD_TSN:
case SCTP_CID_I_FWD_TSN:
case SCTP_CID_RECONF:
status = sctp_packet_transmit_chunk(ctx->packet, chunk,
one_packet, ctx->gfp);
if (status != SCTP_XMIT_OK) {
/* put the chunk back */
list_add(&chunk->list, &ctx->q->control_chunk_list);
break;
}
ctx->asoc->stats.octrlchunks++;
/* PR-SCTP C5) If a FORWARD TSN is sent, the
* sender MUST assure that at least one T3-rtx
* timer is running.
*/
if (chunk->chunk_hdr->type == SCTP_CID_FWD_TSN ||
chunk->chunk_hdr->type == SCTP_CID_I_FWD_TSN) {
sctp_transport_reset_t3_rtx(ctx->transport);
ctx->transport->last_time_sent = jiffies;
}
if (chunk == ctx->asoc->strreset_chunk)
sctp_transport_reset_reconf_timer(ctx->transport);
break;
default:
/* We built a chunk with an illegal type! */
BUG();
}
}
}
/* Returns false if new data shouldn't be sent */
static bool sctp_outq_flush_rtx(struct sctp_flush_ctx *ctx,
int rtx_timeout)
{
int error, start_timer = 0;
if (ctx->asoc->peer.retran_path->state == SCTP_UNCONFIRMED)
return false;
if (ctx->transport != ctx->asoc->peer.retran_path) {
/* Switch transports & prepare the packet. */
ctx->transport = ctx->asoc->peer.retran_path;
ctx->packet = &ctx->transport->packet;
if (list_empty(&ctx->transport->send_ready))
list_add_tail(&ctx->transport->send_ready,
&ctx->transport_list);
sctp_packet_config(ctx->packet, ctx->asoc->peer.i.init_tag,
ctx->asoc->peer.ecn_capable);
}
error = __sctp_outq_flush_rtx(ctx->q, ctx->packet, rtx_timeout,
&start_timer, ctx->gfp);
if (error < 0)
ctx->asoc->base.sk->sk_err = -error;
if (start_timer) {
sctp_transport_reset_t3_rtx(ctx->transport);
ctx->transport->last_time_sent = jiffies;
}
/* This can happen on COOKIE-ECHO resend. Only
* one chunk can get bundled with a COOKIE-ECHO.
*/
if (ctx->packet->has_cookie_echo)
return false;
/* Don't send new data if there is still data
* waiting to retransmit.
*/
if (!list_empty(&ctx->q->retransmit))
return false;
return true;
}
static void sctp_outq_flush_data(struct sctp_flush_ctx *ctx,
int rtx_timeout)
{
struct sctp_chunk *chunk;
enum sctp_xmit status;
/* Is it OK to send data chunks? */
switch (ctx->asoc->state) {
case SCTP_STATE_COOKIE_ECHOED:
/* Only allow bundling when this packet has a COOKIE-ECHO
* chunk.
*/
if (!ctx->packet || !ctx->packet->has_cookie_echo)
return;
fallthrough;
case SCTP_STATE_ESTABLISHED:
case SCTP_STATE_SHUTDOWN_PENDING:
case SCTP_STATE_SHUTDOWN_RECEIVED:
break;
default:
/* Do nothing. */
return;
}
/* RFC 2960 6.1 Transmission of DATA Chunks
*
* C) When the time comes for the sender to transmit,
* before sending new DATA chunks, the sender MUST
* first transmit any outstanding DATA chunks which
* are marked for retransmission (limited by the
* current cwnd).
*/
if (!list_empty(&ctx->q->retransmit) &&
!sctp_outq_flush_rtx(ctx, rtx_timeout))
return;
/* Apply Max.Burst limitation to the current transport in
* case it will be used for new data. We are going to
* rest it before we return, but we want to apply the limit
* to the currently queued data.
*/
if (ctx->transport)
sctp_transport_burst_limited(ctx->transport);
/* Finally, transmit new packets. */
while ((chunk = sctp_outq_dequeue_data(ctx->q)) != NULL) {
__u32 sid = ntohs(chunk->subh.data_hdr->stream);
__u8 stream_state = SCTP_SO(&ctx->asoc->stream, sid)->state;
/* Has this chunk expired? */
if (sctp_chunk_abandoned(chunk)) {
sctp_sched_dequeue_done(ctx->q, chunk);
sctp_chunk_fail(chunk, 0);
sctp_chunk_free(chunk);
continue;
}
if (stream_state == SCTP_STREAM_CLOSED) {
sctp_outq_head_data(ctx->q, chunk);
break;
}
sctp_outq_select_transport(ctx, chunk);
pr_debug("%s: outq:%p, chunk:%p[%s], tx-tsn:0x%x skb->head:%p skb->users:%d\n",
__func__, ctx->q, chunk, chunk && chunk->chunk_hdr ?
sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)) :
"illegal chunk", ntohl(chunk->subh.data_hdr->tsn),
chunk->skb ? chunk->skb->head : NULL, chunk->skb ?
refcount_read(&chunk->skb->users) : -1);
/* Add the chunk to the packet. */
status = sctp_packet_transmit_chunk(ctx->packet, chunk, 0,
ctx->gfp);
if (status != SCTP_XMIT_OK) {
/* We could not append this chunk, so put
* the chunk back on the output queue.
*/
pr_debug("%s: could not transmit tsn:0x%x, status:%d\n",
__func__, ntohl(chunk->subh.data_hdr->tsn),
status);
sctp_outq_head_data(ctx->q, chunk);
break;
}
/* The sender is in the SHUTDOWN-PENDING state,
* The sender MAY set the I-bit in the DATA
* chunk header.
*/
if (ctx->asoc->state == SCTP_STATE_SHUTDOWN_PENDING)
chunk->chunk_hdr->flags |= SCTP_DATA_SACK_IMM;
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED)
ctx->asoc->stats.ouodchunks++;
else
ctx->asoc->stats.oodchunks++;
/* Only now it's safe to consider this
* chunk as sent, sched-wise.
*/
sctp_sched_dequeue_done(ctx->q, chunk);
list_add_tail(&chunk->transmitted_list,
&ctx->transport->transmitted);
sctp_transport_reset_t3_rtx(ctx->transport);
ctx->transport->last_time_sent = jiffies;
/* Only let one DATA chunk get bundled with a
* COOKIE-ECHO chunk.
*/
if (ctx->packet->has_cookie_echo)
break;
}
}
static void sctp_outq_flush_transports(struct sctp_flush_ctx *ctx)
{
struct sock *sk = ctx->asoc->base.sk;
struct list_head *ltransport;
struct sctp_packet *packet;
struct sctp_transport *t;
int error = 0;
while ((ltransport = sctp_list_dequeue(&ctx->transport_list)) != NULL) {
t = list_entry(ltransport, struct sctp_transport, send_ready);
packet = &t->packet;
if (!sctp_packet_empty(packet)) {
rcu_read_lock();
if (t->dst && __sk_dst_get(sk) != t->dst) {
dst_hold(t->dst);
sk_setup_caps(sk, t->dst);
}
rcu_read_unlock();
error = sctp_packet_transmit(packet, ctx->gfp);
if (error < 0)
ctx->q->asoc->base.sk->sk_err = -error;
}
/* Clear the burst limited state, if any */
sctp_transport_burst_reset(t);
}
}
/* Try to flush an outqueue.
*
* Description: Send everything in q which we legally can, subject to
* congestion limitations.
* * Note: This function can be called from multiple contexts so appropriate
* locking concerns must be made. Today we use the sock lock to protect
* this function.
*/
static void sctp_outq_flush(struct sctp_outq *q, int rtx_timeout, gfp_t gfp)
{
struct sctp_flush_ctx ctx = {
.q = q,
.transport = NULL,
.transport_list = LIST_HEAD_INIT(ctx.transport_list),
.asoc = q->asoc,
.packet = NULL,
.gfp = gfp,
};
/* 6.10 Bundling
* ...
* When bundling control chunks with DATA chunks, an
* endpoint MUST place control chunks first in the outbound
* SCTP packet. The transmitter MUST transmit DATA chunks
* within a SCTP packet in increasing order of TSN.
* ...
*/
sctp_outq_flush_ctrl(&ctx);
if (q->asoc->src_out_of_asoc_ok)
goto sctp_flush_out;
sctp_outq_flush_data(&ctx, rtx_timeout);
sctp_flush_out:
sctp_outq_flush_transports(&ctx);
}
/* Update unack_data based on the incoming SACK chunk */
static void sctp_sack_update_unack_data(struct sctp_association *assoc,
struct sctp_sackhdr *sack)
{
union sctp_sack_variable *frags;
__u16 unack_data;
int i;
unack_data = assoc->next_tsn - assoc->ctsn_ack_point - 1;
frags = (union sctp_sack_variable *)(sack + 1);
for (i = 0; i < ntohs(sack->num_gap_ack_blocks); i++) {
unack_data -= ((ntohs(frags[i].gab.end) -
ntohs(frags[i].gab.start) + 1));
}
assoc->unack_data = unack_data;
}
/* This is where we REALLY process a SACK.
*
* Process the SACK against the outqueue. Mostly, this just frees
* things off the transmitted queue.
*/
int sctp_outq_sack(struct sctp_outq *q, struct sctp_chunk *chunk)
{
struct sctp_association *asoc = q->asoc;
struct sctp_sackhdr *sack = chunk->subh.sack_hdr;
struct sctp_transport *transport;
struct sctp_chunk *tchunk = NULL;
struct list_head *lchunk, *transport_list, *temp;
__u32 sack_ctsn, ctsn, tsn;
__u32 highest_tsn, highest_new_tsn;
__u32 sack_a_rwnd;
unsigned int outstanding;
struct sctp_transport *primary = asoc->peer.primary_path;
int count_of_newacks = 0;
int gap_ack_blocks;
u8 accum_moved = 0;
/* Grab the association's destination address list. */
transport_list = &asoc->peer.transport_addr_list;
/* SCTP path tracepoint for congestion control debugging. */
if (trace_sctp_probe_path_enabled()) {
list_for_each_entry(transport, transport_list, transports)
trace_sctp_probe_path(transport, asoc);
}
sack_ctsn = ntohl(sack->cum_tsn_ack);
gap_ack_blocks = ntohs(sack->num_gap_ack_blocks);
asoc->stats.gapcnt += gap_ack_blocks;
/*
* SFR-CACC algorithm:
* On receipt of a SACK the sender SHOULD execute the
* following statements.
*
* 1) If the cumulative ack in the SACK passes next tsn_at_change
* on the current primary, the CHANGEOVER_ACTIVE flag SHOULD be
* cleared. The CYCLING_CHANGEOVER flag SHOULD also be cleared for
* all destinations.
* 2) If the SACK contains gap acks and the flag CHANGEOVER_ACTIVE
* is set the receiver of the SACK MUST take the following actions:
*
* A) Initialize the cacc_saw_newack to 0 for all destination
* addresses.
*
* Only bother if changeover_active is set. Otherwise, this is
* totally suboptimal to do on every SACK.
*/
if (primary->cacc.changeover_active) {
u8 clear_cycling = 0;
if (TSN_lte(primary->cacc.next_tsn_at_change, sack_ctsn)) {
primary->cacc.changeover_active = 0;
clear_cycling = 1;
}
if (clear_cycling || gap_ack_blocks) {
list_for_each_entry(transport, transport_list,
transports) {
if (clear_cycling)
transport->cacc.cycling_changeover = 0;
if (gap_ack_blocks)
transport->cacc.cacc_saw_newack = 0;
}
}
}
/* Get the highest TSN in the sack. */
highest_tsn = sack_ctsn;
if (gap_ack_blocks) {
union sctp_sack_variable *frags =
(union sctp_sack_variable *)(sack + 1);
highest_tsn += ntohs(frags[gap_ack_blocks - 1].gab.end);
}
if (TSN_lt(asoc->highest_sacked, highest_tsn))
asoc->highest_sacked = highest_tsn;
highest_new_tsn = sack_ctsn;
/* Run through the retransmit queue. Credit bytes received
* and free those chunks that we can.
*/
sctp_check_transmitted(q, &q->retransmit, NULL, NULL, sack, &highest_new_tsn);
/* Run through the transmitted queue.
* Credit bytes received and free those chunks which we can.
*
* This is a MASSIVE candidate for optimization.
*/
list_for_each_entry(transport, transport_list, transports) {
sctp_check_transmitted(q, &transport->transmitted,
transport, &chunk->source, sack,
&highest_new_tsn);
/*
* SFR-CACC algorithm:
* C) Let count_of_newacks be the number of
* destinations for which cacc_saw_newack is set.
*/
if (transport->cacc.cacc_saw_newack)
count_of_newacks++;
}
/* Move the Cumulative TSN Ack Point if appropriate. */
if (TSN_lt(asoc->ctsn_ack_point, sack_ctsn)) {
asoc->ctsn_ack_point = sack_ctsn;
accum_moved = 1;
}
if (gap_ack_blocks) {
if (asoc->fast_recovery && accum_moved)
highest_new_tsn = highest_tsn;
list_for_each_entry(transport, transport_list, transports)
sctp_mark_missing(q, &transport->transmitted, transport,
highest_new_tsn, count_of_newacks);
}
/* Update unack_data field in the assoc. */
sctp_sack_update_unack_data(asoc, sack);
ctsn = asoc->ctsn_ack_point;
/* Throw away stuff rotting on the sack queue. */
list_for_each_safe(lchunk, temp, &q->sacked) {
tchunk = list_entry(lchunk, struct sctp_chunk,
transmitted_list);
tsn = ntohl(tchunk->subh.data_hdr->tsn);
if (TSN_lte(tsn, ctsn)) {
list_del_init(&tchunk->transmitted_list);
if (asoc->peer.prsctp_capable &&
SCTP_PR_PRIO_ENABLED(chunk->sinfo.sinfo_flags))
asoc->sent_cnt_removable--;
sctp_chunk_free(tchunk);
}
}
/* ii) Set rwnd equal to the newly received a_rwnd minus the
* number of bytes still outstanding after processing the
* Cumulative TSN Ack and the Gap Ack Blocks.
*/
sack_a_rwnd = ntohl(sack->a_rwnd);
asoc->peer.zero_window_announced = !sack_a_rwnd;
outstanding = q->outstanding_bytes;
if (outstanding < sack_a_rwnd)
sack_a_rwnd -= outstanding;
else
sack_a_rwnd = 0;
asoc->peer.rwnd = sack_a_rwnd;
asoc->stream.si->generate_ftsn(q, sack_ctsn);
pr_debug("%s: sack cumulative tsn ack:0x%x\n", __func__, sack_ctsn);
pr_debug("%s: cumulative tsn ack of assoc:%p is 0x%x, "
"advertised peer ack point:0x%x\n", __func__, asoc, ctsn,
asoc->adv_peer_ack_point);
return sctp_outq_is_empty(q);
}
/* Is the outqueue empty?
* The queue is empty when we have not pending data, no in-flight data
* and nothing pending retransmissions.
*/
int sctp_outq_is_empty(const struct sctp_outq *q)
{
return q->out_qlen == 0 && q->outstanding_bytes == 0 &&
list_empty(&q->retransmit);
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* Go through a transport's transmitted list or the association's retransmit
* list and move chunks that are acked by the Cumulative TSN Ack to q->sacked.
* The retransmit list will not have an associated transport.
*
* I added coherent debug information output. --xguo
*
* Instead of printing 'sacked' or 'kept' for each TSN on the
* transmitted_queue, we print a range: SACKED: TSN1-TSN2, TSN3, TSN4-TSN5.
* KEPT TSN6-TSN7, etc.
*/
static void sctp_check_transmitted(struct sctp_outq *q,
struct list_head *transmitted_queue,
struct sctp_transport *transport,
union sctp_addr *saddr,
struct sctp_sackhdr *sack,
__u32 *highest_new_tsn_in_sack)
{
struct list_head *lchunk;
struct sctp_chunk *tchunk;
struct list_head tlist;
__u32 tsn;
__u32 sack_ctsn;
__u32 rtt;
__u8 restart_timer = 0;
int bytes_acked = 0;
int migrate_bytes = 0;
bool forward_progress = false;
sack_ctsn = ntohl(sack->cum_tsn_ack);
INIT_LIST_HEAD(&tlist);
/* The while loop will skip empty transmitted queues. */
while (NULL != (lchunk = sctp_list_dequeue(transmitted_queue))) {
tchunk = list_entry(lchunk, struct sctp_chunk,
transmitted_list);
if (sctp_chunk_abandoned(tchunk)) {
/* Move the chunk to abandoned list. */
sctp_insert_list(&q->abandoned, lchunk);
/* If this chunk has not been acked, stop
* considering it as 'outstanding'.
*/
if (transmitted_queue != &q->retransmit &&
!tchunk->tsn_gap_acked) {
if (tchunk->transport)
tchunk->transport->flight_size -=
sctp_data_size(tchunk);
q->outstanding_bytes -= sctp_data_size(tchunk);
}
continue;
}
tsn = ntohl(tchunk->subh.data_hdr->tsn);
if (sctp_acked(sack, tsn)) {
/* If this queue is the retransmit queue, the
* retransmit timer has already reclaimed
* the outstanding bytes for this chunk, so only
* count bytes associated with a transport.
*/
if (transport && !tchunk->tsn_gap_acked) {
/* If this chunk is being used for RTT
* measurement, calculate the RTT and update
* the RTO using this value.
*
* 6.3.1 C5) Karn's algorithm: RTT measurements
* MUST NOT be made using packets that were
* retransmitted (and thus for which it is
* ambiguous whether the reply was for the
* first instance of the packet or a later
* instance).
*/
if (!sctp_chunk_retransmitted(tchunk) &&
tchunk->rtt_in_progress) {
tchunk->rtt_in_progress = 0;
rtt = jiffies - tchunk->sent_at;
sctp_transport_update_rto(transport,
rtt);
}
if (TSN_lte(tsn, sack_ctsn)) {
/*
* SFR-CACC algorithm:
* 2) If the SACK contains gap acks
* and the flag CHANGEOVER_ACTIVE is
* set the receiver of the SACK MUST
* take the following action:
*
* B) For each TSN t being acked that
* has not been acked in any SACK so
* far, set cacc_saw_newack to 1 for
* the destination that the TSN was
* sent to.
*/
if (sack->num_gap_ack_blocks &&
q->asoc->peer.primary_path->cacc.
changeover_active)
transport->cacc.cacc_saw_newack
= 1;
}
}
/* If the chunk hasn't been marked as ACKED,
* mark it and account bytes_acked if the
* chunk had a valid transport (it will not
* have a transport if ASCONF had deleted it
* while DATA was outstanding).
*/
if (!tchunk->tsn_gap_acked) {
tchunk->tsn_gap_acked = 1;
if (TSN_lt(*highest_new_tsn_in_sack, tsn))
*highest_new_tsn_in_sack = tsn;
bytes_acked += sctp_data_size(tchunk);
if (!tchunk->transport)
migrate_bytes += sctp_data_size(tchunk);
forward_progress = true;
}
if (TSN_lte(tsn, sack_ctsn)) {
/* RFC 2960 6.3.2 Retransmission Timer Rules
*
* R3) Whenever a SACK is received
* that acknowledges the DATA chunk
* with the earliest outstanding TSN
* for that address, restart T3-rtx
* timer for that address with its
* current RTO.
*/
restart_timer = 1;
forward_progress = true;
list_add_tail(&tchunk->transmitted_list,
&q->sacked);
} else {
/* RFC2960 7.2.4, sctpimpguide-05 2.8.2
* M2) Each time a SACK arrives reporting
* 'Stray DATA chunk(s)' record the highest TSN
* reported as newly acknowledged, call this
* value 'HighestTSNinSack'. A newly
* acknowledged DATA chunk is one not
* previously acknowledged in a SACK.
*
* When the SCTP sender of data receives a SACK
* chunk that acknowledges, for the first time,
* the receipt of a DATA chunk, all the still
* unacknowledged DATA chunks whose TSN is
* older than that newly acknowledged DATA
* chunk, are qualified as 'Stray DATA chunks'.
*/
list_add_tail(lchunk, &tlist);
}
} else {
if (tchunk->tsn_gap_acked) {
pr_debug("%s: receiver reneged on data TSN:0x%x\n",
__func__, tsn);
tchunk->tsn_gap_acked = 0;
if (tchunk->transport)
bytes_acked -= sctp_data_size(tchunk);
/* RFC 2960 6.3.2 Retransmission Timer Rules
*
* R4) Whenever a SACK is received missing a
* TSN that was previously acknowledged via a
* Gap Ack Block, start T3-rtx for the
* destination address to which the DATA
* chunk was originally
* transmitted if it is not already running.
*/
restart_timer = 1;
}
list_add_tail(lchunk, &tlist);
}
}
if (transport) {
if (bytes_acked) {
struct sctp_association *asoc = transport->asoc;
/* We may have counted DATA that was migrated
* to this transport due to DEL-IP operation.
* Subtract those bytes, since the were never
* send on this transport and shouldn't be
* credited to this transport.
*/
bytes_acked -= migrate_bytes;
/* 8.2. When an outstanding TSN is acknowledged,
* the endpoint shall clear the error counter of
* the destination transport address to which the
* DATA chunk was last sent.
* The association's overall error counter is
* also cleared.
*/
transport->error_count = 0;
transport->asoc->overall_error_count = 0;
forward_progress = true;
/*
* While in SHUTDOWN PENDING, we may have started
* the T5 shutdown guard timer after reaching the
* retransmission limit. Stop that timer as soon
* as the receiver acknowledged any data.
*/
if (asoc->state == SCTP_STATE_SHUTDOWN_PENDING &&
del_timer(&asoc->timers
[SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD]))
sctp_association_put(asoc);
/* Mark the destination transport address as
* active if it is not so marked.
*/
if ((transport->state == SCTP_INACTIVE ||
transport->state == SCTP_UNCONFIRMED) &&
sctp_cmp_addr_exact(&transport->ipaddr, saddr)) {
sctp_assoc_control_transport(
transport->asoc,
transport,
SCTP_TRANSPORT_UP,
SCTP_RECEIVED_SACK);
}
sctp_transport_raise_cwnd(transport, sack_ctsn,
bytes_acked);
transport->flight_size -= bytes_acked;
if (transport->flight_size == 0)
transport->partial_bytes_acked = 0;
q->outstanding_bytes -= bytes_acked + migrate_bytes;
} else {
/* RFC 2960 6.1, sctpimpguide-06 2.15.2
* When a sender is doing zero window probing, it
* should not timeout the association if it continues
* to receive new packets from the receiver. The
* reason is that the receiver MAY keep its window
* closed for an indefinite time.
* A sender is doing zero window probing when the
* receiver's advertised window is zero, and there is
* only one data chunk in flight to the receiver.
*
* Allow the association to timeout while in SHUTDOWN
* PENDING or SHUTDOWN RECEIVED in case the receiver
* stays in zero window mode forever.
*/
if (!q->asoc->peer.rwnd &&
!list_empty(&tlist) &&
(sack_ctsn+2 == q->asoc->next_tsn) &&
q->asoc->state < SCTP_STATE_SHUTDOWN_PENDING) {
pr_debug("%s: sack received for zero window "
"probe:%u\n", __func__, sack_ctsn);
q->asoc->overall_error_count = 0;
transport->error_count = 0;
}
}
/* RFC 2960 6.3.2 Retransmission Timer Rules
*
* R2) Whenever all outstanding data sent to an address have
* been acknowledged, turn off the T3-rtx timer of that
* address.
*/
if (!transport->flight_size) {
if (del_timer(&transport->T3_rtx_timer))
sctp_transport_put(transport);
} else if (restart_timer) {
if (!mod_timer(&transport->T3_rtx_timer,
jiffies + transport->rto))
sctp_transport_hold(transport);
}
if (forward_progress) {
if (transport->dst)
sctp_transport_dst_confirm(transport);
}
}
list_splice(&tlist, transmitted_queue);
}
/* Mark chunks as missing and consequently may get retransmitted. */
static void sctp_mark_missing(struct sctp_outq *q,
struct list_head *transmitted_queue,
struct sctp_transport *transport,
__u32 highest_new_tsn_in_sack,
int count_of_newacks)
{
struct sctp_chunk *chunk;
__u32 tsn;
char do_fast_retransmit = 0;
struct sctp_association *asoc = q->asoc;
struct sctp_transport *primary = asoc->peer.primary_path;
list_for_each_entry(chunk, transmitted_queue, transmitted_list) {
tsn = ntohl(chunk->subh.data_hdr->tsn);
/* RFC 2960 7.2.4, sctpimpguide-05 2.8.2 M3) Examine all
* 'Unacknowledged TSN's', if the TSN number of an
* 'Unacknowledged TSN' is smaller than the 'HighestTSNinSack'
* value, increment the 'TSN.Missing.Report' count on that
* chunk if it has NOT been fast retransmitted or marked for
* fast retransmit already.
*/
if (chunk->fast_retransmit == SCTP_CAN_FRTX &&
!chunk->tsn_gap_acked &&
TSN_lt(tsn, highest_new_tsn_in_sack)) {
/* SFR-CACC may require us to skip marking
* this chunk as missing.
*/
if (!transport || !sctp_cacc_skip(primary,
chunk->transport,
count_of_newacks, tsn)) {
chunk->tsn_missing_report++;
pr_debug("%s: tsn:0x%x missing counter:%d\n",
__func__, tsn, chunk->tsn_missing_report);
}
}
/*
* M4) If any DATA chunk is found to have a
* 'TSN.Missing.Report'
* value larger than or equal to 3, mark that chunk for
* retransmission and start the fast retransmit procedure.
*/
if (chunk->tsn_missing_report >= 3) {
chunk->fast_retransmit = SCTP_NEED_FRTX;
do_fast_retransmit = 1;
}
}
if (transport) {
if (do_fast_retransmit)
sctp_retransmit(q, transport, SCTP_RTXR_FAST_RTX);
pr_debug("%s: transport:%p, cwnd:%d, ssthresh:%d, "
"flight_size:%d, pba:%d\n", __func__, transport,
transport->cwnd, transport->ssthresh,
transport->flight_size, transport->partial_bytes_acked);
}
}
/* Is the given TSN acked by this packet? */
static int sctp_acked(struct sctp_sackhdr *sack, __u32 tsn)
{
__u32 ctsn = ntohl(sack->cum_tsn_ack);
union sctp_sack_variable *frags;
__u16 tsn_offset, blocks;
int i;
if (TSN_lte(tsn, ctsn))
goto pass;
/* 3.3.4 Selective Acknowledgment (SACK) (3):
*
* Gap Ack Blocks:
* These fields contain the Gap Ack Blocks. They are repeated
* for each Gap Ack Block up to the number of Gap Ack Blocks
* defined in the Number of Gap Ack Blocks field. All DATA
* chunks with TSNs greater than or equal to (Cumulative TSN
* Ack + Gap Ack Block Start) and less than or equal to
* (Cumulative TSN Ack + Gap Ack Block End) of each Gap Ack
* Block are assumed to have been received correctly.
*/
frags = (union sctp_sack_variable *)(sack + 1);
blocks = ntohs(sack->num_gap_ack_blocks);
tsn_offset = tsn - ctsn;
for (i = 0; i < blocks; ++i) {
if (tsn_offset >= ntohs(frags[i].gab.start) &&
tsn_offset <= ntohs(frags[i].gab.end))
goto pass;
}
return 0;
pass:
return 1;
}
static inline int sctp_get_skip_pos(struct sctp_fwdtsn_skip *skiplist,
int nskips, __be16 stream)
{
int i;
for (i = 0; i < nskips; i++) {
if (skiplist[i].stream == stream)
return i;
}
return i;
}
/* Create and add a fwdtsn chunk to the outq's control queue if needed. */
void sctp_generate_fwdtsn(struct sctp_outq *q, __u32 ctsn)
{
struct sctp_association *asoc = q->asoc;
struct sctp_chunk *ftsn_chunk = NULL;
struct sctp_fwdtsn_skip ftsn_skip_arr[10];
int nskips = 0;
int skip_pos = 0;
__u32 tsn;
struct sctp_chunk *chunk;
struct list_head *lchunk, *temp;
if (!asoc->peer.prsctp_capable)
return;
/* PR-SCTP C1) Let SackCumAck be the Cumulative TSN ACK carried in the
* received SACK.
*
* If (Advanced.Peer.Ack.Point < SackCumAck), then update
* Advanced.Peer.Ack.Point to be equal to SackCumAck.
*/
if (TSN_lt(asoc->adv_peer_ack_point, ctsn))
asoc->adv_peer_ack_point = ctsn;
/* PR-SCTP C2) Try to further advance the "Advanced.Peer.Ack.Point"
* locally, that is, to move "Advanced.Peer.Ack.Point" up as long as
* the chunk next in the out-queue space is marked as "abandoned" as
* shown in the following example:
*
* Assuming that a SACK arrived with the Cumulative TSN ACK 102
* and the Advanced.Peer.Ack.Point is updated to this value:
*
* out-queue at the end of ==> out-queue after Adv.Ack.Point
* normal SACK processing local advancement
* ... ...
* Adv.Ack.Pt-> 102 acked 102 acked
* 103 abandoned 103 abandoned
* 104 abandoned Adv.Ack.P-> 104 abandoned
* 105 105
* 106 acked 106 acked
* ... ...
*
* In this example, the data sender successfully advanced the
* "Advanced.Peer.Ack.Point" from 102 to 104 locally.
*/
list_for_each_safe(lchunk, temp, &q->abandoned) {
chunk = list_entry(lchunk, struct sctp_chunk,
transmitted_list);
tsn = ntohl(chunk->subh.data_hdr->tsn);
/* Remove any chunks in the abandoned queue that are acked by
* the ctsn.
*/
if (TSN_lte(tsn, ctsn)) {
list_del_init(lchunk);
sctp_chunk_free(chunk);
} else {
if (TSN_lte(tsn, asoc->adv_peer_ack_point+1)) {
asoc->adv_peer_ack_point = tsn;
if (chunk->chunk_hdr->flags &
SCTP_DATA_UNORDERED)
continue;
skip_pos = sctp_get_skip_pos(&ftsn_skip_arr[0],
nskips,
chunk->subh.data_hdr->stream);
ftsn_skip_arr[skip_pos].stream =
chunk->subh.data_hdr->stream;
ftsn_skip_arr[skip_pos].ssn =
chunk->subh.data_hdr->ssn;
if (skip_pos == nskips)
nskips++;
if (nskips == 10)
break;
} else
break;
}
}
/* PR-SCTP C3) If, after step C1 and C2, the "Advanced.Peer.Ack.Point"
* is greater than the Cumulative TSN ACK carried in the received
* SACK, the data sender MUST send the data receiver a FORWARD TSN
* chunk containing the latest value of the
* "Advanced.Peer.Ack.Point".
*
* C4) For each "abandoned" TSN the sender of the FORWARD TSN SHOULD
* list each stream and sequence number in the forwarded TSN. This
* information will enable the receiver to easily find any
* stranded TSN's waiting on stream reorder queues. Each stream
* SHOULD only be reported once; this means that if multiple
* abandoned messages occur in the same stream then only the
* highest abandoned stream sequence number is reported. If the
* total size of the FORWARD TSN does NOT fit in a single MTU then
* the sender of the FORWARD TSN SHOULD lower the
* Advanced.Peer.Ack.Point to the last TSN that will fit in a
* single MTU.
*/
if (asoc->adv_peer_ack_point > ctsn)
ftsn_chunk = sctp_make_fwdtsn(asoc, asoc->adv_peer_ack_point,
nskips, &ftsn_skip_arr[0]);
if (ftsn_chunk) {
list_add_tail(&ftsn_chunk->list, &q->control_chunk_list);
SCTP_INC_STATS(asoc->base.net, SCTP_MIB_OUTCTRLCHUNKS);
}
}
| linux-master | net/sctp/outqueue.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
*
* This file is part of the SCTP kernel implementation
*
* Support for memory object debugging. This allows one to monitor the
* object allocations/deallocations for types instrumented for this
* via the proc fs.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Jon Grimm <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <net/sctp/sctp.h>
/*
* Global counters to count raw object allocation counts.
* To add new counters, choose a unique suffix for the variable
* name as the helper macros key off this suffix to make
* life easier for the programmer.
*/
SCTP_DBG_OBJCNT(sock);
SCTP_DBG_OBJCNT(ep);
SCTP_DBG_OBJCNT(transport);
SCTP_DBG_OBJCNT(assoc);
SCTP_DBG_OBJCNT(bind_addr);
SCTP_DBG_OBJCNT(bind_bucket);
SCTP_DBG_OBJCNT(chunk);
SCTP_DBG_OBJCNT(addr);
SCTP_DBG_OBJCNT(datamsg);
SCTP_DBG_OBJCNT(keys);
/* An array to make it easy to pretty print the debug information
* to the proc fs.
*/
static struct sctp_dbg_objcnt_entry sctp_dbg_objcnt[] = {
SCTP_DBG_OBJCNT_ENTRY(sock),
SCTP_DBG_OBJCNT_ENTRY(ep),
SCTP_DBG_OBJCNT_ENTRY(assoc),
SCTP_DBG_OBJCNT_ENTRY(transport),
SCTP_DBG_OBJCNT_ENTRY(chunk),
SCTP_DBG_OBJCNT_ENTRY(bind_addr),
SCTP_DBG_OBJCNT_ENTRY(bind_bucket),
SCTP_DBG_OBJCNT_ENTRY(addr),
SCTP_DBG_OBJCNT_ENTRY(datamsg),
SCTP_DBG_OBJCNT_ENTRY(keys),
};
/* Callback from procfs to read out objcount information.
* Walk through the entries in the sctp_dbg_objcnt array, dumping
* the raw object counts for each monitored type.
*/
static int sctp_objcnt_seq_show(struct seq_file *seq, void *v)
{
int i;
i = (int)*(loff_t *)v;
seq_setwidth(seq, 127);
seq_printf(seq, "%s: %d", sctp_dbg_objcnt[i].label,
atomic_read(sctp_dbg_objcnt[i].counter));
seq_pad(seq, '\n');
return 0;
}
static void *sctp_objcnt_seq_start(struct seq_file *seq, loff_t *pos)
{
return (*pos >= ARRAY_SIZE(sctp_dbg_objcnt)) ? NULL : (void *)pos;
}
static void sctp_objcnt_seq_stop(struct seq_file *seq, void *v)
{
}
static void *sctp_objcnt_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return (*pos >= ARRAY_SIZE(sctp_dbg_objcnt)) ? NULL : (void *)pos;
}
static const struct seq_operations sctp_objcnt_seq_ops = {
.start = sctp_objcnt_seq_start,
.next = sctp_objcnt_seq_next,
.stop = sctp_objcnt_seq_stop,
.show = sctp_objcnt_seq_show,
};
/* Initialize the objcount in the proc filesystem. */
void sctp_dbg_objcnt_init(struct net *net)
{
struct proc_dir_entry *ent;
ent = proc_create_seq("sctp_dbg_objcnt", 0,
net->sctp.proc_net_sctp, &sctp_objcnt_seq_ops);
if (!ent)
pr_warn("sctp_dbg_objcnt: Unable to create /proc entry.\n");
}
| linux-master | net/sctp/objcnt.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* Copyright (c) 2003 International Business Machines, Corp.
*
* This file is part of the SCTP kernel implementation
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Sridhar Samudrala <[email protected]>
*/
#include <linux/types.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/export.h>
#include <net/sctp/sctp.h>
#include <net/ip.h> /* for snmp_fold_field */
static const struct snmp_mib sctp_snmp_list[] = {
SNMP_MIB_ITEM("SctpCurrEstab", SCTP_MIB_CURRESTAB),
SNMP_MIB_ITEM("SctpActiveEstabs", SCTP_MIB_ACTIVEESTABS),
SNMP_MIB_ITEM("SctpPassiveEstabs", SCTP_MIB_PASSIVEESTABS),
SNMP_MIB_ITEM("SctpAborteds", SCTP_MIB_ABORTEDS),
SNMP_MIB_ITEM("SctpShutdowns", SCTP_MIB_SHUTDOWNS),
SNMP_MIB_ITEM("SctpOutOfBlues", SCTP_MIB_OUTOFBLUES),
SNMP_MIB_ITEM("SctpChecksumErrors", SCTP_MIB_CHECKSUMERRORS),
SNMP_MIB_ITEM("SctpOutCtrlChunks", SCTP_MIB_OUTCTRLCHUNKS),
SNMP_MIB_ITEM("SctpOutOrderChunks", SCTP_MIB_OUTORDERCHUNKS),
SNMP_MIB_ITEM("SctpOutUnorderChunks", SCTP_MIB_OUTUNORDERCHUNKS),
SNMP_MIB_ITEM("SctpInCtrlChunks", SCTP_MIB_INCTRLCHUNKS),
SNMP_MIB_ITEM("SctpInOrderChunks", SCTP_MIB_INORDERCHUNKS),
SNMP_MIB_ITEM("SctpInUnorderChunks", SCTP_MIB_INUNORDERCHUNKS),
SNMP_MIB_ITEM("SctpFragUsrMsgs", SCTP_MIB_FRAGUSRMSGS),
SNMP_MIB_ITEM("SctpReasmUsrMsgs", SCTP_MIB_REASMUSRMSGS),
SNMP_MIB_ITEM("SctpOutSCTPPacks", SCTP_MIB_OUTSCTPPACKS),
SNMP_MIB_ITEM("SctpInSCTPPacks", SCTP_MIB_INSCTPPACKS),
SNMP_MIB_ITEM("SctpT1InitExpireds", SCTP_MIB_T1_INIT_EXPIREDS),
SNMP_MIB_ITEM("SctpT1CookieExpireds", SCTP_MIB_T1_COOKIE_EXPIREDS),
SNMP_MIB_ITEM("SctpT2ShutdownExpireds", SCTP_MIB_T2_SHUTDOWN_EXPIREDS),
SNMP_MIB_ITEM("SctpT3RtxExpireds", SCTP_MIB_T3_RTX_EXPIREDS),
SNMP_MIB_ITEM("SctpT4RtoExpireds", SCTP_MIB_T4_RTO_EXPIREDS),
SNMP_MIB_ITEM("SctpT5ShutdownGuardExpireds", SCTP_MIB_T5_SHUTDOWN_GUARD_EXPIREDS),
SNMP_MIB_ITEM("SctpDelaySackExpireds", SCTP_MIB_DELAY_SACK_EXPIREDS),
SNMP_MIB_ITEM("SctpAutocloseExpireds", SCTP_MIB_AUTOCLOSE_EXPIREDS),
SNMP_MIB_ITEM("SctpT3Retransmits", SCTP_MIB_T3_RETRANSMITS),
SNMP_MIB_ITEM("SctpPmtudRetransmits", SCTP_MIB_PMTUD_RETRANSMITS),
SNMP_MIB_ITEM("SctpFastRetransmits", SCTP_MIB_FAST_RETRANSMITS),
SNMP_MIB_ITEM("SctpInPktSoftirq", SCTP_MIB_IN_PKT_SOFTIRQ),
SNMP_MIB_ITEM("SctpInPktBacklog", SCTP_MIB_IN_PKT_BACKLOG),
SNMP_MIB_ITEM("SctpInPktDiscards", SCTP_MIB_IN_PKT_DISCARDS),
SNMP_MIB_ITEM("SctpInDataChunkDiscards", SCTP_MIB_IN_DATA_CHUNK_DISCARDS),
SNMP_MIB_SENTINEL
};
/* Display sctp snmp mib statistics(/proc/net/sctp/snmp). */
static int sctp_snmp_seq_show(struct seq_file *seq, void *v)
{
unsigned long buff[SCTP_MIB_MAX];
struct net *net = seq->private;
int i;
memset(buff, 0, sizeof(unsigned long) * SCTP_MIB_MAX);
snmp_get_cpu_field_batch(buff, sctp_snmp_list,
net->sctp.sctp_statistics);
for (i = 0; sctp_snmp_list[i].name; i++)
seq_printf(seq, "%-32s\t%ld\n", sctp_snmp_list[i].name,
buff[i]);
return 0;
}
/* Dump local addresses of an association/endpoint. */
static void sctp_seq_dump_local_addrs(struct seq_file *seq, struct sctp_ep_common *epb)
{
struct sctp_association *asoc;
struct sctp_sockaddr_entry *laddr;
struct sctp_transport *peer;
union sctp_addr *addr, *primary = NULL;
struct sctp_af *af;
if (epb->type == SCTP_EP_TYPE_ASSOCIATION) {
asoc = sctp_assoc(epb);
peer = asoc->peer.primary_path;
if (unlikely(peer == NULL)) {
WARN(1, "Association %p with NULL primary path!\n", asoc);
return;
}
primary = &peer->saddr;
}
rcu_read_lock();
list_for_each_entry_rcu(laddr, &epb->bind_addr.address_list, list) {
if (!laddr->valid)
continue;
addr = &laddr->a;
af = sctp_get_af_specific(addr->sa.sa_family);
if (primary && af->cmp_addr(addr, primary)) {
seq_printf(seq, "*");
}
af->seq_dump_addr(seq, addr);
}
rcu_read_unlock();
}
/* Dump remote addresses of an association. */
static void sctp_seq_dump_remote_addrs(struct seq_file *seq, struct sctp_association *assoc)
{
struct sctp_transport *transport;
union sctp_addr *addr, *primary;
struct sctp_af *af;
primary = &assoc->peer.primary_addr;
list_for_each_entry_rcu(transport, &assoc->peer.transport_addr_list,
transports) {
addr = &transport->ipaddr;
af = sctp_get_af_specific(addr->sa.sa_family);
if (af->cmp_addr(addr, primary)) {
seq_printf(seq, "*");
}
af->seq_dump_addr(seq, addr);
}
}
static void *sctp_eps_seq_start(struct seq_file *seq, loff_t *pos)
{
if (*pos >= sctp_ep_hashsize)
return NULL;
if (*pos < 0)
*pos = 0;
if (*pos == 0)
seq_printf(seq, " ENDPT SOCK STY SST HBKT LPORT UID INODE LADDRS\n");
return (void *)pos;
}
static void sctp_eps_seq_stop(struct seq_file *seq, void *v)
{
}
static void *sctp_eps_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
if (++*pos >= sctp_ep_hashsize)
return NULL;
return pos;
}
/* Display sctp endpoints (/proc/net/sctp/eps). */
static int sctp_eps_seq_show(struct seq_file *seq, void *v)
{
struct sctp_hashbucket *head;
struct sctp_endpoint *ep;
struct sock *sk;
int hash = *(loff_t *)v;
if (hash >= sctp_ep_hashsize)
return -ENOMEM;
head = &sctp_ep_hashtable[hash];
read_lock_bh(&head->lock);
sctp_for_each_hentry(ep, &head->chain) {
sk = ep->base.sk;
if (!net_eq(sock_net(sk), seq_file_net(seq)))
continue;
seq_printf(seq, "%8pK %8pK %-3d %-3d %-4d %-5d %5u %5lu ", ep, sk,
sctp_sk(sk)->type, sk->sk_state, hash,
ep->base.bind_addr.port,
from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk)),
sock_i_ino(sk));
sctp_seq_dump_local_addrs(seq, &ep->base);
seq_printf(seq, "\n");
}
read_unlock_bh(&head->lock);
return 0;
}
static const struct seq_operations sctp_eps_ops = {
.start = sctp_eps_seq_start,
.next = sctp_eps_seq_next,
.stop = sctp_eps_seq_stop,
.show = sctp_eps_seq_show,
};
struct sctp_ht_iter {
struct seq_net_private p;
struct rhashtable_iter hti;
};
static void *sctp_transport_seq_start(struct seq_file *seq, loff_t *pos)
{
struct sctp_ht_iter *iter = seq->private;
sctp_transport_walk_start(&iter->hti);
return sctp_transport_get_idx(seq_file_net(seq), &iter->hti, *pos);
}
static void sctp_transport_seq_stop(struct seq_file *seq, void *v)
{
struct sctp_ht_iter *iter = seq->private;
if (v && v != SEQ_START_TOKEN) {
struct sctp_transport *transport = v;
sctp_transport_put(transport);
}
sctp_transport_walk_stop(&iter->hti);
}
static void *sctp_transport_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct sctp_ht_iter *iter = seq->private;
if (v && v != SEQ_START_TOKEN) {
struct sctp_transport *transport = v;
sctp_transport_put(transport);
}
++*pos;
return sctp_transport_get_next(seq_file_net(seq), &iter->hti);
}
/* Display sctp associations (/proc/net/sctp/assocs). */
static int sctp_assocs_seq_show(struct seq_file *seq, void *v)
{
struct sctp_transport *transport;
struct sctp_association *assoc;
struct sctp_ep_common *epb;
struct sock *sk;
if (v == SEQ_START_TOKEN) {
seq_printf(seq, " ASSOC SOCK STY SST ST HBKT "
"ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT "
"RPORT LADDRS <-> RADDRS "
"HBINT INS OUTS MAXRT T1X T2X RTXC "
"wmema wmemq sndbuf rcvbuf\n");
return 0;
}
transport = (struct sctp_transport *)v;
assoc = transport->asoc;
epb = &assoc->base;
sk = epb->sk;
seq_printf(seq,
"%8pK %8pK %-3d %-3d %-2d %-4d "
"%4d %8d %8d %7u %5lu %-5d %5d ",
assoc, sk, sctp_sk(sk)->type, sk->sk_state,
assoc->state, 0,
assoc->assoc_id,
assoc->sndbuf_used,
atomic_read(&assoc->rmem_alloc),
from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk)),
sock_i_ino(sk),
epb->bind_addr.port,
assoc->peer.port);
seq_printf(seq, " ");
sctp_seq_dump_local_addrs(seq, epb);
seq_printf(seq, "<-> ");
sctp_seq_dump_remote_addrs(seq, assoc);
seq_printf(seq, "\t%8lu %5d %5d %4d %4d %4d %8d "
"%8d %8d %8d %8d",
assoc->hbinterval, assoc->stream.incnt,
assoc->stream.outcnt, assoc->max_retrans,
assoc->init_retries, assoc->shutdown_retries,
assoc->rtx_data_chunks,
refcount_read(&sk->sk_wmem_alloc),
READ_ONCE(sk->sk_wmem_queued),
sk->sk_sndbuf,
sk->sk_rcvbuf);
seq_printf(seq, "\n");
return 0;
}
static const struct seq_operations sctp_assoc_ops = {
.start = sctp_transport_seq_start,
.next = sctp_transport_seq_next,
.stop = sctp_transport_seq_stop,
.show = sctp_assocs_seq_show,
};
static int sctp_remaddr_seq_show(struct seq_file *seq, void *v)
{
struct sctp_association *assoc;
struct sctp_transport *transport, *tsp;
if (v == SEQ_START_TOKEN) {
seq_printf(seq, "ADDR ASSOC_ID HB_ACT RTO MAX_PATH_RTX "
"REM_ADDR_RTX START STATE\n");
return 0;
}
transport = (struct sctp_transport *)v;
assoc = transport->asoc;
list_for_each_entry_rcu(tsp, &assoc->peer.transport_addr_list,
transports) {
/*
* The remote address (ADDR)
*/
tsp->af_specific->seq_dump_addr(seq, &tsp->ipaddr);
seq_printf(seq, " ");
/*
* The association ID (ASSOC_ID)
*/
seq_printf(seq, "%d ", tsp->asoc->assoc_id);
/*
* If the Heartbeat is active (HB_ACT)
* Note: 1 = Active, 0 = Inactive
*/
seq_printf(seq, "%d ", timer_pending(&tsp->hb_timer));
/*
* Retransmit time out (RTO)
*/
seq_printf(seq, "%lu ", tsp->rto);
/*
* Maximum path retransmit count (PATH_MAX_RTX)
*/
seq_printf(seq, "%d ", tsp->pathmaxrxt);
/*
* remote address retransmit count (REM_ADDR_RTX)
* Note: We don't have a way to tally this at the moment
* so lets just leave it as zero for the moment
*/
seq_puts(seq, "0 ");
/*
* remote address start time (START). This is also not
* currently implemented, but we can record it with a
* jiffies marker in a subsequent patch
*/
seq_puts(seq, "0 ");
/*
* The current state of this destination. I.e.
* SCTP_ACTIVE, SCTP_INACTIVE, ...
*/
seq_printf(seq, "%d", tsp->state);
seq_printf(seq, "\n");
}
return 0;
}
static const struct seq_operations sctp_remaddr_ops = {
.start = sctp_transport_seq_start,
.next = sctp_transport_seq_next,
.stop = sctp_transport_seq_stop,
.show = sctp_remaddr_seq_show,
};
/* Set up the proc fs entry for the SCTP protocol. */
int __net_init sctp_proc_init(struct net *net)
{
net->sctp.proc_net_sctp = proc_net_mkdir(net, "sctp", net->proc_net);
if (!net->sctp.proc_net_sctp)
return -ENOMEM;
if (!proc_create_net_single("snmp", 0444, net->sctp.proc_net_sctp,
sctp_snmp_seq_show, NULL))
goto cleanup;
if (!proc_create_net("eps", 0444, net->sctp.proc_net_sctp,
&sctp_eps_ops, sizeof(struct seq_net_private)))
goto cleanup;
if (!proc_create_net("assocs", 0444, net->sctp.proc_net_sctp,
&sctp_assoc_ops, sizeof(struct sctp_ht_iter)))
goto cleanup;
if (!proc_create_net("remaddr", 0444, net->sctp.proc_net_sctp,
&sctp_remaddr_ops, sizeof(struct sctp_ht_iter)))
goto cleanup;
return 0;
cleanup:
remove_proc_subtree("sctp", net->proc_net);
net->sctp.proc_net_sctp = NULL;
return -ENOMEM;
}
| linux-master | net/sctp/proc.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
*
* This file is part of the SCTP kernel implementation
*
* These functions manipulate sctp tsn mapping array.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Jon Grimm <[email protected]>
* Karl Knutson <[email protected]>
* Sridhar Samudrala <[email protected]>
*/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/bitmap.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
static void sctp_tsnmap_update(struct sctp_tsnmap *map);
static void sctp_tsnmap_find_gap_ack(unsigned long *map, __u16 off,
__u16 len, __u16 *start, __u16 *end);
static int sctp_tsnmap_grow(struct sctp_tsnmap *map, u16 size);
/* Initialize a block of memory as a tsnmap. */
struct sctp_tsnmap *sctp_tsnmap_init(struct sctp_tsnmap *map, __u16 len,
__u32 initial_tsn, gfp_t gfp)
{
if (!map->tsn_map) {
map->tsn_map = kzalloc(len>>3, gfp);
if (map->tsn_map == NULL)
return NULL;
map->len = len;
} else {
bitmap_zero(map->tsn_map, map->len);
}
/* Keep track of TSNs represented by tsn_map. */
map->base_tsn = initial_tsn;
map->cumulative_tsn_ack_point = initial_tsn - 1;
map->max_tsn_seen = map->cumulative_tsn_ack_point;
map->num_dup_tsns = 0;
return map;
}
void sctp_tsnmap_free(struct sctp_tsnmap *map)
{
map->len = 0;
kfree(map->tsn_map);
}
/* Test the tracking state of this TSN.
* Returns:
* 0 if the TSN has not yet been seen
* >0 if the TSN has been seen (duplicate)
* <0 if the TSN is invalid (too large to track)
*/
int sctp_tsnmap_check(const struct sctp_tsnmap *map, __u32 tsn)
{
u32 gap;
/* Check to see if this is an old TSN */
if (TSN_lte(tsn, map->cumulative_tsn_ack_point))
return 1;
/* Verify that we can hold this TSN and that it will not
* overflow our map
*/
if (!TSN_lt(tsn, map->base_tsn + SCTP_TSN_MAP_SIZE))
return -1;
/* Calculate the index into the mapping arrays. */
gap = tsn - map->base_tsn;
/* Check to see if TSN has already been recorded. */
if (gap < map->len && test_bit(gap, map->tsn_map))
return 1;
else
return 0;
}
/* Mark this TSN as seen. */
int sctp_tsnmap_mark(struct sctp_tsnmap *map, __u32 tsn,
struct sctp_transport *trans)
{
u16 gap;
if (TSN_lt(tsn, map->base_tsn))
return 0;
gap = tsn - map->base_tsn;
if (gap >= map->len && !sctp_tsnmap_grow(map, gap + 1))
return -ENOMEM;
if (!sctp_tsnmap_has_gap(map) && gap == 0) {
/* In this case the map has no gaps and the tsn we are
* recording is the next expected tsn. We don't touch
* the map but simply bump the values.
*/
map->max_tsn_seen++;
map->cumulative_tsn_ack_point++;
if (trans)
trans->sack_generation =
trans->asoc->peer.sack_generation;
map->base_tsn++;
} else {
/* Either we already have a gap, or about to record a gap, so
* have work to do.
*
* Bump the max.
*/
if (TSN_lt(map->max_tsn_seen, tsn))
map->max_tsn_seen = tsn;
/* Mark the TSN as received. */
set_bit(gap, map->tsn_map);
/* Go fixup any internal TSN mapping variables including
* cumulative_tsn_ack_point.
*/
sctp_tsnmap_update(map);
}
return 0;
}
/* Initialize a Gap Ack Block iterator from memory being provided. */
static void sctp_tsnmap_iter_init(const struct sctp_tsnmap *map,
struct sctp_tsnmap_iter *iter)
{
/* Only start looking one past the Cumulative TSN Ack Point. */
iter->start = map->cumulative_tsn_ack_point + 1;
}
/* Get the next Gap Ack Blocks. Returns 0 if there was not another block
* to get.
*/
static int sctp_tsnmap_next_gap_ack(const struct sctp_tsnmap *map,
struct sctp_tsnmap_iter *iter,
__u16 *start, __u16 *end)
{
int ended = 0;
__u16 start_ = 0, end_ = 0, offset;
/* If there are no more gap acks possible, get out fast. */
if (TSN_lte(map->max_tsn_seen, iter->start))
return 0;
offset = iter->start - map->base_tsn;
sctp_tsnmap_find_gap_ack(map->tsn_map, offset, map->len,
&start_, &end_);
/* The Gap Ack Block happens to end at the end of the map. */
if (start_ && !end_)
end_ = map->len - 1;
/* If we found a Gap Ack Block, return the start and end and
* bump the iterator forward.
*/
if (end_) {
/* Fix up the start and end based on the
* Cumulative TSN Ack which is always 1 behind base.
*/
*start = start_ + 1;
*end = end_ + 1;
/* Move the iterator forward. */
iter->start = map->cumulative_tsn_ack_point + *end + 1;
ended = 1;
}
return ended;
}
/* Mark this and any lower TSN as seen. */
void sctp_tsnmap_skip(struct sctp_tsnmap *map, __u32 tsn)
{
u32 gap;
if (TSN_lt(tsn, map->base_tsn))
return;
if (!TSN_lt(tsn, map->base_tsn + SCTP_TSN_MAP_SIZE))
return;
/* Bump the max. */
if (TSN_lt(map->max_tsn_seen, tsn))
map->max_tsn_seen = tsn;
gap = tsn - map->base_tsn + 1;
map->base_tsn += gap;
map->cumulative_tsn_ack_point += gap;
if (gap >= map->len) {
/* If our gap is larger then the map size, just
* zero out the map.
*/
bitmap_zero(map->tsn_map, map->len);
} else {
/* If the gap is smaller than the map size,
* shift the map by 'gap' bits and update further.
*/
bitmap_shift_right(map->tsn_map, map->tsn_map, gap, map->len);
sctp_tsnmap_update(map);
}
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* This private helper function updates the tsnmap buffers and
* the Cumulative TSN Ack Point.
*/
static void sctp_tsnmap_update(struct sctp_tsnmap *map)
{
u16 len;
unsigned long zero_bit;
len = map->max_tsn_seen - map->cumulative_tsn_ack_point;
zero_bit = find_first_zero_bit(map->tsn_map, len);
if (!zero_bit)
return; /* The first 0-bit is bit 0. nothing to do */
map->base_tsn += zero_bit;
map->cumulative_tsn_ack_point += zero_bit;
bitmap_shift_right(map->tsn_map, map->tsn_map, zero_bit, map->len);
}
/* How many data chunks are we missing from our peer?
*/
__u16 sctp_tsnmap_pending(struct sctp_tsnmap *map)
{
__u32 cum_tsn = map->cumulative_tsn_ack_point;
__u32 max_tsn = map->max_tsn_seen;
__u32 base_tsn = map->base_tsn;
__u16 pending_data;
u32 gap;
pending_data = max_tsn - cum_tsn;
gap = max_tsn - base_tsn;
if (gap == 0 || gap >= map->len)
goto out;
pending_data -= bitmap_weight(map->tsn_map, gap + 1);
out:
return pending_data;
}
/* This is a private helper for finding Gap Ack Blocks. It searches a
* single array for the start and end of a Gap Ack Block.
*
* The flags "started" and "ended" tell is if we found the beginning
* or (respectively) the end of a Gap Ack Block.
*/
static void sctp_tsnmap_find_gap_ack(unsigned long *map, __u16 off,
__u16 len, __u16 *start, __u16 *end)
{
int i = off;
/* Look through the entire array, but break out
* early if we have found the end of the Gap Ack Block.
*/
/* Also, stop looking past the maximum TSN seen. */
/* Look for the start. */
i = find_next_bit(map, len, off);
if (i < len)
*start = i;
/* Look for the end. */
if (*start) {
/* We have found the start, let's find the
* end. If we find the end, break out.
*/
i = find_next_zero_bit(map, len, i);
if (i < len)
*end = i - 1;
}
}
/* Renege that we have seen a TSN. */
void sctp_tsnmap_renege(struct sctp_tsnmap *map, __u32 tsn)
{
u32 gap;
if (TSN_lt(tsn, map->base_tsn))
return;
/* Assert: TSN is in range. */
if (!TSN_lt(tsn, map->base_tsn + map->len))
return;
gap = tsn - map->base_tsn;
/* Pretend we never saw the TSN. */
clear_bit(gap, map->tsn_map);
}
/* How many gap ack blocks do we have recorded? */
__u16 sctp_tsnmap_num_gabs(struct sctp_tsnmap *map,
struct sctp_gap_ack_block *gabs)
{
struct sctp_tsnmap_iter iter;
int ngaps = 0;
/* Refresh the gap ack information. */
if (sctp_tsnmap_has_gap(map)) {
__u16 start = 0, end = 0;
sctp_tsnmap_iter_init(map, &iter);
while (sctp_tsnmap_next_gap_ack(map, &iter,
&start,
&end)) {
gabs[ngaps].start = htons(start);
gabs[ngaps].end = htons(end);
ngaps++;
if (ngaps >= SCTP_MAX_GABS)
break;
}
}
return ngaps;
}
static int sctp_tsnmap_grow(struct sctp_tsnmap *map, u16 size)
{
unsigned long *new;
unsigned long inc;
u16 len;
if (size > SCTP_TSN_MAP_SIZE)
return 0;
inc = ALIGN((size - map->len), BITS_PER_LONG) + SCTP_TSN_MAP_INCREMENT;
len = min_t(u16, map->len + inc, SCTP_TSN_MAP_SIZE);
new = kzalloc(len>>3, GFP_ATOMIC);
if (!new)
return 0;
bitmap_copy(new, map->tsn_map,
map->max_tsn_seen - map->cumulative_tsn_ack_point);
kfree(map->tsn_map);
map->tsn_map = new;
map->len = len;
return 1;
}
| linux-master | net/sctp/tsnmap.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2002 International Business Machines, Corp.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 Nokia, Inc.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This file is part of the SCTP kernel implementation
*
* This abstraction represents an SCTP endpoint.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Jon Grimm <[email protected]>
* Daisy Chang <[email protected]>
* Dajiang Zhang <[email protected]>
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <linux/random.h> /* get_random_bytes() */
#include <net/sock.h>
#include <net/ipv6.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
/* Forward declarations for internal helpers. */
static void sctp_endpoint_bh_rcv(struct work_struct *work);
/*
* Initialize the base fields of the endpoint structure.
*/
static struct sctp_endpoint *sctp_endpoint_init(struct sctp_endpoint *ep,
struct sock *sk,
gfp_t gfp)
{
struct net *net = sock_net(sk);
struct sctp_shared_key *null_key;
ep->digest = kzalloc(SCTP_SIGNATURE_SIZE, gfp);
if (!ep->digest)
return NULL;
ep->asconf_enable = net->sctp.addip_enable;
ep->auth_enable = net->sctp.auth_enable;
if (ep->auth_enable) {
if (sctp_auth_init(ep, gfp))
goto nomem;
if (ep->asconf_enable) {
sctp_auth_ep_add_chunkid(ep, SCTP_CID_ASCONF);
sctp_auth_ep_add_chunkid(ep, SCTP_CID_ASCONF_ACK);
}
}
/* Initialize the base structure. */
/* What type of endpoint are we? */
ep->base.type = SCTP_EP_TYPE_SOCKET;
/* Initialize the basic object fields. */
refcount_set(&ep->base.refcnt, 1);
ep->base.dead = false;
/* Create an input queue. */
sctp_inq_init(&ep->base.inqueue);
/* Set its top-half handler */
sctp_inq_set_th_handler(&ep->base.inqueue, sctp_endpoint_bh_rcv);
/* Initialize the bind addr area */
sctp_bind_addr_init(&ep->base.bind_addr, 0);
/* Create the lists of associations. */
INIT_LIST_HEAD(&ep->asocs);
/* Use SCTP specific send buffer space queues. */
ep->sndbuf_policy = net->sctp.sndbuf_policy;
sk->sk_data_ready = sctp_data_ready;
sk->sk_write_space = sctp_write_space;
sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
/* Get the receive buffer policy for this endpoint */
ep->rcvbuf_policy = net->sctp.rcvbuf_policy;
/* Initialize the secret key used with cookie. */
get_random_bytes(ep->secret_key, sizeof(ep->secret_key));
/* SCTP-AUTH extensions*/
INIT_LIST_HEAD(&ep->endpoint_shared_keys);
null_key = sctp_auth_shkey_create(0, gfp);
if (!null_key)
goto nomem_shkey;
list_add(&null_key->key_list, &ep->endpoint_shared_keys);
/* Add the null key to the endpoint shared keys list and
* set the hmcas and chunks pointers.
*/
ep->prsctp_enable = net->sctp.prsctp_enable;
ep->reconf_enable = net->sctp.reconf_enable;
ep->ecn_enable = net->sctp.ecn_enable;
/* Remember who we are attached to. */
ep->base.sk = sk;
ep->base.net = sock_net(sk);
sock_hold(ep->base.sk);
return ep;
nomem_shkey:
sctp_auth_free(ep);
nomem:
kfree(ep->digest);
return NULL;
}
/* Create a sctp_endpoint with all that boring stuff initialized.
* Returns NULL if there isn't enough memory.
*/
struct sctp_endpoint *sctp_endpoint_new(struct sock *sk, gfp_t gfp)
{
struct sctp_endpoint *ep;
/* Build a local endpoint. */
ep = kzalloc(sizeof(*ep), gfp);
if (!ep)
goto fail;
if (!sctp_endpoint_init(ep, sk, gfp))
goto fail_init;
SCTP_DBG_OBJCNT_INC(ep);
return ep;
fail_init:
kfree(ep);
fail:
return NULL;
}
/* Add an association to an endpoint. */
void sctp_endpoint_add_asoc(struct sctp_endpoint *ep,
struct sctp_association *asoc)
{
struct sock *sk = ep->base.sk;
/* If this is a temporary association, don't bother
* since we'll be removing it shortly and don't
* want anyone to find it anyway.
*/
if (asoc->temp)
return;
/* Now just add it to our list of asocs */
list_add_tail(&asoc->asocs, &ep->asocs);
/* Increment the backlog value for a TCP-style listening socket. */
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
sk_acceptq_added(sk);
}
/* Free the endpoint structure. Delay cleanup until
* all users have released their reference count on this structure.
*/
void sctp_endpoint_free(struct sctp_endpoint *ep)
{
ep->base.dead = true;
inet_sk_set_state(ep->base.sk, SCTP_SS_CLOSED);
/* Unlink this endpoint, so we can't find it again! */
sctp_unhash_endpoint(ep);
sctp_endpoint_put(ep);
}
/* Final destructor for endpoint. */
static void sctp_endpoint_destroy_rcu(struct rcu_head *head)
{
struct sctp_endpoint *ep = container_of(head, struct sctp_endpoint, rcu);
struct sock *sk = ep->base.sk;
sctp_sk(sk)->ep = NULL;
sock_put(sk);
kfree(ep);
SCTP_DBG_OBJCNT_DEC(ep);
}
static void sctp_endpoint_destroy(struct sctp_endpoint *ep)
{
struct sock *sk;
if (unlikely(!ep->base.dead)) {
WARN(1, "Attempt to destroy undead endpoint %p!\n", ep);
return;
}
/* Free the digest buffer */
kfree(ep->digest);
/* SCTP-AUTH: Free up AUTH releated data such as shared keys
* chunks and hmacs arrays that were allocated
*/
sctp_auth_destroy_keys(&ep->endpoint_shared_keys);
sctp_auth_free(ep);
/* Cleanup. */
sctp_inq_free(&ep->base.inqueue);
sctp_bind_addr_free(&ep->base.bind_addr);
memset(ep->secret_key, 0, sizeof(ep->secret_key));
sk = ep->base.sk;
/* Remove and free the port */
if (sctp_sk(sk)->bind_hash)
sctp_put_port(sk);
call_rcu(&ep->rcu, sctp_endpoint_destroy_rcu);
}
/* Hold a reference to an endpoint. */
int sctp_endpoint_hold(struct sctp_endpoint *ep)
{
return refcount_inc_not_zero(&ep->base.refcnt);
}
/* Release a reference to an endpoint and clean up if there are
* no more references.
*/
void sctp_endpoint_put(struct sctp_endpoint *ep)
{
if (refcount_dec_and_test(&ep->base.refcnt))
sctp_endpoint_destroy(ep);
}
/* Is this the endpoint we are looking for? */
struct sctp_endpoint *sctp_endpoint_is_match(struct sctp_endpoint *ep,
struct net *net,
const union sctp_addr *laddr,
int dif, int sdif)
{
int bound_dev_if = READ_ONCE(ep->base.sk->sk_bound_dev_if);
struct sctp_endpoint *retval = NULL;
if (net_eq(ep->base.net, net) &&
sctp_sk_bound_dev_eq(net, bound_dev_if, dif, sdif) &&
(htons(ep->base.bind_addr.port) == laddr->v4.sin_port)) {
if (sctp_bind_addr_match(&ep->base.bind_addr, laddr,
sctp_sk(ep->base.sk)))
retval = ep;
}
return retval;
}
/* Find the association that goes with this chunk.
* We lookup the transport from hashtable at first, then get association
* through t->assoc.
*/
struct sctp_association *sctp_endpoint_lookup_assoc(
const struct sctp_endpoint *ep,
const union sctp_addr *paddr,
struct sctp_transport **transport)
{
struct sctp_association *asoc = NULL;
struct sctp_transport *t;
*transport = NULL;
/* If the local port is not set, there can't be any associations
* on this endpoint.
*/
if (!ep->base.bind_addr.port)
return NULL;
rcu_read_lock();
t = sctp_epaddr_lookup_transport(ep, paddr);
if (!t)
goto out;
*transport = t;
asoc = t->asoc;
out:
rcu_read_unlock();
return asoc;
}
/* Look for any peeled off association from the endpoint that matches the
* given peer address.
*/
bool sctp_endpoint_is_peeled_off(struct sctp_endpoint *ep,
const union sctp_addr *paddr)
{
int bound_dev_if = READ_ONCE(ep->base.sk->sk_bound_dev_if);
struct sctp_sockaddr_entry *addr;
struct net *net = ep->base.net;
struct sctp_bind_addr *bp;
bp = &ep->base.bind_addr;
/* This function is called with the socket lock held,
* so the address_list can not change.
*/
list_for_each_entry(addr, &bp->address_list, list) {
if (sctp_has_association(net, &addr->a, paddr,
bound_dev_if, bound_dev_if))
return true;
}
return false;
}
/* Do delayed input processing. This is scheduled by sctp_rcv().
* This may be called on BH or task time.
*/
static void sctp_endpoint_bh_rcv(struct work_struct *work)
{
struct sctp_endpoint *ep =
container_of(work, struct sctp_endpoint,
base.inqueue.immediate);
struct sctp_association *asoc;
struct sock *sk;
struct net *net;
struct sctp_transport *transport;
struct sctp_chunk *chunk;
struct sctp_inq *inqueue;
union sctp_subtype subtype;
enum sctp_state state;
int error = 0;
int first_time = 1; /* is this the first time through the loop */
if (ep->base.dead)
return;
asoc = NULL;
inqueue = &ep->base.inqueue;
sk = ep->base.sk;
net = sock_net(sk);
while (NULL != (chunk = sctp_inq_pop(inqueue))) {
subtype = SCTP_ST_CHUNK(chunk->chunk_hdr->type);
/* If the first chunk in the packet is AUTH, do special
* processing specified in Section 6.3 of SCTP-AUTH spec
*/
if (first_time && (subtype.chunk == SCTP_CID_AUTH)) {
struct sctp_chunkhdr *next_hdr;
next_hdr = sctp_inq_peek(inqueue);
if (!next_hdr)
goto normal;
/* If the next chunk is COOKIE-ECHO, skip the AUTH
* chunk while saving a pointer to it so we can do
* Authentication later (during cookie-echo
* processing).
*/
if (next_hdr->type == SCTP_CID_COOKIE_ECHO) {
chunk->auth_chunk = skb_clone(chunk->skb,
GFP_ATOMIC);
chunk->auth = 1;
continue;
}
}
normal:
/* We might have grown an association since last we
* looked, so try again.
*
* This happens when we've just processed our
* COOKIE-ECHO chunk.
*/
if (NULL == chunk->asoc) {
asoc = sctp_endpoint_lookup_assoc(ep,
sctp_source(chunk),
&transport);
chunk->asoc = asoc;
chunk->transport = transport;
}
state = asoc ? asoc->state : SCTP_STATE_CLOSED;
if (sctp_auth_recv_cid(subtype.chunk, asoc) && !chunk->auth)
continue;
/* Remember where the last DATA chunk came from so we
* know where to send the SACK.
*/
if (asoc && sctp_chunk_is_data(chunk))
asoc->peer.last_data_from = chunk->transport;
else {
SCTP_INC_STATS(ep->base.net, SCTP_MIB_INCTRLCHUNKS);
if (asoc)
asoc->stats.ictrlchunks++;
}
if (chunk->transport)
chunk->transport->last_time_heard = ktime_get();
error = sctp_do_sm(net, SCTP_EVENT_T_CHUNK, subtype, state,
ep, asoc, chunk, GFP_ATOMIC);
if (error && chunk)
chunk->pdiscard = 1;
/* Check to see if the endpoint is freed in response to
* the incoming chunk. If so, get out of the while loop.
*/
if (!sctp_sk(sk)->ep)
break;
if (first_time)
first_time = 0;
}
}
| linux-master | net/sctp/endpointola.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 Nokia, Inc.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This abstraction carries sctp events to the ULP (sockets).
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Jon Grimm <[email protected]>
* La Monte H.P. Yarroll <[email protected]>
* Sridhar Samudrala <[email protected]>
*/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/busy_poll.h>
#include <net/sctp/structs.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
/* Forward declarations for internal helpers. */
static struct sctp_ulpevent *sctp_ulpq_reasm(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *);
static struct sctp_ulpevent *sctp_ulpq_order(struct sctp_ulpq *,
struct sctp_ulpevent *);
static void sctp_ulpq_reasm_drain(struct sctp_ulpq *ulpq);
/* 1st Level Abstractions */
/* Initialize a ULP queue from a block of memory. */
void sctp_ulpq_init(struct sctp_ulpq *ulpq, struct sctp_association *asoc)
{
memset(ulpq, 0, sizeof(struct sctp_ulpq));
ulpq->asoc = asoc;
skb_queue_head_init(&ulpq->reasm);
skb_queue_head_init(&ulpq->reasm_uo);
skb_queue_head_init(&ulpq->lobby);
ulpq->pd_mode = 0;
}
/* Flush the reassembly and ordering queues. */
void sctp_ulpq_flush(struct sctp_ulpq *ulpq)
{
struct sk_buff *skb;
struct sctp_ulpevent *event;
while ((skb = __skb_dequeue(&ulpq->lobby)) != NULL) {
event = sctp_skb2event(skb);
sctp_ulpevent_free(event);
}
while ((skb = __skb_dequeue(&ulpq->reasm)) != NULL) {
event = sctp_skb2event(skb);
sctp_ulpevent_free(event);
}
while ((skb = __skb_dequeue(&ulpq->reasm_uo)) != NULL) {
event = sctp_skb2event(skb);
sctp_ulpevent_free(event);
}
}
/* Dispose of a ulpqueue. */
void sctp_ulpq_free(struct sctp_ulpq *ulpq)
{
sctp_ulpq_flush(ulpq);
}
/* Process an incoming DATA chunk. */
int sctp_ulpq_tail_data(struct sctp_ulpq *ulpq, struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sk_buff_head temp;
struct sctp_ulpevent *event;
int event_eor = 0;
/* Create an event from the incoming chunk. */
event = sctp_ulpevent_make_rcvmsg(chunk->asoc, chunk, gfp);
if (!event)
return -ENOMEM;
event->ssn = ntohs(chunk->subh.data_hdr->ssn);
event->ppid = chunk->subh.data_hdr->ppid;
/* Do reassembly if needed. */
event = sctp_ulpq_reasm(ulpq, event);
/* Do ordering if needed. */
if (event) {
/* Create a temporary list to collect chunks on. */
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
if (event->msg_flags & MSG_EOR)
event = sctp_ulpq_order(ulpq, event);
}
/* Send event to the ULP. 'event' is the sctp_ulpevent for
* very first SKB on the 'temp' list.
*/
if (event) {
event_eor = (event->msg_flags & MSG_EOR) ? 1 : 0;
sctp_ulpq_tail_event(ulpq, &temp);
}
return event_eor;
}
/* Add a new event for propagation to the ULP. */
/* Clear the partial delivery mode for this socket. Note: This
* assumes that no association is currently in partial delivery mode.
*/
int sctp_clear_pd(struct sock *sk, struct sctp_association *asoc)
{
struct sctp_sock *sp = sctp_sk(sk);
if (atomic_dec_and_test(&sp->pd_mode)) {
/* This means there are no other associations in PD, so
* we can go ahead and clear out the lobby in one shot
*/
if (!skb_queue_empty(&sp->pd_lobby)) {
skb_queue_splice_tail_init(&sp->pd_lobby,
&sk->sk_receive_queue);
return 1;
}
} else {
/* There are other associations in PD, so we only need to
* pull stuff out of the lobby that belongs to the
* associations that is exiting PD (all of its notifications
* are posted here).
*/
if (!skb_queue_empty(&sp->pd_lobby) && asoc) {
struct sk_buff *skb, *tmp;
struct sctp_ulpevent *event;
sctp_skb_for_each(skb, &sp->pd_lobby, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == asoc) {
__skb_unlink(skb, &sp->pd_lobby);
__skb_queue_tail(&sk->sk_receive_queue,
skb);
}
}
}
}
return 0;
}
/* Set the pd_mode on the socket and ulpq */
static void sctp_ulpq_set_pd(struct sctp_ulpq *ulpq)
{
struct sctp_sock *sp = sctp_sk(ulpq->asoc->base.sk);
atomic_inc(&sp->pd_mode);
ulpq->pd_mode = 1;
}
/* Clear the pd_mode and restart any pending messages waiting for delivery. */
static int sctp_ulpq_clear_pd(struct sctp_ulpq *ulpq)
{
ulpq->pd_mode = 0;
sctp_ulpq_reasm_drain(ulpq);
return sctp_clear_pd(ulpq->asoc->base.sk, ulpq->asoc);
}
int sctp_ulpq_tail_event(struct sctp_ulpq *ulpq, struct sk_buff_head *skb_list)
{
struct sock *sk = ulpq->asoc->base.sk;
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_ulpevent *event;
struct sk_buff_head *queue;
struct sk_buff *skb;
int clear_pd = 0;
skb = __skb_peek(skb_list);
event = sctp_skb2event(skb);
/* If the socket is just going to throw this away, do not
* even try to deliver it.
*/
if (sk->sk_shutdown & RCV_SHUTDOWN &&
(sk->sk_shutdown & SEND_SHUTDOWN ||
!sctp_ulpevent_is_notification(event)))
goto out_free;
if (!sctp_ulpevent_is_notification(event)) {
sk_mark_napi_id(sk, skb);
sk_incoming_cpu_update(sk);
}
/* Check if the user wishes to receive this event. */
if (!sctp_ulpevent_is_enabled(event, ulpq->asoc->subscribe))
goto out_free;
/* If we are in partial delivery mode, post to the lobby until
* partial delivery is cleared, unless, of course _this_ is
* the association the cause of the partial delivery.
*/
if (atomic_read(&sp->pd_mode) == 0) {
queue = &sk->sk_receive_queue;
} else {
if (ulpq->pd_mode) {
/* If the association is in partial delivery, we
* need to finish delivering the partially processed
* packet before passing any other data. This is
* because we don't truly support stream interleaving.
*/
if ((event->msg_flags & MSG_NOTIFICATION) ||
(SCTP_DATA_NOT_FRAG ==
(event->msg_flags & SCTP_DATA_FRAG_MASK)))
queue = &sp->pd_lobby;
else {
clear_pd = event->msg_flags & MSG_EOR;
queue = &sk->sk_receive_queue;
}
} else {
/*
* If fragment interleave is enabled, we
* can queue this to the receive queue instead
* of the lobby.
*/
if (sp->frag_interleave)
queue = &sk->sk_receive_queue;
else
queue = &sp->pd_lobby;
}
}
skb_queue_splice_tail_init(skb_list, queue);
/* Did we just complete partial delivery and need to get
* rolling again? Move pending data to the receive
* queue.
*/
if (clear_pd)
sctp_ulpq_clear_pd(ulpq);
if (queue == &sk->sk_receive_queue && !sp->data_ready_signalled) {
if (!sock_owned_by_user(sk))
sp->data_ready_signalled = 1;
sk->sk_data_ready(sk);
}
return 1;
out_free:
sctp_queue_purge_ulpevents(skb_list);
return 0;
}
/* 2nd Level Abstractions */
/* Helper function to store chunks that need to be reassembled. */
static void sctp_ulpq_store_reasm(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sk_buff *pos;
struct sctp_ulpevent *cevent;
__u32 tsn, ctsn;
tsn = event->tsn;
/* See if it belongs at the end. */
pos = skb_peek_tail(&ulpq->reasm);
if (!pos) {
__skb_queue_tail(&ulpq->reasm, sctp_event2skb(event));
return;
}
/* Short circuit just dropping it at the end. */
cevent = sctp_skb2event(pos);
ctsn = cevent->tsn;
if (TSN_lt(ctsn, tsn)) {
__skb_queue_tail(&ulpq->reasm, sctp_event2skb(event));
return;
}
/* Find the right place in this list. We store them by TSN. */
skb_queue_walk(&ulpq->reasm, pos) {
cevent = sctp_skb2event(pos);
ctsn = cevent->tsn;
if (TSN_lt(tsn, ctsn))
break;
}
/* Insert before pos. */
__skb_queue_before(&ulpq->reasm, pos, sctp_event2skb(event));
}
/* Helper function to return an event corresponding to the reassembled
* datagram.
* This routine creates a re-assembled skb given the first and last skb's
* as stored in the reassembly queue. The skb's may be non-linear if the sctp
* payload was fragmented on the way and ip had to reassemble them.
* We add the rest of skb's to the first skb's fraglist.
*/
struct sctp_ulpevent *sctp_make_reassembled_event(struct net *net,
struct sk_buff_head *queue,
struct sk_buff *f_frag,
struct sk_buff *l_frag)
{
struct sk_buff *pos;
struct sk_buff *new = NULL;
struct sctp_ulpevent *event;
struct sk_buff *pnext, *last;
struct sk_buff *list = skb_shinfo(f_frag)->frag_list;
/* Store the pointer to the 2nd skb */
if (f_frag == l_frag)
pos = NULL;
else
pos = f_frag->next;
/* Get the last skb in the f_frag's frag_list if present. */
for (last = list; list; last = list, list = list->next)
;
/* Add the list of remaining fragments to the first fragments
* frag_list.
*/
if (last)
last->next = pos;
else {
if (skb_cloned(f_frag)) {
/* This is a cloned skb, we can't just modify
* the frag_list. We need a new skb to do that.
* Instead of calling skb_unshare(), we'll do it
* ourselves since we need to delay the free.
*/
new = skb_copy(f_frag, GFP_ATOMIC);
if (!new)
return NULL; /* try again later */
sctp_skb_set_owner_r(new, f_frag->sk);
skb_shinfo(new)->frag_list = pos;
} else
skb_shinfo(f_frag)->frag_list = pos;
}
/* Remove the first fragment from the reassembly queue. */
__skb_unlink(f_frag, queue);
/* if we did unshare, then free the old skb and re-assign */
if (new) {
kfree_skb(f_frag);
f_frag = new;
}
while (pos) {
pnext = pos->next;
/* Update the len and data_len fields of the first fragment. */
f_frag->len += pos->len;
f_frag->data_len += pos->len;
/* Remove the fragment from the reassembly queue. */
__skb_unlink(pos, queue);
/* Break if we have reached the last fragment. */
if (pos == l_frag)
break;
pos->next = pnext;
pos = pnext;
}
event = sctp_skb2event(f_frag);
SCTP_INC_STATS(net, SCTP_MIB_REASMUSRMSGS);
return event;
}
/* Helper function to check if an incoming chunk has filled up the last
* missing fragment in a SCTP datagram and return the corresponding event.
*/
static struct sctp_ulpevent *sctp_ulpq_retrieve_reassembled(struct sctp_ulpq *ulpq)
{
struct sk_buff *pos;
struct sctp_ulpevent *cevent;
struct sk_buff *first_frag = NULL;
__u32 ctsn, next_tsn;
struct sctp_ulpevent *retval = NULL;
struct sk_buff *pd_first = NULL;
struct sk_buff *pd_last = NULL;
size_t pd_len = 0;
struct sctp_association *asoc;
u32 pd_point;
/* Initialized to 0 just to avoid compiler warning message. Will
* never be used with this value. It is referenced only after it
* is set when we find the first fragment of a message.
*/
next_tsn = 0;
/* The chunks are held in the reasm queue sorted by TSN.
* Walk through the queue sequentially and look for a sequence of
* fragmented chunks that complete a datagram.
* 'first_frag' and next_tsn are reset when we find a chunk which
* is the first fragment of a datagram. Once these 2 fields are set
* we expect to find the remaining middle fragments and the last
* fragment in order. If not, first_frag is reset to NULL and we
* start the next pass when we find another first fragment.
*
* There is a potential to do partial delivery if user sets
* SCTP_PARTIAL_DELIVERY_POINT option. Lets count some things here
* to see if can do PD.
*/
skb_queue_walk(&ulpq->reasm, pos) {
cevent = sctp_skb2event(pos);
ctsn = cevent->tsn;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
/* If this "FIRST_FRAG" is the first
* element in the queue, then count it towards
* possible PD.
*/
if (skb_queue_is_first(&ulpq->reasm, pos)) {
pd_first = pos;
pd_last = pos;
pd_len = pos->len;
} else {
pd_first = NULL;
pd_last = NULL;
pd_len = 0;
}
first_frag = pos;
next_tsn = ctsn + 1;
break;
case SCTP_DATA_MIDDLE_FRAG:
if ((first_frag) && (ctsn == next_tsn)) {
next_tsn++;
if (pd_first) {
pd_last = pos;
pd_len += pos->len;
}
} else
first_frag = NULL;
break;
case SCTP_DATA_LAST_FRAG:
if (first_frag && (ctsn == next_tsn))
goto found;
else
first_frag = NULL;
break;
}
}
asoc = ulpq->asoc;
if (pd_first) {
/* Make sure we can enter partial deliver.
* We can trigger partial delivery only if framgent
* interleave is set, or the socket is not already
* in partial delivery.
*/
if (!sctp_sk(asoc->base.sk)->frag_interleave &&
atomic_read(&sctp_sk(asoc->base.sk)->pd_mode))
goto done;
cevent = sctp_skb2event(pd_first);
pd_point = sctp_sk(asoc->base.sk)->pd_point;
if (pd_point && pd_point <= pd_len) {
retval = sctp_make_reassembled_event(asoc->base.net,
&ulpq->reasm,
pd_first, pd_last);
if (retval)
sctp_ulpq_set_pd(ulpq);
}
}
done:
return retval;
found:
retval = sctp_make_reassembled_event(ulpq->asoc->base.net,
&ulpq->reasm, first_frag, pos);
if (retval)
retval->msg_flags |= MSG_EOR;
goto done;
}
/* Retrieve the next set of fragments of a partial message. */
static struct sctp_ulpevent *sctp_ulpq_retrieve_partial(struct sctp_ulpq *ulpq)
{
struct sk_buff *pos, *last_frag, *first_frag;
struct sctp_ulpevent *cevent;
__u32 ctsn, next_tsn;
int is_last;
struct sctp_ulpevent *retval;
/* The chunks are held in the reasm queue sorted by TSN.
* Walk through the queue sequentially and look for the first
* sequence of fragmented chunks.
*/
if (skb_queue_empty(&ulpq->reasm))
return NULL;
last_frag = first_frag = NULL;
retval = NULL;
next_tsn = 0;
is_last = 0;
skb_queue_walk(&ulpq->reasm, pos) {
cevent = sctp_skb2event(pos);
ctsn = cevent->tsn;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
if (!first_frag)
return NULL;
goto done;
case SCTP_DATA_MIDDLE_FRAG:
if (!first_frag) {
first_frag = pos;
next_tsn = ctsn + 1;
last_frag = pos;
} else if (next_tsn == ctsn) {
next_tsn++;
last_frag = pos;
} else
goto done;
break;
case SCTP_DATA_LAST_FRAG:
if (!first_frag)
first_frag = pos;
else if (ctsn != next_tsn)
goto done;
last_frag = pos;
is_last = 1;
goto done;
default:
return NULL;
}
}
/* We have the reassembled event. There is no need to look
* further.
*/
done:
retval = sctp_make_reassembled_event(ulpq->asoc->base.net, &ulpq->reasm,
first_frag, last_frag);
if (retval && is_last)
retval->msg_flags |= MSG_EOR;
return retval;
}
/* Helper function to reassemble chunks. Hold chunks on the reasm queue that
* need reassembling.
*/
static struct sctp_ulpevent *sctp_ulpq_reasm(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sctp_ulpevent *retval = NULL;
/* Check if this is part of a fragmented message. */
if (SCTP_DATA_NOT_FRAG == (event->msg_flags & SCTP_DATA_FRAG_MASK)) {
event->msg_flags |= MSG_EOR;
return event;
}
sctp_ulpq_store_reasm(ulpq, event);
if (!ulpq->pd_mode)
retval = sctp_ulpq_retrieve_reassembled(ulpq);
else {
__u32 ctsn, ctsnap;
/* Do not even bother unless this is the next tsn to
* be delivered.
*/
ctsn = event->tsn;
ctsnap = sctp_tsnmap_get_ctsn(&ulpq->asoc->peer.tsn_map);
if (TSN_lte(ctsn, ctsnap))
retval = sctp_ulpq_retrieve_partial(ulpq);
}
return retval;
}
/* Retrieve the first part (sequential fragments) for partial delivery. */
static struct sctp_ulpevent *sctp_ulpq_retrieve_first(struct sctp_ulpq *ulpq)
{
struct sk_buff *pos, *last_frag, *first_frag;
struct sctp_ulpevent *cevent;
__u32 ctsn, next_tsn;
struct sctp_ulpevent *retval;
/* The chunks are held in the reasm queue sorted by TSN.
* Walk through the queue sequentially and look for a sequence of
* fragmented chunks that start a datagram.
*/
if (skb_queue_empty(&ulpq->reasm))
return NULL;
last_frag = first_frag = NULL;
retval = NULL;
next_tsn = 0;
skb_queue_walk(&ulpq->reasm, pos) {
cevent = sctp_skb2event(pos);
ctsn = cevent->tsn;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
if (!first_frag) {
first_frag = pos;
next_tsn = ctsn + 1;
last_frag = pos;
} else
goto done;
break;
case SCTP_DATA_MIDDLE_FRAG:
if (!first_frag)
return NULL;
if (ctsn == next_tsn) {
next_tsn++;
last_frag = pos;
} else
goto done;
break;
case SCTP_DATA_LAST_FRAG:
if (!first_frag)
return NULL;
else
goto done;
break;
default:
return NULL;
}
}
/* We have the reassembled event. There is no need to look
* further.
*/
done:
retval = sctp_make_reassembled_event(ulpq->asoc->base.net, &ulpq->reasm,
first_frag, last_frag);
return retval;
}
/*
* Flush out stale fragments from the reassembly queue when processing
* a Forward TSN.
*
* RFC 3758, Section 3.6
*
* After receiving and processing a FORWARD TSN, the data receiver MUST
* take cautions in updating its re-assembly queue. The receiver MUST
* remove any partially reassembled message, which is still missing one
* or more TSNs earlier than or equal to the new cumulative TSN point.
* In the event that the receiver has invoked the partial delivery API,
* a notification SHOULD also be generated to inform the upper layer API
* that the message being partially delivered will NOT be completed.
*/
void sctp_ulpq_reasm_flushtsn(struct sctp_ulpq *ulpq, __u32 fwd_tsn)
{
struct sk_buff *pos, *tmp;
struct sctp_ulpevent *event;
__u32 tsn;
if (skb_queue_empty(&ulpq->reasm))
return;
skb_queue_walk_safe(&ulpq->reasm, pos, tmp) {
event = sctp_skb2event(pos);
tsn = event->tsn;
/* Since the entire message must be abandoned by the
* sender (item A3 in Section 3.5, RFC 3758), we can
* free all fragments on the list that are less then
* or equal to ctsn_point
*/
if (TSN_lte(tsn, fwd_tsn)) {
__skb_unlink(pos, &ulpq->reasm);
sctp_ulpevent_free(event);
} else
break;
}
}
/*
* Drain the reassembly queue. If we just cleared parted delivery, it
* is possible that the reassembly queue will contain already reassembled
* messages. Retrieve any such messages and give them to the user.
*/
static void sctp_ulpq_reasm_drain(struct sctp_ulpq *ulpq)
{
struct sctp_ulpevent *event = NULL;
if (skb_queue_empty(&ulpq->reasm))
return;
while ((event = sctp_ulpq_retrieve_reassembled(ulpq)) != NULL) {
struct sk_buff_head temp;
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
/* Do ordering if needed. */
if (event->msg_flags & MSG_EOR)
event = sctp_ulpq_order(ulpq, event);
/* Send event to the ULP. 'event' is the
* sctp_ulpevent for very first SKB on the temp' list.
*/
if (event)
sctp_ulpq_tail_event(ulpq, &temp);
}
}
/* Helper function to gather skbs that have possibly become
* ordered by an incoming chunk.
*/
static void sctp_ulpq_retrieve_ordered(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sk_buff_head *event_list;
struct sk_buff *pos, *tmp;
struct sctp_ulpevent *cevent;
struct sctp_stream *stream;
__u16 sid, csid, cssn;
sid = event->stream;
stream = &ulpq->asoc->stream;
event_list = (struct sk_buff_head *) sctp_event2skb(event)->prev;
/* We are holding the chunks by stream, by SSN. */
sctp_skb_for_each(pos, &ulpq->lobby, tmp) {
cevent = (struct sctp_ulpevent *) pos->cb;
csid = cevent->stream;
cssn = cevent->ssn;
/* Have we gone too far? */
if (csid > sid)
break;
/* Have we not gone far enough? */
if (csid < sid)
continue;
if (cssn != sctp_ssn_peek(stream, in, sid))
break;
/* Found it, so mark in the stream. */
sctp_ssn_next(stream, in, sid);
__skb_unlink(pos, &ulpq->lobby);
/* Attach all gathered skbs to the event. */
__skb_queue_tail(event_list, pos);
}
}
/* Helper function to store chunks needing ordering. */
static void sctp_ulpq_store_ordered(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sk_buff *pos;
struct sctp_ulpevent *cevent;
__u16 sid, csid;
__u16 ssn, cssn;
pos = skb_peek_tail(&ulpq->lobby);
if (!pos) {
__skb_queue_tail(&ulpq->lobby, sctp_event2skb(event));
return;
}
sid = event->stream;
ssn = event->ssn;
cevent = (struct sctp_ulpevent *) pos->cb;
csid = cevent->stream;
cssn = cevent->ssn;
if (sid > csid) {
__skb_queue_tail(&ulpq->lobby, sctp_event2skb(event));
return;
}
if ((sid == csid) && SSN_lt(cssn, ssn)) {
__skb_queue_tail(&ulpq->lobby, sctp_event2skb(event));
return;
}
/* Find the right place in this list. We store them by
* stream ID and then by SSN.
*/
skb_queue_walk(&ulpq->lobby, pos) {
cevent = (struct sctp_ulpevent *) pos->cb;
csid = cevent->stream;
cssn = cevent->ssn;
if (csid > sid)
break;
if (csid == sid && SSN_lt(ssn, cssn))
break;
}
/* Insert before pos. */
__skb_queue_before(&ulpq->lobby, pos, sctp_event2skb(event));
}
static struct sctp_ulpevent *sctp_ulpq_order(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
__u16 sid, ssn;
struct sctp_stream *stream;
/* Check if this message needs ordering. */
if (event->msg_flags & SCTP_DATA_UNORDERED)
return event;
/* Note: The stream ID must be verified before this routine. */
sid = event->stream;
ssn = event->ssn;
stream = &ulpq->asoc->stream;
/* Is this the expected SSN for this stream ID? */
if (ssn != sctp_ssn_peek(stream, in, sid)) {
/* We've received something out of order, so find where it
* needs to be placed. We order by stream and then by SSN.
*/
sctp_ulpq_store_ordered(ulpq, event);
return NULL;
}
/* Mark that the next chunk has been found. */
sctp_ssn_next(stream, in, sid);
/* Go find any other chunks that were waiting for
* ordering.
*/
sctp_ulpq_retrieve_ordered(ulpq, event);
return event;
}
/* Helper function to gather skbs that have possibly become
* ordered by forward tsn skipping their dependencies.
*/
static void sctp_ulpq_reap_ordered(struct sctp_ulpq *ulpq, __u16 sid)
{
struct sk_buff *pos, *tmp;
struct sctp_ulpevent *cevent;
struct sctp_ulpevent *event;
struct sctp_stream *stream;
struct sk_buff_head temp;
struct sk_buff_head *lobby = &ulpq->lobby;
__u16 csid, cssn;
stream = &ulpq->asoc->stream;
/* We are holding the chunks by stream, by SSN. */
skb_queue_head_init(&temp);
event = NULL;
sctp_skb_for_each(pos, lobby, tmp) {
cevent = (struct sctp_ulpevent *) pos->cb;
csid = cevent->stream;
cssn = cevent->ssn;
/* Have we gone too far? */
if (csid > sid)
break;
/* Have we not gone far enough? */
if (csid < sid)
continue;
/* see if this ssn has been marked by skipping */
if (!SSN_lt(cssn, sctp_ssn_peek(stream, in, csid)))
break;
__skb_unlink(pos, lobby);
if (!event)
/* Create a temporary list to collect chunks on. */
event = sctp_skb2event(pos);
/* Attach all gathered skbs to the event. */
__skb_queue_tail(&temp, pos);
}
/* If we didn't reap any data, see if the next expected SSN
* is next on the queue and if so, use that.
*/
if (event == NULL && pos != (struct sk_buff *)lobby) {
cevent = (struct sctp_ulpevent *) pos->cb;
csid = cevent->stream;
cssn = cevent->ssn;
if (csid == sid && cssn == sctp_ssn_peek(stream, in, csid)) {
sctp_ssn_next(stream, in, csid);
__skb_unlink(pos, lobby);
__skb_queue_tail(&temp, pos);
event = sctp_skb2event(pos);
}
}
/* Send event to the ULP. 'event' is the sctp_ulpevent for
* very first SKB on the 'temp' list.
*/
if (event) {
/* see if we have more ordered that we can deliver */
sctp_ulpq_retrieve_ordered(ulpq, event);
sctp_ulpq_tail_event(ulpq, &temp);
}
}
/* Skip over an SSN. This is used during the processing of
* Forwared TSN chunk to skip over the abandoned ordered data
*/
void sctp_ulpq_skip(struct sctp_ulpq *ulpq, __u16 sid, __u16 ssn)
{
struct sctp_stream *stream;
/* Note: The stream ID must be verified before this routine. */
stream = &ulpq->asoc->stream;
/* Is this an old SSN? If so ignore. */
if (SSN_lt(ssn, sctp_ssn_peek(stream, in, sid)))
return;
/* Mark that we are no longer expecting this SSN or lower. */
sctp_ssn_skip(stream, in, sid, ssn);
/* Go find any other chunks that were waiting for
* ordering and deliver them if needed.
*/
sctp_ulpq_reap_ordered(ulpq, sid);
}
__u16 sctp_ulpq_renege_list(struct sctp_ulpq *ulpq, struct sk_buff_head *list,
__u16 needed)
{
__u16 freed = 0;
__u32 tsn, last_tsn;
struct sk_buff *skb, *flist, *last;
struct sctp_ulpevent *event;
struct sctp_tsnmap *tsnmap;
tsnmap = &ulpq->asoc->peer.tsn_map;
while ((skb = skb_peek_tail(list)) != NULL) {
event = sctp_skb2event(skb);
tsn = event->tsn;
/* Don't renege below the Cumulative TSN ACK Point. */
if (TSN_lte(tsn, sctp_tsnmap_get_ctsn(tsnmap)))
break;
/* Events in ordering queue may have multiple fragments
* corresponding to additional TSNs. Sum the total
* freed space; find the last TSN.
*/
freed += skb_headlen(skb);
flist = skb_shinfo(skb)->frag_list;
for (last = flist; flist; flist = flist->next) {
last = flist;
freed += skb_headlen(last);
}
if (last)
last_tsn = sctp_skb2event(last)->tsn;
else
last_tsn = tsn;
/* Unlink the event, then renege all applicable TSNs. */
__skb_unlink(skb, list);
sctp_ulpevent_free(event);
while (TSN_lte(tsn, last_tsn)) {
sctp_tsnmap_renege(tsnmap, tsn);
tsn++;
}
if (freed >= needed)
return freed;
}
return freed;
}
/* Renege 'needed' bytes from the ordering queue. */
static __u16 sctp_ulpq_renege_order(struct sctp_ulpq *ulpq, __u16 needed)
{
return sctp_ulpq_renege_list(ulpq, &ulpq->lobby, needed);
}
/* Renege 'needed' bytes from the reassembly queue. */
static __u16 sctp_ulpq_renege_frags(struct sctp_ulpq *ulpq, __u16 needed)
{
return sctp_ulpq_renege_list(ulpq, &ulpq->reasm, needed);
}
/* Partial deliver the first message as there is pressure on rwnd. */
void sctp_ulpq_partial_delivery(struct sctp_ulpq *ulpq,
gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sctp_association *asoc;
struct sctp_sock *sp;
__u32 ctsn;
struct sk_buff *skb;
asoc = ulpq->asoc;
sp = sctp_sk(asoc->base.sk);
/* If the association is already in Partial Delivery mode
* we have nothing to do.
*/
if (ulpq->pd_mode)
return;
/* Data must be at or below the Cumulative TSN ACK Point to
* start partial delivery.
*/
skb = skb_peek(&asoc->ulpq.reasm);
if (skb != NULL) {
ctsn = sctp_skb2event(skb)->tsn;
if (!TSN_lte(ctsn, sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map)))
return;
}
/* If the user enabled fragment interleave socket option,
* multiple associations can enter partial delivery.
* Otherwise, we can only enter partial delivery if the
* socket is not in partial deliver mode.
*/
if (sp->frag_interleave || atomic_read(&sp->pd_mode) == 0) {
/* Is partial delivery possible? */
event = sctp_ulpq_retrieve_first(ulpq);
/* Send event to the ULP. */
if (event) {
struct sk_buff_head temp;
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
sctp_ulpq_tail_event(ulpq, &temp);
sctp_ulpq_set_pd(ulpq);
return;
}
}
}
/* Renege some packets to make room for an incoming chunk. */
void sctp_ulpq_renege(struct sctp_ulpq *ulpq, struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sctp_association *asoc = ulpq->asoc;
__u32 freed = 0;
__u16 needed;
needed = ntohs(chunk->chunk_hdr->length) -
sizeof(struct sctp_data_chunk);
if (skb_queue_empty(&asoc->base.sk->sk_receive_queue)) {
freed = sctp_ulpq_renege_order(ulpq, needed);
if (freed < needed)
freed += sctp_ulpq_renege_frags(ulpq, needed - freed);
}
/* If able to free enough room, accept this chunk. */
if (sk_rmem_schedule(asoc->base.sk, chunk->skb, needed) &&
freed >= needed) {
int retval = sctp_ulpq_tail_data(ulpq, chunk, gfp);
/*
* Enter partial delivery if chunk has not been
* delivered; otherwise, drain the reassembly queue.
*/
if (retval <= 0)
sctp_ulpq_partial_delivery(ulpq, gfp);
else if (retval == 1)
sctp_ulpq_reasm_drain(ulpq);
}
}
/* Notify the application if an association is aborted and in
* partial delivery mode. Send up any pending received messages.
*/
void sctp_ulpq_abort_pd(struct sctp_ulpq *ulpq, gfp_t gfp)
{
struct sctp_ulpevent *ev = NULL;
struct sctp_sock *sp;
struct sock *sk;
if (!ulpq->pd_mode)
return;
sk = ulpq->asoc->base.sk;
sp = sctp_sk(sk);
if (sctp_ulpevent_type_enabled(ulpq->asoc->subscribe,
SCTP_PARTIAL_DELIVERY_EVENT))
ev = sctp_ulpevent_make_pdapi(ulpq->asoc,
SCTP_PARTIAL_DELIVERY_ABORTED,
0, 0, 0, gfp);
if (ev)
__skb_queue_tail(&sk->sk_receive_queue, sctp_event2skb(ev));
/* If there is data waiting, send it up the socket now. */
if ((sctp_ulpq_clear_pd(ulpq) || ev) && !sp->data_ready_signalled) {
sp->data_ready_signalled = 1;
sk->sk_data_ready(sk);
}
}
| linux-master | net/sctp/ulpqueue.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2002 International Business Machines, Corp.
*
* This file is part of the SCTP kernel implementation
*
* These functions are the methods for accessing the SCTP inqueue.
*
* An SCTP inqueue is a queue into which you push SCTP packets
* (which might be bundles or fragments of chunks) and out of which you
* pop SCTP whole chunks.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
/* Initialize an SCTP inqueue. */
void sctp_inq_init(struct sctp_inq *queue)
{
INIT_LIST_HEAD(&queue->in_chunk_list);
queue->in_progress = NULL;
/* Create a task for delivering data. */
INIT_WORK(&queue->immediate, NULL);
}
/* Release the memory associated with an SCTP inqueue. */
void sctp_inq_free(struct sctp_inq *queue)
{
struct sctp_chunk *chunk, *tmp;
/* Empty the queue. */
list_for_each_entry_safe(chunk, tmp, &queue->in_chunk_list, list) {
list_del_init(&chunk->list);
sctp_chunk_free(chunk);
}
/* If there is a packet which is currently being worked on,
* free it as well.
*/
if (queue->in_progress) {
sctp_chunk_free(queue->in_progress);
queue->in_progress = NULL;
}
}
/* Put a new packet in an SCTP inqueue.
* We assume that packet->sctp_hdr is set and in host byte order.
*/
void sctp_inq_push(struct sctp_inq *q, struct sctp_chunk *chunk)
{
/* Directly call the packet handling routine. */
if (chunk->rcvr->dead) {
sctp_chunk_free(chunk);
return;
}
/* We are now calling this either from the soft interrupt
* or from the backlog processing.
* Eventually, we should clean up inqueue to not rely
* on the BH related data structures.
*/
list_add_tail(&chunk->list, &q->in_chunk_list);
if (chunk->asoc)
chunk->asoc->stats.ipackets++;
q->immediate.func(&q->immediate);
}
/* Peek at the next chunk on the inqeue. */
struct sctp_chunkhdr *sctp_inq_peek(struct sctp_inq *queue)
{
struct sctp_chunk *chunk;
struct sctp_chunkhdr *ch = NULL;
chunk = queue->in_progress;
/* If there is no more chunks in this packet, say so */
if (chunk->singleton ||
chunk->end_of_packet ||
chunk->pdiscard)
return NULL;
ch = (struct sctp_chunkhdr *)chunk->chunk_end;
return ch;
}
/* Extract a chunk from an SCTP inqueue.
*
* WARNING: If you need to put the chunk on another queue, you need to
* make a shallow copy (clone) of it.
*/
struct sctp_chunk *sctp_inq_pop(struct sctp_inq *queue)
{
struct sctp_chunk *chunk;
struct sctp_chunkhdr *ch = NULL;
/* The assumption is that we are safe to process the chunks
* at this time.
*/
chunk = queue->in_progress;
if (chunk) {
/* There is a packet that we have been working on.
* Any post processing work to do before we move on?
*/
if (chunk->singleton ||
chunk->end_of_packet ||
chunk->pdiscard) {
if (chunk->head_skb == chunk->skb) {
chunk->skb = skb_shinfo(chunk->skb)->frag_list;
goto new_skb;
}
if (chunk->skb->next) {
chunk->skb = chunk->skb->next;
goto new_skb;
}
if (chunk->head_skb)
chunk->skb = chunk->head_skb;
sctp_chunk_free(chunk);
chunk = queue->in_progress = NULL;
} else {
/* Nothing to do. Next chunk in the packet, please. */
ch = (struct sctp_chunkhdr *)chunk->chunk_end;
/* Force chunk->skb->data to chunk->chunk_end. */
skb_pull(chunk->skb, chunk->chunk_end - chunk->skb->data);
/* We are guaranteed to pull a SCTP header. */
}
}
/* Do we need to take the next packet out of the queue to process? */
if (!chunk) {
struct list_head *entry;
next_chunk:
/* Is the queue empty? */
entry = sctp_list_dequeue(&queue->in_chunk_list);
if (!entry)
return NULL;
chunk = list_entry(entry, struct sctp_chunk, list);
if (skb_is_gso(chunk->skb) && skb_is_gso_sctp(chunk->skb)) {
/* GSO-marked skbs but without frags, handle
* them normally
*/
if (skb_shinfo(chunk->skb)->frag_list)
chunk->head_skb = chunk->skb;
/* skbs with "cover letter" */
if (chunk->head_skb && chunk->skb->data_len == chunk->skb->len)
chunk->skb = skb_shinfo(chunk->skb)->frag_list;
if (WARN_ON(!chunk->skb)) {
__SCTP_INC_STATS(dev_net(chunk->skb->dev), SCTP_MIB_IN_PKT_DISCARDS);
sctp_chunk_free(chunk);
goto next_chunk;
}
}
if (chunk->asoc)
sock_rps_save_rxhash(chunk->asoc->base.sk, chunk->skb);
queue->in_progress = chunk;
new_skb:
/* This is the first chunk in the packet. */
ch = (struct sctp_chunkhdr *)chunk->skb->data;
chunk->singleton = 1;
chunk->data_accepted = 0;
chunk->pdiscard = 0;
chunk->auth = 0;
chunk->has_asconf = 0;
chunk->end_of_packet = 0;
if (chunk->head_skb) {
struct sctp_input_cb
*cb = SCTP_INPUT_CB(chunk->skb),
*head_cb = SCTP_INPUT_CB(chunk->head_skb);
cb->chunk = head_cb->chunk;
cb->af = head_cb->af;
}
}
chunk->chunk_hdr = ch;
chunk->chunk_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));
skb_pull(chunk->skb, sizeof(*ch));
chunk->subh.v = NULL; /* Subheader is no longer valid. */
if (chunk->chunk_end + sizeof(*ch) <= skb_tail_pointer(chunk->skb)) {
/* This is not a singleton */
chunk->singleton = 0;
} else if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) {
/* Discard inside state machine. */
chunk->pdiscard = 1;
chunk->chunk_end = skb_tail_pointer(chunk->skb);
} else {
/* We are at the end of the packet, so mark the chunk
* in case we need to send a SACK.
*/
chunk->end_of_packet = 1;
}
pr_debug("+++sctp_inq_pop+++ chunk:%p[%s], length:%d, skb->len:%d\n",
chunk, sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)),
ntohs(chunk->chunk_hdr->length), chunk->skb->len);
return chunk;
}
/* Set a top-half handler.
*
* Originally, we the top-half handler was scheduled as a BH. We now
* call the handler directly in sctp_inq_push() at a time that
* we know we are lock safe.
* The intent is that this routine will pull stuff out of the
* inqueue and process it.
*/
void sctp_inq_set_th_handler(struct sctp_inq *q, work_func_t callback)
{
INIT_WORK(&q->immediate, callback);
}
| linux-master | net/sctp/inqueue.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright Red Hat Inc. 2017
*
* This file is part of the SCTP kernel implementation
*
* These functions manipulate sctp stream queue/scheduling.
*
* Please send any bug reports or fixes you make to the
* email addresched(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Marcelo Ricardo Leitner <[email protected]>
*/
#include <linux/list.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/stream_sched.h>
/* First Come First Serve (a.k.a. FIFO)
* RFC DRAFT ndata Section 3.1
*/
static int sctp_sched_fcfs_set(struct sctp_stream *stream, __u16 sid,
__u16 value, gfp_t gfp)
{
return 0;
}
static int sctp_sched_fcfs_get(struct sctp_stream *stream, __u16 sid,
__u16 *value)
{
*value = 0;
return 0;
}
static int sctp_sched_fcfs_init(struct sctp_stream *stream)
{
return 0;
}
static int sctp_sched_fcfs_init_sid(struct sctp_stream *stream, __u16 sid,
gfp_t gfp)
{
return 0;
}
static void sctp_sched_fcfs_free_sid(struct sctp_stream *stream, __u16 sid)
{
}
static void sctp_sched_fcfs_enqueue(struct sctp_outq *q,
struct sctp_datamsg *msg)
{
}
static struct sctp_chunk *sctp_sched_fcfs_dequeue(struct sctp_outq *q)
{
struct sctp_stream *stream = &q->asoc->stream;
struct sctp_chunk *ch = NULL;
struct list_head *entry;
if (list_empty(&q->out_chunk_list))
goto out;
if (stream->out_curr) {
ch = list_entry(stream->out_curr->ext->outq.next,
struct sctp_chunk, stream_list);
} else {
entry = q->out_chunk_list.next;
ch = list_entry(entry, struct sctp_chunk, list);
}
sctp_sched_dequeue_common(q, ch);
out:
return ch;
}
static void sctp_sched_fcfs_dequeue_done(struct sctp_outq *q,
struct sctp_chunk *chunk)
{
}
static void sctp_sched_fcfs_sched_all(struct sctp_stream *stream)
{
}
static void sctp_sched_fcfs_unsched_all(struct sctp_stream *stream)
{
}
static struct sctp_sched_ops sctp_sched_fcfs = {
.set = sctp_sched_fcfs_set,
.get = sctp_sched_fcfs_get,
.init = sctp_sched_fcfs_init,
.init_sid = sctp_sched_fcfs_init_sid,
.free_sid = sctp_sched_fcfs_free_sid,
.enqueue = sctp_sched_fcfs_enqueue,
.dequeue = sctp_sched_fcfs_dequeue,
.dequeue_done = sctp_sched_fcfs_dequeue_done,
.sched_all = sctp_sched_fcfs_sched_all,
.unsched_all = sctp_sched_fcfs_unsched_all,
};
static void sctp_sched_ops_fcfs_init(void)
{
sctp_sched_ops_register(SCTP_SS_FCFS, &sctp_sched_fcfs);
}
/* API to other parts of the stack */
static struct sctp_sched_ops *sctp_sched_ops[SCTP_SS_MAX + 1];
void sctp_sched_ops_register(enum sctp_sched_type sched,
struct sctp_sched_ops *sched_ops)
{
sctp_sched_ops[sched] = sched_ops;
}
void sctp_sched_ops_init(void)
{
sctp_sched_ops_fcfs_init();
sctp_sched_ops_prio_init();
sctp_sched_ops_rr_init();
sctp_sched_ops_fc_init();
sctp_sched_ops_wfq_init();
}
static void sctp_sched_free_sched(struct sctp_stream *stream)
{
struct sctp_sched_ops *sched = sctp_sched_ops_from_stream(stream);
struct sctp_stream_out_ext *soute;
int i;
sched->unsched_all(stream);
for (i = 0; i < stream->outcnt; i++) {
soute = SCTP_SO(stream, i)->ext;
if (!soute)
continue;
sched->free_sid(stream, i);
/* Give the next scheduler a clean slate. */
memset_after(soute, 0, outq);
}
}
int sctp_sched_set_sched(struct sctp_association *asoc,
enum sctp_sched_type sched)
{
struct sctp_sched_ops *old = asoc->outqueue.sched;
struct sctp_datamsg *msg = NULL;
struct sctp_sched_ops *n;
struct sctp_chunk *ch;
int i, ret = 0;
if (sched > SCTP_SS_MAX)
return -EINVAL;
n = sctp_sched_ops[sched];
if (old == n)
return ret;
if (old)
sctp_sched_free_sched(&asoc->stream);
asoc->outqueue.sched = n;
n->init(&asoc->stream);
for (i = 0; i < asoc->stream.outcnt; i++) {
if (!SCTP_SO(&asoc->stream, i)->ext)
continue;
ret = n->init_sid(&asoc->stream, i, GFP_ATOMIC);
if (ret)
goto err;
}
/* We have to requeue all chunks already queued. */
list_for_each_entry(ch, &asoc->outqueue.out_chunk_list, list) {
if (ch->msg == msg)
continue;
msg = ch->msg;
n->enqueue(&asoc->outqueue, msg);
}
return ret;
err:
sctp_sched_free_sched(&asoc->stream);
asoc->outqueue.sched = &sctp_sched_fcfs; /* Always safe */
return ret;
}
int sctp_sched_get_sched(struct sctp_association *asoc)
{
int i;
for (i = 0; i <= SCTP_SS_MAX; i++)
if (asoc->outqueue.sched == sctp_sched_ops[i])
return i;
return 0;
}
int sctp_sched_set_value(struct sctp_association *asoc, __u16 sid,
__u16 value, gfp_t gfp)
{
if (sid >= asoc->stream.outcnt)
return -EINVAL;
if (!SCTP_SO(&asoc->stream, sid)->ext) {
int ret;
ret = sctp_stream_init_ext(&asoc->stream, sid);
if (ret)
return ret;
}
return asoc->outqueue.sched->set(&asoc->stream, sid, value, gfp);
}
int sctp_sched_get_value(struct sctp_association *asoc, __u16 sid,
__u16 *value)
{
if (sid >= asoc->stream.outcnt)
return -EINVAL;
if (!SCTP_SO(&asoc->stream, sid)->ext)
return 0;
return asoc->outqueue.sched->get(&asoc->stream, sid, value);
}
void sctp_sched_dequeue_done(struct sctp_outq *q, struct sctp_chunk *ch)
{
if (!list_is_last(&ch->frag_list, &ch->msg->chunks) &&
!q->asoc->peer.intl_capable) {
struct sctp_stream_out *sout;
__u16 sid;
/* datamsg is not finish, so save it as current one,
* in case application switch scheduler or a higher
* priority stream comes in.
*/
sid = sctp_chunk_stream_no(ch);
sout = SCTP_SO(&q->asoc->stream, sid);
q->asoc->stream.out_curr = sout;
return;
}
q->asoc->stream.out_curr = NULL;
q->sched->dequeue_done(q, ch);
}
/* Auxiliary functions for the schedulers */
void sctp_sched_dequeue_common(struct sctp_outq *q, struct sctp_chunk *ch)
{
list_del_init(&ch->list);
list_del_init(&ch->stream_list);
q->out_qlen -= ch->skb->len;
}
int sctp_sched_init_sid(struct sctp_stream *stream, __u16 sid, gfp_t gfp)
{
struct sctp_sched_ops *sched = sctp_sched_ops_from_stream(stream);
struct sctp_stream_out_ext *ext = SCTP_SO(stream, sid)->ext;
INIT_LIST_HEAD(&ext->outq);
return sched->init_sid(stream, sid, gfp);
}
struct sctp_sched_ops *sctp_sched_ops_from_stream(struct sctp_stream *stream)
{
struct sctp_association *asoc;
asoc = container_of(stream, struct sctp_association, stream);
return asoc->outqueue.sched;
}
| linux-master | net/sctp/stream_sched.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
*
* This file is part of the SCTP kernel implementation
*
* These functions handle output processing.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Jon Grimm <[email protected]>
* Sridhar Samudrala <[email protected]>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <net/inet_ecn.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/net_namespace.h>
#include <linux/socket.h> /* for sa_family_t */
#include <net/sock.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/checksum.h>
/* Forward declarations for private helpers. */
static enum sctp_xmit __sctp_packet_append_chunk(struct sctp_packet *packet,
struct sctp_chunk *chunk);
static enum sctp_xmit sctp_packet_can_append_data(struct sctp_packet *packet,
struct sctp_chunk *chunk);
static void sctp_packet_append_data(struct sctp_packet *packet,
struct sctp_chunk *chunk);
static enum sctp_xmit sctp_packet_will_fit(struct sctp_packet *packet,
struct sctp_chunk *chunk,
u16 chunk_len);
static void sctp_packet_reset(struct sctp_packet *packet)
{
/* sctp_packet_transmit() relies on this to reset size to the
* current overhead after sending packets.
*/
packet->size = packet->overhead;
packet->has_cookie_echo = 0;
packet->has_sack = 0;
packet->has_data = 0;
packet->has_auth = 0;
packet->ipfragok = 0;
packet->auth = NULL;
}
/* Config a packet.
* This appears to be a followup set of initializations.
*/
void sctp_packet_config(struct sctp_packet *packet, __u32 vtag,
int ecn_capable)
{
struct sctp_transport *tp = packet->transport;
struct sctp_association *asoc = tp->asoc;
struct sctp_sock *sp = NULL;
struct sock *sk;
pr_debug("%s: packet:%p vtag:0x%x\n", __func__, packet, vtag);
packet->vtag = vtag;
/* do the following jobs only once for a flush schedule */
if (!sctp_packet_empty(packet))
return;
/* set packet max_size with pathmtu, then calculate overhead */
packet->max_size = tp->pathmtu;
if (asoc) {
sk = asoc->base.sk;
sp = sctp_sk(sk);
}
packet->overhead = sctp_mtu_payload(sp, 0, 0);
packet->size = packet->overhead;
if (!asoc)
return;
/* update dst or transport pathmtu if in need */
if (!sctp_transport_dst_check(tp)) {
sctp_transport_route(tp, NULL, sp);
if (asoc->param_flags & SPP_PMTUD_ENABLE)
sctp_assoc_sync_pmtu(asoc);
} else if (!sctp_transport_pl_enabled(tp) &&
asoc->param_flags & SPP_PMTUD_ENABLE) {
if (!sctp_transport_pmtu_check(tp))
sctp_assoc_sync_pmtu(asoc);
}
if (asoc->pmtu_pending) {
if (asoc->param_flags & SPP_PMTUD_ENABLE)
sctp_assoc_sync_pmtu(asoc);
asoc->pmtu_pending = 0;
}
/* If there a is a prepend chunk stick it on the list before
* any other chunks get appended.
*/
if (ecn_capable) {
struct sctp_chunk *chunk = sctp_get_ecne_prepend(asoc);
if (chunk)
sctp_packet_append_chunk(packet, chunk);
}
if (!tp->dst)
return;
/* set packet max_size with gso_max_size if gso is enabled*/
rcu_read_lock();
if (__sk_dst_get(sk) != tp->dst) {
dst_hold(tp->dst);
sk_setup_caps(sk, tp->dst);
}
packet->max_size = sk_can_gso(sk) ? min(READ_ONCE(tp->dst->dev->gso_max_size),
GSO_LEGACY_MAX_SIZE)
: asoc->pathmtu;
rcu_read_unlock();
}
/* Initialize the packet structure. */
void sctp_packet_init(struct sctp_packet *packet,
struct sctp_transport *transport,
__u16 sport, __u16 dport)
{
pr_debug("%s: packet:%p transport:%p\n", __func__, packet, transport);
packet->transport = transport;
packet->source_port = sport;
packet->destination_port = dport;
INIT_LIST_HEAD(&packet->chunk_list);
/* The overhead will be calculated by sctp_packet_config() */
packet->overhead = 0;
sctp_packet_reset(packet);
packet->vtag = 0;
}
/* Free a packet. */
void sctp_packet_free(struct sctp_packet *packet)
{
struct sctp_chunk *chunk, *tmp;
pr_debug("%s: packet:%p\n", __func__, packet);
list_for_each_entry_safe(chunk, tmp, &packet->chunk_list, list) {
list_del_init(&chunk->list);
sctp_chunk_free(chunk);
}
}
/* This routine tries to append the chunk to the offered packet. If adding
* the chunk causes the packet to exceed the path MTU and COOKIE_ECHO chunk
* is not present in the packet, it transmits the input packet.
* Data can be bundled with a packet containing a COOKIE_ECHO chunk as long
* as it can fit in the packet, but any more data that does not fit in this
* packet can be sent only after receiving the COOKIE_ACK.
*/
enum sctp_xmit sctp_packet_transmit_chunk(struct sctp_packet *packet,
struct sctp_chunk *chunk,
int one_packet, gfp_t gfp)
{
enum sctp_xmit retval;
pr_debug("%s: packet:%p size:%zu chunk:%p size:%d\n", __func__,
packet, packet->size, chunk, chunk->skb ? chunk->skb->len : -1);
switch ((retval = (sctp_packet_append_chunk(packet, chunk)))) {
case SCTP_XMIT_PMTU_FULL:
if (!packet->has_cookie_echo) {
int error = 0;
error = sctp_packet_transmit(packet, gfp);
if (error < 0)
chunk->skb->sk->sk_err = -error;
/* If we have an empty packet, then we can NOT ever
* return PMTU_FULL.
*/
if (!one_packet)
retval = sctp_packet_append_chunk(packet,
chunk);
}
break;
case SCTP_XMIT_RWND_FULL:
case SCTP_XMIT_OK:
case SCTP_XMIT_DELAY:
break;
}
return retval;
}
/* Try to bundle a pad chunk into a packet with a heartbeat chunk for PLPMTUTD probe */
static enum sctp_xmit sctp_packet_bundle_pad(struct sctp_packet *pkt, struct sctp_chunk *chunk)
{
struct sctp_transport *t = pkt->transport;
struct sctp_chunk *pad;
int overhead = 0;
if (!chunk->pmtu_probe)
return SCTP_XMIT_OK;
/* calculate the Padding Data size for the pad chunk */
overhead += sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
overhead += sizeof(struct sctp_sender_hb_info) + sizeof(struct sctp_pad_chunk);
pad = sctp_make_pad(t->asoc, t->pl.probe_size - overhead);
if (!pad)
return SCTP_XMIT_DELAY;
list_add_tail(&pad->list, &pkt->chunk_list);
pkt->size += SCTP_PAD4(ntohs(pad->chunk_hdr->length));
chunk->transport = t;
return SCTP_XMIT_OK;
}
/* Try to bundle an auth chunk into the packet. */
static enum sctp_xmit sctp_packet_bundle_auth(struct sctp_packet *pkt,
struct sctp_chunk *chunk)
{
struct sctp_association *asoc = pkt->transport->asoc;
enum sctp_xmit retval = SCTP_XMIT_OK;
struct sctp_chunk *auth;
/* if we don't have an association, we can't do authentication */
if (!asoc)
return retval;
/* See if this is an auth chunk we are bundling or if
* auth is already bundled.
*/
if (chunk->chunk_hdr->type == SCTP_CID_AUTH || pkt->has_auth)
return retval;
/* if the peer did not request this chunk to be authenticated,
* don't do it
*/
if (!chunk->auth)
return retval;
auth = sctp_make_auth(asoc, chunk->shkey->key_id);
if (!auth)
return retval;
auth->shkey = chunk->shkey;
sctp_auth_shkey_hold(auth->shkey);
retval = __sctp_packet_append_chunk(pkt, auth);
if (retval != SCTP_XMIT_OK)
sctp_chunk_free(auth);
return retval;
}
/* Try to bundle a SACK with the packet. */
static enum sctp_xmit sctp_packet_bundle_sack(struct sctp_packet *pkt,
struct sctp_chunk *chunk)
{
enum sctp_xmit retval = SCTP_XMIT_OK;
/* If sending DATA and haven't aleady bundled a SACK, try to
* bundle one in to the packet.
*/
if (sctp_chunk_is_data(chunk) && !pkt->has_sack &&
!pkt->has_cookie_echo) {
struct sctp_association *asoc;
struct timer_list *timer;
asoc = pkt->transport->asoc;
timer = &asoc->timers[SCTP_EVENT_TIMEOUT_SACK];
/* If the SACK timer is running, we have a pending SACK */
if (timer_pending(timer)) {
struct sctp_chunk *sack;
if (pkt->transport->sack_generation !=
pkt->transport->asoc->peer.sack_generation)
return retval;
asoc->a_rwnd = asoc->rwnd;
sack = sctp_make_sack(asoc);
if (sack) {
retval = __sctp_packet_append_chunk(pkt, sack);
if (retval != SCTP_XMIT_OK) {
sctp_chunk_free(sack);
goto out;
}
SCTP_INC_STATS(asoc->base.net,
SCTP_MIB_OUTCTRLCHUNKS);
asoc->stats.octrlchunks++;
asoc->peer.sack_needed = 0;
if (del_timer(timer))
sctp_association_put(asoc);
}
}
}
out:
return retval;
}
/* Append a chunk to the offered packet reporting back any inability to do
* so.
*/
static enum sctp_xmit __sctp_packet_append_chunk(struct sctp_packet *packet,
struct sctp_chunk *chunk)
{
__u16 chunk_len = SCTP_PAD4(ntohs(chunk->chunk_hdr->length));
enum sctp_xmit retval = SCTP_XMIT_OK;
/* Check to see if this chunk will fit into the packet */
retval = sctp_packet_will_fit(packet, chunk, chunk_len);
if (retval != SCTP_XMIT_OK)
goto finish;
/* We believe that this chunk is OK to add to the packet */
switch (chunk->chunk_hdr->type) {
case SCTP_CID_DATA:
case SCTP_CID_I_DATA:
/* Account for the data being in the packet */
sctp_packet_append_data(packet, chunk);
/* Disallow SACK bundling after DATA. */
packet->has_sack = 1;
/* Disallow AUTH bundling after DATA */
packet->has_auth = 1;
/* Let it be knows that packet has DATA in it */
packet->has_data = 1;
/* timestamp the chunk for rtx purposes */
chunk->sent_at = jiffies;
/* Mainly used for prsctp RTX policy */
chunk->sent_count++;
break;
case SCTP_CID_COOKIE_ECHO:
packet->has_cookie_echo = 1;
break;
case SCTP_CID_SACK:
packet->has_sack = 1;
if (chunk->asoc)
chunk->asoc->stats.osacks++;
break;
case SCTP_CID_AUTH:
packet->has_auth = 1;
packet->auth = chunk;
break;
}
/* It is OK to send this chunk. */
list_add_tail(&chunk->list, &packet->chunk_list);
packet->size += chunk_len;
chunk->transport = packet->transport;
finish:
return retval;
}
/* Append a chunk to the offered packet reporting back any inability to do
* so.
*/
enum sctp_xmit sctp_packet_append_chunk(struct sctp_packet *packet,
struct sctp_chunk *chunk)
{
enum sctp_xmit retval = SCTP_XMIT_OK;
pr_debug("%s: packet:%p chunk:%p\n", __func__, packet, chunk);
/* Data chunks are special. Before seeing what else we can
* bundle into this packet, check to see if we are allowed to
* send this DATA.
*/
if (sctp_chunk_is_data(chunk)) {
retval = sctp_packet_can_append_data(packet, chunk);
if (retval != SCTP_XMIT_OK)
goto finish;
}
/* Try to bundle AUTH chunk */
retval = sctp_packet_bundle_auth(packet, chunk);
if (retval != SCTP_XMIT_OK)
goto finish;
/* Try to bundle SACK chunk */
retval = sctp_packet_bundle_sack(packet, chunk);
if (retval != SCTP_XMIT_OK)
goto finish;
retval = __sctp_packet_append_chunk(packet, chunk);
if (retval != SCTP_XMIT_OK)
goto finish;
retval = sctp_packet_bundle_pad(packet, chunk);
finish:
return retval;
}
static void sctp_packet_gso_append(struct sk_buff *head, struct sk_buff *skb)
{
if (SCTP_OUTPUT_CB(head)->last == head)
skb_shinfo(head)->frag_list = skb;
else
SCTP_OUTPUT_CB(head)->last->next = skb;
SCTP_OUTPUT_CB(head)->last = skb;
head->truesize += skb->truesize;
head->data_len += skb->len;
head->len += skb->len;
refcount_add(skb->truesize, &head->sk->sk_wmem_alloc);
__skb_header_release(skb);
}
static int sctp_packet_pack(struct sctp_packet *packet,
struct sk_buff *head, int gso, gfp_t gfp)
{
struct sctp_transport *tp = packet->transport;
struct sctp_auth_chunk *auth = NULL;
struct sctp_chunk *chunk, *tmp;
int pkt_count = 0, pkt_size;
struct sock *sk = head->sk;
struct sk_buff *nskb;
int auth_len = 0;
if (gso) {
skb_shinfo(head)->gso_type = sk->sk_gso_type;
SCTP_OUTPUT_CB(head)->last = head;
} else {
nskb = head;
pkt_size = packet->size;
goto merge;
}
do {
/* calculate the pkt_size and alloc nskb */
pkt_size = packet->overhead;
list_for_each_entry_safe(chunk, tmp, &packet->chunk_list,
list) {
int padded = SCTP_PAD4(chunk->skb->len);
if (chunk == packet->auth)
auth_len = padded;
else if (auth_len + padded + packet->overhead >
tp->pathmtu)
return 0;
else if (pkt_size + padded > tp->pathmtu)
break;
pkt_size += padded;
}
nskb = alloc_skb(pkt_size + MAX_HEADER, gfp);
if (!nskb)
return 0;
skb_reserve(nskb, packet->overhead + MAX_HEADER);
merge:
/* merge chunks into nskb and append nskb into head list */
pkt_size -= packet->overhead;
list_for_each_entry_safe(chunk, tmp, &packet->chunk_list, list) {
int padding;
list_del_init(&chunk->list);
if (sctp_chunk_is_data(chunk)) {
if (!sctp_chunk_retransmitted(chunk) &&
!tp->rto_pending) {
chunk->rtt_in_progress = 1;
tp->rto_pending = 1;
}
}
padding = SCTP_PAD4(chunk->skb->len) - chunk->skb->len;
if (padding)
skb_put_zero(chunk->skb, padding);
if (chunk == packet->auth)
auth = (struct sctp_auth_chunk *)
skb_tail_pointer(nskb);
skb_put_data(nskb, chunk->skb->data, chunk->skb->len);
pr_debug("*** Chunk:%p[%s] %s 0x%x, length:%d, chunk->skb->len:%d, rtt_in_progress:%d\n",
chunk,
sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)),
chunk->has_tsn ? "TSN" : "No TSN",
chunk->has_tsn ? ntohl(chunk->subh.data_hdr->tsn) : 0,
ntohs(chunk->chunk_hdr->length), chunk->skb->len,
chunk->rtt_in_progress);
pkt_size -= SCTP_PAD4(chunk->skb->len);
if (!sctp_chunk_is_data(chunk) && chunk != packet->auth)
sctp_chunk_free(chunk);
if (!pkt_size)
break;
}
if (auth) {
sctp_auth_calculate_hmac(tp->asoc, nskb, auth,
packet->auth->shkey, gfp);
/* free auth if no more chunks, or add it back */
if (list_empty(&packet->chunk_list))
sctp_chunk_free(packet->auth);
else
list_add(&packet->auth->list,
&packet->chunk_list);
}
if (gso)
sctp_packet_gso_append(head, nskb);
pkt_count++;
} while (!list_empty(&packet->chunk_list));
if (gso) {
memset(head->cb, 0, max(sizeof(struct inet_skb_parm),
sizeof(struct inet6_skb_parm)));
skb_shinfo(head)->gso_segs = pkt_count;
skb_shinfo(head)->gso_size = GSO_BY_FRAGS;
goto chksum;
}
if (sctp_checksum_disable)
return 1;
if (!(tp->dst->dev->features & NETIF_F_SCTP_CRC) ||
dst_xfrm(tp->dst) || packet->ipfragok || tp->encap_port) {
struct sctphdr *sh =
(struct sctphdr *)skb_transport_header(head);
sh->checksum = sctp_compute_cksum(head, 0);
} else {
chksum:
head->ip_summed = CHECKSUM_PARTIAL;
head->csum_not_inet = 1;
head->csum_start = skb_transport_header(head) - head->head;
head->csum_offset = offsetof(struct sctphdr, checksum);
}
return pkt_count;
}
/* All packets are sent to the network through this function from
* sctp_outq_tail().
*
* The return value is always 0 for now.
*/
int sctp_packet_transmit(struct sctp_packet *packet, gfp_t gfp)
{
struct sctp_transport *tp = packet->transport;
struct sctp_association *asoc = tp->asoc;
struct sctp_chunk *chunk, *tmp;
int pkt_count, gso = 0;
struct sk_buff *head;
struct sctphdr *sh;
struct sock *sk;
pr_debug("%s: packet:%p\n", __func__, packet);
if (list_empty(&packet->chunk_list))
return 0;
chunk = list_entry(packet->chunk_list.next, struct sctp_chunk, list);
sk = chunk->skb->sk;
if (packet->size > tp->pathmtu && !packet->ipfragok && !chunk->pmtu_probe) {
if (tp->pl.state == SCTP_PL_ERROR) { /* do IP fragmentation if in Error state */
packet->ipfragok = 1;
} else {
if (!sk_can_gso(sk)) { /* check gso */
pr_err_once("Trying to GSO but underlying device doesn't support it.");
goto out;
}
gso = 1;
}
}
/* alloc head skb */
head = alloc_skb((gso ? packet->overhead : packet->size) +
MAX_HEADER, gfp);
if (!head)
goto out;
skb_reserve(head, packet->overhead + MAX_HEADER);
skb_set_owner_w(head, sk);
/* set sctp header */
sh = skb_push(head, sizeof(struct sctphdr));
skb_reset_transport_header(head);
sh->source = htons(packet->source_port);
sh->dest = htons(packet->destination_port);
sh->vtag = htonl(packet->vtag);
sh->checksum = 0;
/* drop packet if no dst */
if (!tp->dst) {
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(head);
goto out;
}
/* pack up chunks */
pkt_count = sctp_packet_pack(packet, head, gso, gfp);
if (!pkt_count) {
kfree_skb(head);
goto out;
}
pr_debug("***sctp_transmit_packet*** skb->len:%d\n", head->len);
/* start autoclose timer */
if (packet->has_data && sctp_state(asoc, ESTABLISHED) &&
asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) {
struct timer_list *timer =
&asoc->timers[SCTP_EVENT_TIMEOUT_AUTOCLOSE];
unsigned long timeout =
asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE];
if (!mod_timer(timer, jiffies + timeout))
sctp_association_hold(asoc);
}
/* sctp xmit */
tp->af_specific->ecn_capable(sk);
if (asoc) {
asoc->stats.opackets += pkt_count;
if (asoc->peer.last_sent_to != tp)
asoc->peer.last_sent_to = tp;
}
head->ignore_df = packet->ipfragok;
if (tp->dst_pending_confirm)
skb_set_dst_pending_confirm(head, 1);
/* neighbour should be confirmed on successful transmission or
* positive error
*/
if (tp->af_specific->sctp_xmit(head, tp) >= 0 &&
tp->dst_pending_confirm)
tp->dst_pending_confirm = 0;
out:
list_for_each_entry_safe(chunk, tmp, &packet->chunk_list, list) {
list_del_init(&chunk->list);
if (!sctp_chunk_is_data(chunk))
sctp_chunk_free(chunk);
}
sctp_packet_reset(packet);
return 0;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* This private function check to see if a chunk can be added */
static enum sctp_xmit sctp_packet_can_append_data(struct sctp_packet *packet,
struct sctp_chunk *chunk)
{
size_t datasize, rwnd, inflight, flight_size;
struct sctp_transport *transport = packet->transport;
struct sctp_association *asoc = transport->asoc;
struct sctp_outq *q = &asoc->outqueue;
/* RFC 2960 6.1 Transmission of DATA Chunks
*
* A) At any given time, the data sender MUST NOT transmit new data to
* any destination transport address if its peer's rwnd indicates
* that the peer has no buffer space (i.e. rwnd is 0, see Section
* 6.2.1). However, regardless of the value of rwnd (including if it
* is 0), the data sender can always have one DATA chunk in flight to
* the receiver if allowed by cwnd (see rule B below). This rule
* allows the sender to probe for a change in rwnd that the sender
* missed due to the SACK having been lost in transit from the data
* receiver to the data sender.
*/
rwnd = asoc->peer.rwnd;
inflight = q->outstanding_bytes;
flight_size = transport->flight_size;
datasize = sctp_data_size(chunk);
if (datasize > rwnd && inflight > 0)
/* We have (at least) one data chunk in flight,
* so we can't fall back to rule 6.1 B).
*/
return SCTP_XMIT_RWND_FULL;
/* RFC 2960 6.1 Transmission of DATA Chunks
*
* B) At any given time, the sender MUST NOT transmit new data
* to a given transport address if it has cwnd or more bytes
* of data outstanding to that transport address.
*/
/* RFC 7.2.4 & the Implementers Guide 2.8.
*
* 3) ...
* When a Fast Retransmit is being performed the sender SHOULD
* ignore the value of cwnd and SHOULD NOT delay retransmission.
*/
if (chunk->fast_retransmit != SCTP_NEED_FRTX &&
flight_size >= transport->cwnd)
return SCTP_XMIT_RWND_FULL;
/* Nagle's algorithm to solve small-packet problem:
* Inhibit the sending of new chunks when new outgoing data arrives
* if any previously transmitted data on the connection remains
* unacknowledged.
*/
if ((sctp_sk(asoc->base.sk)->nodelay || inflight == 0) &&
!asoc->force_delay)
/* Nothing unacked */
return SCTP_XMIT_OK;
if (!sctp_packet_empty(packet))
/* Append to packet */
return SCTP_XMIT_OK;
if (!sctp_state(asoc, ESTABLISHED))
return SCTP_XMIT_OK;
/* Check whether this chunk and all the rest of pending data will fit
* or delay in hopes of bundling a full sized packet.
*/
if (chunk->skb->len + q->out_qlen > transport->pathmtu -
packet->overhead - sctp_datachk_len(&chunk->asoc->stream) - 4)
/* Enough data queued to fill a packet */
return SCTP_XMIT_OK;
/* Don't delay large message writes that may have been fragmented */
if (!chunk->msg->can_delay)
return SCTP_XMIT_OK;
/* Defer until all data acked or packet full */
return SCTP_XMIT_DELAY;
}
/* This private function does management things when adding DATA chunk */
static void sctp_packet_append_data(struct sctp_packet *packet,
struct sctp_chunk *chunk)
{
struct sctp_transport *transport = packet->transport;
size_t datasize = sctp_data_size(chunk);
struct sctp_association *asoc = transport->asoc;
u32 rwnd = asoc->peer.rwnd;
/* Keep track of how many bytes are in flight over this transport. */
transport->flight_size += datasize;
/* Keep track of how many bytes are in flight to the receiver. */
asoc->outqueue.outstanding_bytes += datasize;
/* Update our view of the receiver's rwnd. */
if (datasize < rwnd)
rwnd -= datasize;
else
rwnd = 0;
asoc->peer.rwnd = rwnd;
sctp_chunk_assign_tsn(chunk);
asoc->stream.si->assign_number(chunk);
}
static enum sctp_xmit sctp_packet_will_fit(struct sctp_packet *packet,
struct sctp_chunk *chunk,
u16 chunk_len)
{
enum sctp_xmit retval = SCTP_XMIT_OK;
size_t psize, pmtu, maxsize;
/* Don't bundle in this packet if this chunk's auth key doesn't
* match other chunks already enqueued on this packet. Also,
* don't bundle the chunk with auth key if other chunks in this
* packet don't have auth key.
*/
if ((packet->auth && chunk->shkey != packet->auth->shkey) ||
(!packet->auth && chunk->shkey &&
chunk->chunk_hdr->type != SCTP_CID_AUTH))
return SCTP_XMIT_PMTU_FULL;
psize = packet->size;
if (packet->transport->asoc)
pmtu = packet->transport->asoc->pathmtu;
else
pmtu = packet->transport->pathmtu;
/* Decide if we need to fragment or resubmit later. */
if (psize + chunk_len > pmtu) {
/* It's OK to fragment at IP level if any one of the following
* is true:
* 1. The packet is empty (meaning this chunk is greater
* the MTU)
* 2. The packet doesn't have any data in it yet and data
* requires authentication.
*/
if (sctp_packet_empty(packet) ||
(!packet->has_data && chunk->auth)) {
/* We no longer do re-fragmentation.
* Just fragment at the IP layer, if we
* actually hit this condition
*/
packet->ipfragok = 1;
goto out;
}
/* Similarly, if this chunk was built before a PMTU
* reduction, we have to fragment it at IP level now. So
* if the packet already contains something, we need to
* flush.
*/
maxsize = pmtu - packet->overhead;
if (packet->auth)
maxsize -= SCTP_PAD4(packet->auth->skb->len);
if (chunk_len > maxsize)
retval = SCTP_XMIT_PMTU_FULL;
/* It is also okay to fragment if the chunk we are
* adding is a control chunk, but only if current packet
* is not a GSO one otherwise it causes fragmentation of
* a large frame. So in this case we allow the
* fragmentation by forcing it to be in a new packet.
*/
if (!sctp_chunk_is_data(chunk) && packet->has_data)
retval = SCTP_XMIT_PMTU_FULL;
if (psize + chunk_len > packet->max_size)
/* Hit GSO/PMTU limit, gotta flush */
retval = SCTP_XMIT_PMTU_FULL;
if (!packet->transport->burst_limited &&
psize + chunk_len > (packet->transport->cwnd >> 1))
/* Do not allow a single GSO packet to use more
* than half of cwnd.
*/
retval = SCTP_XMIT_PMTU_FULL;
if (packet->transport->burst_limited &&
psize + chunk_len > (packet->transport->burst_limited >> 1))
/* Do not allow a single GSO packet to use more
* than half of original cwnd.
*/
retval = SCTP_XMIT_PMTU_FULL;
/* Otherwise it will fit in the GSO packet */
}
out:
return retval;
}
| linux-master | net/sctp/output.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright Red Hat Inc. 2022
*
* This file is part of the SCTP kernel implementation
*
* These functions manipulate sctp stream queue/scheduling.
*
* Please send any bug reports or fixes you make to the
* email addresched(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Xin Long <[email protected]>
*/
#include <linux/list.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/stream_sched.h>
/* Fair Capacity and Weighted Fair Queueing handling
* RFC 8260 section 3.5 and 3.6
*/
static void sctp_sched_fc_unsched_all(struct sctp_stream *stream);
static int sctp_sched_wfq_set(struct sctp_stream *stream, __u16 sid,
__u16 weight, gfp_t gfp)
{
struct sctp_stream_out_ext *soute = SCTP_SO(stream, sid)->ext;
if (!weight)
return -EINVAL;
soute->fc_weight = weight;
return 0;
}
static int sctp_sched_wfq_get(struct sctp_stream *stream, __u16 sid,
__u16 *value)
{
struct sctp_stream_out_ext *soute = SCTP_SO(stream, sid)->ext;
*value = soute->fc_weight;
return 0;
}
static int sctp_sched_fc_set(struct sctp_stream *stream, __u16 sid,
__u16 weight, gfp_t gfp)
{
return 0;
}
static int sctp_sched_fc_get(struct sctp_stream *stream, __u16 sid,
__u16 *value)
{
return 0;
}
static int sctp_sched_fc_init(struct sctp_stream *stream)
{
INIT_LIST_HEAD(&stream->fc_list);
return 0;
}
static int sctp_sched_fc_init_sid(struct sctp_stream *stream, __u16 sid,
gfp_t gfp)
{
struct sctp_stream_out_ext *soute = SCTP_SO(stream, sid)->ext;
INIT_LIST_HEAD(&soute->fc_list);
soute->fc_length = 0;
soute->fc_weight = 1;
return 0;
}
static void sctp_sched_fc_free_sid(struct sctp_stream *stream, __u16 sid)
{
}
static void sctp_sched_fc_sched(struct sctp_stream *stream,
struct sctp_stream_out_ext *soute)
{
struct sctp_stream_out_ext *pos;
if (!list_empty(&soute->fc_list))
return;
list_for_each_entry(pos, &stream->fc_list, fc_list)
if ((__u64)pos->fc_length * soute->fc_weight >=
(__u64)soute->fc_length * pos->fc_weight)
break;
list_add_tail(&soute->fc_list, &pos->fc_list);
}
static void sctp_sched_fc_enqueue(struct sctp_outq *q,
struct sctp_datamsg *msg)
{
struct sctp_stream *stream;
struct sctp_chunk *ch;
__u16 sid;
ch = list_first_entry(&msg->chunks, struct sctp_chunk, frag_list);
sid = sctp_chunk_stream_no(ch);
stream = &q->asoc->stream;
sctp_sched_fc_sched(stream, SCTP_SO(stream, sid)->ext);
}
static struct sctp_chunk *sctp_sched_fc_dequeue(struct sctp_outq *q)
{
struct sctp_stream *stream = &q->asoc->stream;
struct sctp_stream_out_ext *soute;
struct sctp_chunk *ch;
/* Bail out quickly if queue is empty */
if (list_empty(&q->out_chunk_list))
return NULL;
/* Find which chunk is next */
if (stream->out_curr)
soute = stream->out_curr->ext;
else
soute = list_entry(stream->fc_list.next, struct sctp_stream_out_ext, fc_list);
ch = list_entry(soute->outq.next, struct sctp_chunk, stream_list);
sctp_sched_dequeue_common(q, ch);
return ch;
}
static void sctp_sched_fc_dequeue_done(struct sctp_outq *q,
struct sctp_chunk *ch)
{
struct sctp_stream *stream = &q->asoc->stream;
struct sctp_stream_out_ext *soute, *pos;
__u16 sid, i;
sid = sctp_chunk_stream_no(ch);
soute = SCTP_SO(stream, sid)->ext;
/* reduce all fc_lengths by U32_MAX / 4 if the current fc_length overflows. */
if (soute->fc_length > U32_MAX - ch->skb->len) {
for (i = 0; i < stream->outcnt; i++) {
pos = SCTP_SO(stream, i)->ext;
if (!pos)
continue;
if (pos->fc_length <= (U32_MAX >> 2)) {
pos->fc_length = 0;
continue;
}
pos->fc_length -= (U32_MAX >> 2);
}
}
soute->fc_length += ch->skb->len;
if (list_empty(&soute->outq)) {
list_del_init(&soute->fc_list);
return;
}
pos = soute;
list_for_each_entry_continue(pos, &stream->fc_list, fc_list)
if ((__u64)pos->fc_length * soute->fc_weight >=
(__u64)soute->fc_length * pos->fc_weight)
break;
list_move_tail(&soute->fc_list, &pos->fc_list);
}
static void sctp_sched_fc_sched_all(struct sctp_stream *stream)
{
struct sctp_association *asoc;
struct sctp_chunk *ch;
asoc = container_of(stream, struct sctp_association, stream);
list_for_each_entry(ch, &asoc->outqueue.out_chunk_list, list) {
__u16 sid = sctp_chunk_stream_no(ch);
if (SCTP_SO(stream, sid)->ext)
sctp_sched_fc_sched(stream, SCTP_SO(stream, sid)->ext);
}
}
static void sctp_sched_fc_unsched_all(struct sctp_stream *stream)
{
struct sctp_stream_out_ext *soute, *tmp;
list_for_each_entry_safe(soute, tmp, &stream->fc_list, fc_list)
list_del_init(&soute->fc_list);
}
static struct sctp_sched_ops sctp_sched_fc = {
.set = sctp_sched_fc_set,
.get = sctp_sched_fc_get,
.init = sctp_sched_fc_init,
.init_sid = sctp_sched_fc_init_sid,
.free_sid = sctp_sched_fc_free_sid,
.enqueue = sctp_sched_fc_enqueue,
.dequeue = sctp_sched_fc_dequeue,
.dequeue_done = sctp_sched_fc_dequeue_done,
.sched_all = sctp_sched_fc_sched_all,
.unsched_all = sctp_sched_fc_unsched_all,
};
void sctp_sched_ops_fc_init(void)
{
sctp_sched_ops_register(SCTP_SS_FC, &sctp_sched_fc);
}
static struct sctp_sched_ops sctp_sched_wfq = {
.set = sctp_sched_wfq_set,
.get = sctp_sched_wfq_get,
.init = sctp_sched_fc_init,
.init_sid = sctp_sched_fc_init_sid,
.free_sid = sctp_sched_fc_free_sid,
.enqueue = sctp_sched_fc_enqueue,
.dequeue = sctp_sched_fc_dequeue,
.dequeue_done = sctp_sched_fc_dequeue_done,
.sched_all = sctp_sched_fc_sched_all,
.unsched_all = sctp_sched_fc_unsched_all,
};
void sctp_sched_ops_wfq_init(void)
{
sctp_sched_ops_register(SCTP_SS_WFQ, &sctp_sched_wfq);
}
| linux-master | net/sctp/stream_sched_fc.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
*
* This file is part of the SCTP kernel implementation
*
* This file contains sctp stream maniuplation primitives and helpers.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Written or modified by:
* Xin Long <[email protected]>
*/
#include <linux/list.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/stream_sched.h>
static void sctp_stream_shrink_out(struct sctp_stream *stream, __u16 outcnt)
{
struct sctp_association *asoc;
struct sctp_chunk *ch, *temp;
struct sctp_outq *outq;
asoc = container_of(stream, struct sctp_association, stream);
outq = &asoc->outqueue;
list_for_each_entry_safe(ch, temp, &outq->out_chunk_list, list) {
__u16 sid = sctp_chunk_stream_no(ch);
if (sid < outcnt)
continue;
sctp_sched_dequeue_common(outq, ch);
/* No need to call dequeue_done here because
* the chunks are not scheduled by now.
*/
/* Mark as failed send. */
sctp_chunk_fail(ch, (__force __u32)SCTP_ERROR_INV_STRM);
if (asoc->peer.prsctp_capable &&
SCTP_PR_PRIO_ENABLED(ch->sinfo.sinfo_flags))
asoc->sent_cnt_removable--;
sctp_chunk_free(ch);
}
}
static void sctp_stream_free_ext(struct sctp_stream *stream, __u16 sid)
{
struct sctp_sched_ops *sched;
if (!SCTP_SO(stream, sid)->ext)
return;
sched = sctp_sched_ops_from_stream(stream);
sched->free_sid(stream, sid);
kfree(SCTP_SO(stream, sid)->ext);
SCTP_SO(stream, sid)->ext = NULL;
}
/* Migrates chunks from stream queues to new stream queues if needed,
* but not across associations. Also, removes those chunks to streams
* higher than the new max.
*/
static void sctp_stream_outq_migrate(struct sctp_stream *stream,
struct sctp_stream *new, __u16 outcnt)
{
int i;
if (stream->outcnt > outcnt)
sctp_stream_shrink_out(stream, outcnt);
if (new) {
/* Here we actually move the old ext stuff into the new
* buffer, because we want to keep it. Then
* sctp_stream_update will swap ->out pointers.
*/
for (i = 0; i < outcnt; i++) {
sctp_stream_free_ext(new, i);
SCTP_SO(new, i)->ext = SCTP_SO(stream, i)->ext;
SCTP_SO(stream, i)->ext = NULL;
}
}
for (i = outcnt; i < stream->outcnt; i++)
sctp_stream_free_ext(stream, i);
}
static int sctp_stream_alloc_out(struct sctp_stream *stream, __u16 outcnt,
gfp_t gfp)
{
int ret;
if (outcnt <= stream->outcnt)
goto out;
ret = genradix_prealloc(&stream->out, outcnt, gfp);
if (ret)
return ret;
out:
stream->outcnt = outcnt;
return 0;
}
static int sctp_stream_alloc_in(struct sctp_stream *stream, __u16 incnt,
gfp_t gfp)
{
int ret;
if (incnt <= stream->incnt)
goto out;
ret = genradix_prealloc(&stream->in, incnt, gfp);
if (ret)
return ret;
out:
stream->incnt = incnt;
return 0;
}
int sctp_stream_init(struct sctp_stream *stream, __u16 outcnt, __u16 incnt,
gfp_t gfp)
{
struct sctp_sched_ops *sched = sctp_sched_ops_from_stream(stream);
int i, ret = 0;
gfp |= __GFP_NOWARN;
/* Initial stream->out size may be very big, so free it and alloc
* a new one with new outcnt to save memory if needed.
*/
if (outcnt == stream->outcnt)
goto handle_in;
/* Filter out chunks queued on streams that won't exist anymore */
sched->unsched_all(stream);
sctp_stream_outq_migrate(stream, NULL, outcnt);
sched->sched_all(stream);
ret = sctp_stream_alloc_out(stream, outcnt, gfp);
if (ret)
return ret;
for (i = 0; i < stream->outcnt; i++)
SCTP_SO(stream, i)->state = SCTP_STREAM_OPEN;
handle_in:
sctp_stream_interleave_init(stream);
if (!incnt)
return 0;
return sctp_stream_alloc_in(stream, incnt, gfp);
}
int sctp_stream_init_ext(struct sctp_stream *stream, __u16 sid)
{
struct sctp_stream_out_ext *soute;
int ret;
soute = kzalloc(sizeof(*soute), GFP_KERNEL);
if (!soute)
return -ENOMEM;
SCTP_SO(stream, sid)->ext = soute;
ret = sctp_sched_init_sid(stream, sid, GFP_KERNEL);
if (ret) {
kfree(SCTP_SO(stream, sid)->ext);
SCTP_SO(stream, sid)->ext = NULL;
}
return ret;
}
void sctp_stream_free(struct sctp_stream *stream)
{
struct sctp_sched_ops *sched = sctp_sched_ops_from_stream(stream);
int i;
sched->unsched_all(stream);
for (i = 0; i < stream->outcnt; i++)
sctp_stream_free_ext(stream, i);
genradix_free(&stream->out);
genradix_free(&stream->in);
}
void sctp_stream_clear(struct sctp_stream *stream)
{
int i;
for (i = 0; i < stream->outcnt; i++) {
SCTP_SO(stream, i)->mid = 0;
SCTP_SO(stream, i)->mid_uo = 0;
}
for (i = 0; i < stream->incnt; i++)
SCTP_SI(stream, i)->mid = 0;
}
void sctp_stream_update(struct sctp_stream *stream, struct sctp_stream *new)
{
struct sctp_sched_ops *sched = sctp_sched_ops_from_stream(stream);
sched->unsched_all(stream);
sctp_stream_outq_migrate(stream, new, new->outcnt);
sctp_stream_free(stream);
stream->out = new->out;
stream->in = new->in;
stream->outcnt = new->outcnt;
stream->incnt = new->incnt;
sched->sched_all(stream);
new->out.tree.root = NULL;
new->in.tree.root = NULL;
new->outcnt = 0;
new->incnt = 0;
}
static int sctp_send_reconf(struct sctp_association *asoc,
struct sctp_chunk *chunk)
{
int retval = 0;
retval = sctp_primitive_RECONF(asoc->base.net, asoc, chunk);
if (retval)
sctp_chunk_free(chunk);
return retval;
}
static bool sctp_stream_outq_is_empty(struct sctp_stream *stream,
__u16 str_nums, __be16 *str_list)
{
struct sctp_association *asoc;
__u16 i;
asoc = container_of(stream, struct sctp_association, stream);
if (!asoc->outqueue.out_qlen)
return true;
if (!str_nums)
return false;
for (i = 0; i < str_nums; i++) {
__u16 sid = ntohs(str_list[i]);
if (SCTP_SO(stream, sid)->ext &&
!list_empty(&SCTP_SO(stream, sid)->ext->outq))
return false;
}
return true;
}
int sctp_send_reset_streams(struct sctp_association *asoc,
struct sctp_reset_streams *params)
{
struct sctp_stream *stream = &asoc->stream;
__u16 i, str_nums, *str_list;
struct sctp_chunk *chunk;
int retval = -EINVAL;
__be16 *nstr_list;
bool out, in;
if (!asoc->peer.reconf_capable ||
!(asoc->strreset_enable & SCTP_ENABLE_RESET_STREAM_REQ)) {
retval = -ENOPROTOOPT;
goto out;
}
if (asoc->strreset_outstanding) {
retval = -EINPROGRESS;
goto out;
}
out = params->srs_flags & SCTP_STREAM_RESET_OUTGOING;
in = params->srs_flags & SCTP_STREAM_RESET_INCOMING;
if (!out && !in)
goto out;
str_nums = params->srs_number_streams;
str_list = params->srs_stream_list;
if (str_nums) {
int param_len = 0;
if (out) {
for (i = 0; i < str_nums; i++)
if (str_list[i] >= stream->outcnt)
goto out;
param_len = str_nums * sizeof(__u16) +
sizeof(struct sctp_strreset_outreq);
}
if (in) {
for (i = 0; i < str_nums; i++)
if (str_list[i] >= stream->incnt)
goto out;
param_len += str_nums * sizeof(__u16) +
sizeof(struct sctp_strreset_inreq);
}
if (param_len > SCTP_MAX_CHUNK_LEN -
sizeof(struct sctp_reconf_chunk))
goto out;
}
nstr_list = kcalloc(str_nums, sizeof(__be16), GFP_KERNEL);
if (!nstr_list) {
retval = -ENOMEM;
goto out;
}
for (i = 0; i < str_nums; i++)
nstr_list[i] = htons(str_list[i]);
if (out && !sctp_stream_outq_is_empty(stream, str_nums, nstr_list)) {
kfree(nstr_list);
retval = -EAGAIN;
goto out;
}
chunk = sctp_make_strreset_req(asoc, str_nums, nstr_list, out, in);
kfree(nstr_list);
if (!chunk) {
retval = -ENOMEM;
goto out;
}
if (out) {
if (str_nums)
for (i = 0; i < str_nums; i++)
SCTP_SO(stream, str_list[i])->state =
SCTP_STREAM_CLOSED;
else
for (i = 0; i < stream->outcnt; i++)
SCTP_SO(stream, i)->state = SCTP_STREAM_CLOSED;
}
asoc->strreset_chunk = chunk;
sctp_chunk_hold(asoc->strreset_chunk);
retval = sctp_send_reconf(asoc, chunk);
if (retval) {
sctp_chunk_put(asoc->strreset_chunk);
asoc->strreset_chunk = NULL;
if (!out)
goto out;
if (str_nums)
for (i = 0; i < str_nums; i++)
SCTP_SO(stream, str_list[i])->state =
SCTP_STREAM_OPEN;
else
for (i = 0; i < stream->outcnt; i++)
SCTP_SO(stream, i)->state = SCTP_STREAM_OPEN;
goto out;
}
asoc->strreset_outstanding = out + in;
out:
return retval;
}
int sctp_send_reset_assoc(struct sctp_association *asoc)
{
struct sctp_stream *stream = &asoc->stream;
struct sctp_chunk *chunk = NULL;
int retval;
__u16 i;
if (!asoc->peer.reconf_capable ||
!(asoc->strreset_enable & SCTP_ENABLE_RESET_ASSOC_REQ))
return -ENOPROTOOPT;
if (asoc->strreset_outstanding)
return -EINPROGRESS;
if (!sctp_outq_is_empty(&asoc->outqueue))
return -EAGAIN;
chunk = sctp_make_strreset_tsnreq(asoc);
if (!chunk)
return -ENOMEM;
/* Block further xmit of data until this request is completed */
for (i = 0; i < stream->outcnt; i++)
SCTP_SO(stream, i)->state = SCTP_STREAM_CLOSED;
asoc->strreset_chunk = chunk;
sctp_chunk_hold(asoc->strreset_chunk);
retval = sctp_send_reconf(asoc, chunk);
if (retval) {
sctp_chunk_put(asoc->strreset_chunk);
asoc->strreset_chunk = NULL;
for (i = 0; i < stream->outcnt; i++)
SCTP_SO(stream, i)->state = SCTP_STREAM_OPEN;
return retval;
}
asoc->strreset_outstanding = 1;
return 0;
}
int sctp_send_add_streams(struct sctp_association *asoc,
struct sctp_add_streams *params)
{
struct sctp_stream *stream = &asoc->stream;
struct sctp_chunk *chunk = NULL;
int retval;
__u32 outcnt, incnt;
__u16 out, in;
if (!asoc->peer.reconf_capable ||
!(asoc->strreset_enable & SCTP_ENABLE_CHANGE_ASSOC_REQ)) {
retval = -ENOPROTOOPT;
goto out;
}
if (asoc->strreset_outstanding) {
retval = -EINPROGRESS;
goto out;
}
out = params->sas_outstrms;
in = params->sas_instrms;
outcnt = stream->outcnt + out;
incnt = stream->incnt + in;
if (outcnt > SCTP_MAX_STREAM || incnt > SCTP_MAX_STREAM ||
(!out && !in)) {
retval = -EINVAL;
goto out;
}
if (out) {
retval = sctp_stream_alloc_out(stream, outcnt, GFP_KERNEL);
if (retval)
goto out;
}
chunk = sctp_make_strreset_addstrm(asoc, out, in);
if (!chunk) {
retval = -ENOMEM;
goto out;
}
asoc->strreset_chunk = chunk;
sctp_chunk_hold(asoc->strreset_chunk);
retval = sctp_send_reconf(asoc, chunk);
if (retval) {
sctp_chunk_put(asoc->strreset_chunk);
asoc->strreset_chunk = NULL;
goto out;
}
asoc->strreset_outstanding = !!out + !!in;
out:
return retval;
}
static struct sctp_paramhdr *sctp_chunk_lookup_strreset_param(
struct sctp_association *asoc, __be32 resp_seq,
__be16 type)
{
struct sctp_chunk *chunk = asoc->strreset_chunk;
struct sctp_reconf_chunk *hdr;
union sctp_params param;
if (!chunk)
return NULL;
hdr = (struct sctp_reconf_chunk *)chunk->chunk_hdr;
sctp_walk_params(param, hdr) {
/* sctp_strreset_tsnreq is actually the basic structure
* of all stream reconf params, so it's safe to use it
* to access request_seq.
*/
struct sctp_strreset_tsnreq *req = param.v;
if ((!resp_seq || req->request_seq == resp_seq) &&
(!type || type == req->param_hdr.type))
return param.v;
}
return NULL;
}
static void sctp_update_strreset_result(struct sctp_association *asoc,
__u32 result)
{
asoc->strreset_result[1] = asoc->strreset_result[0];
asoc->strreset_result[0] = result;
}
struct sctp_chunk *sctp_process_strreset_outreq(
struct sctp_association *asoc,
union sctp_params param,
struct sctp_ulpevent **evp)
{
struct sctp_strreset_outreq *outreq = param.v;
struct sctp_stream *stream = &asoc->stream;
__u32 result = SCTP_STRRESET_DENIED;
__be16 *str_p = NULL;
__u32 request_seq;
__u16 i, nums;
request_seq = ntohl(outreq->request_seq);
if (ntohl(outreq->send_reset_at_tsn) >
sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map)) {
result = SCTP_STRRESET_IN_PROGRESS;
goto err;
}
if (TSN_lt(asoc->strreset_inseq, request_seq) ||
TSN_lt(request_seq, asoc->strreset_inseq - 2)) {
result = SCTP_STRRESET_ERR_BAD_SEQNO;
goto err;
} else if (TSN_lt(request_seq, asoc->strreset_inseq)) {
i = asoc->strreset_inseq - request_seq - 1;
result = asoc->strreset_result[i];
goto err;
}
asoc->strreset_inseq++;
/* Check strreset_enable after inseq inc, as sender cannot tell
* the peer doesn't enable strreset after receiving response with
* result denied, as well as to keep consistent with bsd.
*/
if (!(asoc->strreset_enable & SCTP_ENABLE_RESET_STREAM_REQ))
goto out;
nums = (ntohs(param.p->length) - sizeof(*outreq)) / sizeof(__u16);
str_p = outreq->list_of_streams;
for (i = 0; i < nums; i++) {
if (ntohs(str_p[i]) >= stream->incnt) {
result = SCTP_STRRESET_ERR_WRONG_SSN;
goto out;
}
}
if (asoc->strreset_chunk) {
if (!sctp_chunk_lookup_strreset_param(
asoc, outreq->response_seq,
SCTP_PARAM_RESET_IN_REQUEST)) {
/* same process with outstanding isn't 0 */
result = SCTP_STRRESET_ERR_IN_PROGRESS;
goto out;
}
asoc->strreset_outstanding--;
asoc->strreset_outseq++;
if (!asoc->strreset_outstanding) {
struct sctp_transport *t;
t = asoc->strreset_chunk->transport;
if (del_timer(&t->reconf_timer))
sctp_transport_put(t);
sctp_chunk_put(asoc->strreset_chunk);
asoc->strreset_chunk = NULL;
}
}
if (nums)
for (i = 0; i < nums; i++)
SCTP_SI(stream, ntohs(str_p[i]))->mid = 0;
else
for (i = 0; i < stream->incnt; i++)
SCTP_SI(stream, i)->mid = 0;
result = SCTP_STRRESET_PERFORMED;
*evp = sctp_ulpevent_make_stream_reset_event(asoc,
SCTP_STREAM_RESET_INCOMING_SSN, nums, str_p, GFP_ATOMIC);
out:
sctp_update_strreset_result(asoc, result);
err:
return sctp_make_strreset_resp(asoc, result, request_seq);
}
struct sctp_chunk *sctp_process_strreset_inreq(
struct sctp_association *asoc,
union sctp_params param,
struct sctp_ulpevent **evp)
{
struct sctp_strreset_inreq *inreq = param.v;
struct sctp_stream *stream = &asoc->stream;
__u32 result = SCTP_STRRESET_DENIED;
struct sctp_chunk *chunk = NULL;
__u32 request_seq;
__u16 i, nums;
__be16 *str_p;
request_seq = ntohl(inreq->request_seq);
if (TSN_lt(asoc->strreset_inseq, request_seq) ||
TSN_lt(request_seq, asoc->strreset_inseq - 2)) {
result = SCTP_STRRESET_ERR_BAD_SEQNO;
goto err;
} else if (TSN_lt(request_seq, asoc->strreset_inseq)) {
i = asoc->strreset_inseq - request_seq - 1;
result = asoc->strreset_result[i];
if (result == SCTP_STRRESET_PERFORMED)
return NULL;
goto err;
}
asoc->strreset_inseq++;
if (!(asoc->strreset_enable & SCTP_ENABLE_RESET_STREAM_REQ))
goto out;
if (asoc->strreset_outstanding) {
result = SCTP_STRRESET_ERR_IN_PROGRESS;
goto out;
}
nums = (ntohs(param.p->length) - sizeof(*inreq)) / sizeof(__u16);
str_p = inreq->list_of_streams;
for (i = 0; i < nums; i++) {
if (ntohs(str_p[i]) >= stream->outcnt) {
result = SCTP_STRRESET_ERR_WRONG_SSN;
goto out;
}
}
if (!sctp_stream_outq_is_empty(stream, nums, str_p)) {
result = SCTP_STRRESET_IN_PROGRESS;
asoc->strreset_inseq--;
goto err;
}
chunk = sctp_make_strreset_req(asoc, nums, str_p, 1, 0);
if (!chunk)
goto out;
if (nums)
for (i = 0; i < nums; i++)
SCTP_SO(stream, ntohs(str_p[i]))->state =
SCTP_STREAM_CLOSED;
else
for (i = 0; i < stream->outcnt; i++)
SCTP_SO(stream, i)->state = SCTP_STREAM_CLOSED;
asoc->strreset_chunk = chunk;
asoc->strreset_outstanding = 1;
sctp_chunk_hold(asoc->strreset_chunk);
result = SCTP_STRRESET_PERFORMED;
out:
sctp_update_strreset_result(asoc, result);
err:
if (!chunk)
chunk = sctp_make_strreset_resp(asoc, result, request_seq);
return chunk;
}
struct sctp_chunk *sctp_process_strreset_tsnreq(
struct sctp_association *asoc,
union sctp_params param,
struct sctp_ulpevent **evp)
{
__u32 init_tsn = 0, next_tsn = 0, max_tsn_seen;
struct sctp_strreset_tsnreq *tsnreq = param.v;
struct sctp_stream *stream = &asoc->stream;
__u32 result = SCTP_STRRESET_DENIED;
__u32 request_seq;
__u16 i;
request_seq = ntohl(tsnreq->request_seq);
if (TSN_lt(asoc->strreset_inseq, request_seq) ||
TSN_lt(request_seq, asoc->strreset_inseq - 2)) {
result = SCTP_STRRESET_ERR_BAD_SEQNO;
goto err;
} else if (TSN_lt(request_seq, asoc->strreset_inseq)) {
i = asoc->strreset_inseq - request_seq - 1;
result = asoc->strreset_result[i];
if (result == SCTP_STRRESET_PERFORMED) {
next_tsn = asoc->ctsn_ack_point + 1;
init_tsn =
sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map) + 1;
}
goto err;
}
if (!sctp_outq_is_empty(&asoc->outqueue)) {
result = SCTP_STRRESET_IN_PROGRESS;
goto err;
}
asoc->strreset_inseq++;
if (!(asoc->strreset_enable & SCTP_ENABLE_RESET_ASSOC_REQ))
goto out;
if (asoc->strreset_outstanding) {
result = SCTP_STRRESET_ERR_IN_PROGRESS;
goto out;
}
/* G4: The same processing as though a FWD-TSN chunk (as defined in
* [RFC3758]) with all streams affected and a new cumulative TSN
* ACK of the Receiver's Next TSN minus 1 were received MUST be
* performed.
*/
max_tsn_seen = sctp_tsnmap_get_max_tsn_seen(&asoc->peer.tsn_map);
asoc->stream.si->report_ftsn(&asoc->ulpq, max_tsn_seen);
/* G1: Compute an appropriate value for the Receiver's Next TSN -- the
* TSN that the peer should use to send the next DATA chunk. The
* value SHOULD be the smallest TSN not acknowledged by the
* receiver of the request plus 2^31.
*/
init_tsn = sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map) + (1 << 31);
sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
init_tsn, GFP_ATOMIC);
/* G3: The same processing as though a SACK chunk with no gap report
* and a cumulative TSN ACK of the Sender's Next TSN minus 1 were
* received MUST be performed.
*/
sctp_outq_free(&asoc->outqueue);
/* G2: Compute an appropriate value for the local endpoint's next TSN,
* i.e., the next TSN assigned by the receiver of the SSN/TSN reset
* chunk. The value SHOULD be the highest TSN sent by the receiver
* of the request plus 1.
*/
next_tsn = asoc->next_tsn;
asoc->ctsn_ack_point = next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
/* G5: The next expected and outgoing SSNs MUST be reset to 0 for all
* incoming and outgoing streams.
*/
for (i = 0; i < stream->outcnt; i++) {
SCTP_SO(stream, i)->mid = 0;
SCTP_SO(stream, i)->mid_uo = 0;
}
for (i = 0; i < stream->incnt; i++)
SCTP_SI(stream, i)->mid = 0;
result = SCTP_STRRESET_PERFORMED;
*evp = sctp_ulpevent_make_assoc_reset_event(asoc, 0, init_tsn,
next_tsn, GFP_ATOMIC);
out:
sctp_update_strreset_result(asoc, result);
err:
return sctp_make_strreset_tsnresp(asoc, result, request_seq,
next_tsn, init_tsn);
}
struct sctp_chunk *sctp_process_strreset_addstrm_out(
struct sctp_association *asoc,
union sctp_params param,
struct sctp_ulpevent **evp)
{
struct sctp_strreset_addstrm *addstrm = param.v;
struct sctp_stream *stream = &asoc->stream;
__u32 result = SCTP_STRRESET_DENIED;
__u32 request_seq, incnt;
__u16 in, i;
request_seq = ntohl(addstrm->request_seq);
if (TSN_lt(asoc->strreset_inseq, request_seq) ||
TSN_lt(request_seq, asoc->strreset_inseq - 2)) {
result = SCTP_STRRESET_ERR_BAD_SEQNO;
goto err;
} else if (TSN_lt(request_seq, asoc->strreset_inseq)) {
i = asoc->strreset_inseq - request_seq - 1;
result = asoc->strreset_result[i];
goto err;
}
asoc->strreset_inseq++;
if (!(asoc->strreset_enable & SCTP_ENABLE_CHANGE_ASSOC_REQ))
goto out;
in = ntohs(addstrm->number_of_streams);
incnt = stream->incnt + in;
if (!in || incnt > SCTP_MAX_STREAM)
goto out;
if (sctp_stream_alloc_in(stream, incnt, GFP_ATOMIC))
goto out;
if (asoc->strreset_chunk) {
if (!sctp_chunk_lookup_strreset_param(
asoc, 0, SCTP_PARAM_RESET_ADD_IN_STREAMS)) {
/* same process with outstanding isn't 0 */
result = SCTP_STRRESET_ERR_IN_PROGRESS;
goto out;
}
asoc->strreset_outstanding--;
asoc->strreset_outseq++;
if (!asoc->strreset_outstanding) {
struct sctp_transport *t;
t = asoc->strreset_chunk->transport;
if (del_timer(&t->reconf_timer))
sctp_transport_put(t);
sctp_chunk_put(asoc->strreset_chunk);
asoc->strreset_chunk = NULL;
}
}
stream->incnt = incnt;
result = SCTP_STRRESET_PERFORMED;
*evp = sctp_ulpevent_make_stream_change_event(asoc,
0, ntohs(addstrm->number_of_streams), 0, GFP_ATOMIC);
out:
sctp_update_strreset_result(asoc, result);
err:
return sctp_make_strreset_resp(asoc, result, request_seq);
}
struct sctp_chunk *sctp_process_strreset_addstrm_in(
struct sctp_association *asoc,
union sctp_params param,
struct sctp_ulpevent **evp)
{
struct sctp_strreset_addstrm *addstrm = param.v;
struct sctp_stream *stream = &asoc->stream;
__u32 result = SCTP_STRRESET_DENIED;
struct sctp_chunk *chunk = NULL;
__u32 request_seq, outcnt;
__u16 out, i;
int ret;
request_seq = ntohl(addstrm->request_seq);
if (TSN_lt(asoc->strreset_inseq, request_seq) ||
TSN_lt(request_seq, asoc->strreset_inseq - 2)) {
result = SCTP_STRRESET_ERR_BAD_SEQNO;
goto err;
} else if (TSN_lt(request_seq, asoc->strreset_inseq)) {
i = asoc->strreset_inseq - request_seq - 1;
result = asoc->strreset_result[i];
if (result == SCTP_STRRESET_PERFORMED)
return NULL;
goto err;
}
asoc->strreset_inseq++;
if (!(asoc->strreset_enable & SCTP_ENABLE_CHANGE_ASSOC_REQ))
goto out;
if (asoc->strreset_outstanding) {
result = SCTP_STRRESET_ERR_IN_PROGRESS;
goto out;
}
out = ntohs(addstrm->number_of_streams);
outcnt = stream->outcnt + out;
if (!out || outcnt > SCTP_MAX_STREAM)
goto out;
ret = sctp_stream_alloc_out(stream, outcnt, GFP_ATOMIC);
if (ret)
goto out;
chunk = sctp_make_strreset_addstrm(asoc, out, 0);
if (!chunk)
goto out;
asoc->strreset_chunk = chunk;
asoc->strreset_outstanding = 1;
sctp_chunk_hold(asoc->strreset_chunk);
stream->outcnt = outcnt;
result = SCTP_STRRESET_PERFORMED;
out:
sctp_update_strreset_result(asoc, result);
err:
if (!chunk)
chunk = sctp_make_strreset_resp(asoc, result, request_seq);
return chunk;
}
struct sctp_chunk *sctp_process_strreset_resp(
struct sctp_association *asoc,
union sctp_params param,
struct sctp_ulpevent **evp)
{
struct sctp_stream *stream = &asoc->stream;
struct sctp_strreset_resp *resp = param.v;
struct sctp_transport *t;
__u16 i, nums, flags = 0;
struct sctp_paramhdr *req;
__u32 result;
req = sctp_chunk_lookup_strreset_param(asoc, resp->response_seq, 0);
if (!req)
return NULL;
result = ntohl(resp->result);
if (result != SCTP_STRRESET_PERFORMED) {
/* if in progress, do nothing but retransmit */
if (result == SCTP_STRRESET_IN_PROGRESS)
return NULL;
else if (result == SCTP_STRRESET_DENIED)
flags = SCTP_STREAM_RESET_DENIED;
else
flags = SCTP_STREAM_RESET_FAILED;
}
if (req->type == SCTP_PARAM_RESET_OUT_REQUEST) {
struct sctp_strreset_outreq *outreq;
__be16 *str_p;
outreq = (struct sctp_strreset_outreq *)req;
str_p = outreq->list_of_streams;
nums = (ntohs(outreq->param_hdr.length) - sizeof(*outreq)) /
sizeof(__u16);
if (result == SCTP_STRRESET_PERFORMED) {
struct sctp_stream_out *sout;
if (nums) {
for (i = 0; i < nums; i++) {
sout = SCTP_SO(stream, ntohs(str_p[i]));
sout->mid = 0;
sout->mid_uo = 0;
}
} else {
for (i = 0; i < stream->outcnt; i++) {
sout = SCTP_SO(stream, i);
sout->mid = 0;
sout->mid_uo = 0;
}
}
}
flags |= SCTP_STREAM_RESET_OUTGOING_SSN;
for (i = 0; i < stream->outcnt; i++)
SCTP_SO(stream, i)->state = SCTP_STREAM_OPEN;
*evp = sctp_ulpevent_make_stream_reset_event(asoc, flags,
nums, str_p, GFP_ATOMIC);
} else if (req->type == SCTP_PARAM_RESET_IN_REQUEST) {
struct sctp_strreset_inreq *inreq;
__be16 *str_p;
/* if the result is performed, it's impossible for inreq */
if (result == SCTP_STRRESET_PERFORMED)
return NULL;
inreq = (struct sctp_strreset_inreq *)req;
str_p = inreq->list_of_streams;
nums = (ntohs(inreq->param_hdr.length) - sizeof(*inreq)) /
sizeof(__u16);
flags |= SCTP_STREAM_RESET_INCOMING_SSN;
*evp = sctp_ulpevent_make_stream_reset_event(asoc, flags,
nums, str_p, GFP_ATOMIC);
} else if (req->type == SCTP_PARAM_RESET_TSN_REQUEST) {
struct sctp_strreset_resptsn *resptsn;
__u32 stsn, rtsn;
/* check for resptsn, as sctp_verify_reconf didn't do it*/
if (ntohs(param.p->length) != sizeof(*resptsn))
return NULL;
resptsn = (struct sctp_strreset_resptsn *)resp;
stsn = ntohl(resptsn->senders_next_tsn);
rtsn = ntohl(resptsn->receivers_next_tsn);
if (result == SCTP_STRRESET_PERFORMED) {
__u32 mtsn = sctp_tsnmap_get_max_tsn_seen(
&asoc->peer.tsn_map);
LIST_HEAD(temp);
asoc->stream.si->report_ftsn(&asoc->ulpq, mtsn);
sctp_tsnmap_init(&asoc->peer.tsn_map,
SCTP_TSN_MAP_INITIAL,
stsn, GFP_ATOMIC);
/* Clean up sacked and abandoned queues only. As the
* out_chunk_list may not be empty, splice it to temp,
* then get it back after sctp_outq_free is done.
*/
list_splice_init(&asoc->outqueue.out_chunk_list, &temp);
sctp_outq_free(&asoc->outqueue);
list_splice_init(&temp, &asoc->outqueue.out_chunk_list);
asoc->next_tsn = rtsn;
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
for (i = 0; i < stream->outcnt; i++) {
SCTP_SO(stream, i)->mid = 0;
SCTP_SO(stream, i)->mid_uo = 0;
}
for (i = 0; i < stream->incnt; i++)
SCTP_SI(stream, i)->mid = 0;
}
for (i = 0; i < stream->outcnt; i++)
SCTP_SO(stream, i)->state = SCTP_STREAM_OPEN;
*evp = sctp_ulpevent_make_assoc_reset_event(asoc, flags,
stsn, rtsn, GFP_ATOMIC);
} else if (req->type == SCTP_PARAM_RESET_ADD_OUT_STREAMS) {
struct sctp_strreset_addstrm *addstrm;
__u16 number;
addstrm = (struct sctp_strreset_addstrm *)req;
nums = ntohs(addstrm->number_of_streams);
number = stream->outcnt - nums;
if (result == SCTP_STRRESET_PERFORMED) {
for (i = number; i < stream->outcnt; i++)
SCTP_SO(stream, i)->state = SCTP_STREAM_OPEN;
} else {
sctp_stream_shrink_out(stream, number);
stream->outcnt = number;
}
*evp = sctp_ulpevent_make_stream_change_event(asoc, flags,
0, nums, GFP_ATOMIC);
} else if (req->type == SCTP_PARAM_RESET_ADD_IN_STREAMS) {
struct sctp_strreset_addstrm *addstrm;
/* if the result is performed, it's impossible for addstrm in
* request.
*/
if (result == SCTP_STRRESET_PERFORMED)
return NULL;
addstrm = (struct sctp_strreset_addstrm *)req;
nums = ntohs(addstrm->number_of_streams);
*evp = sctp_ulpevent_make_stream_change_event(asoc, flags,
nums, 0, GFP_ATOMIC);
}
asoc->strreset_outstanding--;
asoc->strreset_outseq++;
/* remove everything for this reconf request */
if (!asoc->strreset_outstanding) {
t = asoc->strreset_chunk->transport;
if (del_timer(&t->reconf_timer))
sctp_transport_put(t);
sctp_chunk_put(asoc->strreset_chunk);
asoc->strreset_chunk = NULL;
}
return NULL;
}
| linux-master | net/sctp/stream.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Copyright Jonathan Naylor G4KLX ([email protected])
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/slab.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <linux/uaccess.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <net/netrom.h>
/*
* This routine purges all of the queues of frames.
*/
void nr_clear_queues(struct sock *sk)
{
struct nr_sock *nr = nr_sk(sk);
skb_queue_purge(&sk->sk_write_queue);
skb_queue_purge(&nr->ack_queue);
skb_queue_purge(&nr->reseq_queue);
skb_queue_purge(&nr->frag_queue);
}
/*
* This routine purges the input queue of those frames that have been
* acknowledged. This replaces the boxes labelled "V(a) <- N(r)" on the
* SDL diagram.
*/
void nr_frames_acked(struct sock *sk, unsigned short nr)
{
struct nr_sock *nrom = nr_sk(sk);
struct sk_buff *skb;
/*
* Remove all the ack-ed frames from the ack queue.
*/
if (nrom->va != nr) {
while (skb_peek(&nrom->ack_queue) != NULL && nrom->va != nr) {
skb = skb_dequeue(&nrom->ack_queue);
kfree_skb(skb);
nrom->va = (nrom->va + 1) % NR_MODULUS;
}
}
}
/*
* Requeue all the un-ack-ed frames on the output queue to be picked
* up by nr_kick called from the timer. This arrangement handles the
* possibility of an empty output queue.
*/
void nr_requeue_frames(struct sock *sk)
{
struct sk_buff *skb, *skb_prev = NULL;
while ((skb = skb_dequeue(&nr_sk(sk)->ack_queue)) != NULL) {
if (skb_prev == NULL)
skb_queue_head(&sk->sk_write_queue, skb);
else
skb_append(skb_prev, skb, &sk->sk_write_queue);
skb_prev = skb;
}
}
/*
* Validate that the value of nr is between va and vs. Return true or
* false for testing.
*/
int nr_validate_nr(struct sock *sk, unsigned short nr)
{
struct nr_sock *nrom = nr_sk(sk);
unsigned short vc = nrom->va;
while (vc != nrom->vs) {
if (nr == vc) return 1;
vc = (vc + 1) % NR_MODULUS;
}
return nr == nrom->vs;
}
/*
* Check that ns is within the receive window.
*/
int nr_in_rx_window(struct sock *sk, unsigned short ns)
{
struct nr_sock *nr = nr_sk(sk);
unsigned short vc = nr->vr;
unsigned short vt = (nr->vl + nr->window) % NR_MODULUS;
while (vc != vt) {
if (ns == vc) return 1;
vc = (vc + 1) % NR_MODULUS;
}
return 0;
}
/*
* This routine is called when the HDLC layer internally generates a
* control frame.
*/
void nr_write_internal(struct sock *sk, int frametype)
{
struct nr_sock *nr = nr_sk(sk);
struct sk_buff *skb;
unsigned char *dptr;
int len, timeout;
len = NR_TRANSPORT_LEN;
switch (frametype & 0x0F) {
case NR_CONNREQ:
len += 17;
break;
case NR_CONNACK:
len += (nr->bpqext) ? 2 : 1;
break;
case NR_DISCREQ:
case NR_DISCACK:
case NR_INFOACK:
break;
default:
printk(KERN_ERR "NET/ROM: nr_write_internal - invalid frame type %d\n", frametype);
return;
}
skb = alloc_skb(NR_NETWORK_LEN + len, GFP_ATOMIC);
if (!skb)
return;
/*
* Space for AX.25 and NET/ROM network header
*/
skb_reserve(skb, NR_NETWORK_LEN);
dptr = skb_put(skb, len);
switch (frametype & 0x0F) {
case NR_CONNREQ:
timeout = nr->t1 / HZ;
*dptr++ = nr->my_index;
*dptr++ = nr->my_id;
*dptr++ = 0;
*dptr++ = 0;
*dptr++ = frametype;
*dptr++ = nr->window;
memcpy(dptr, &nr->user_addr, AX25_ADDR_LEN);
dptr[6] &= ~AX25_CBIT;
dptr[6] &= ~AX25_EBIT;
dptr[6] |= AX25_SSSID_SPARE;
dptr += AX25_ADDR_LEN;
memcpy(dptr, &nr->source_addr, AX25_ADDR_LEN);
dptr[6] &= ~AX25_CBIT;
dptr[6] &= ~AX25_EBIT;
dptr[6] |= AX25_SSSID_SPARE;
dptr += AX25_ADDR_LEN;
*dptr++ = timeout % 256;
*dptr++ = timeout / 256;
break;
case NR_CONNACK:
*dptr++ = nr->your_index;
*dptr++ = nr->your_id;
*dptr++ = nr->my_index;
*dptr++ = nr->my_id;
*dptr++ = frametype;
*dptr++ = nr->window;
if (nr->bpqext) *dptr++ = sysctl_netrom_network_ttl_initialiser;
break;
case NR_DISCREQ:
case NR_DISCACK:
*dptr++ = nr->your_index;
*dptr++ = nr->your_id;
*dptr++ = 0;
*dptr++ = 0;
*dptr++ = frametype;
break;
case NR_INFOACK:
*dptr++ = nr->your_index;
*dptr++ = nr->your_id;
*dptr++ = 0;
*dptr++ = nr->vr;
*dptr++ = frametype;
break;
}
nr_transmit_buffer(sk, skb);
}
/*
* This routine is called to send an error reply.
*/
void __nr_transmit_reply(struct sk_buff *skb, int mine, unsigned char cmdflags)
{
struct sk_buff *skbn;
unsigned char *dptr;
int len;
len = NR_NETWORK_LEN + NR_TRANSPORT_LEN + 1;
if ((skbn = alloc_skb(len, GFP_ATOMIC)) == NULL)
return;
skb_reserve(skbn, 0);
dptr = skb_put(skbn, NR_NETWORK_LEN + NR_TRANSPORT_LEN);
skb_copy_from_linear_data_offset(skb, 7, dptr, AX25_ADDR_LEN);
dptr[6] &= ~AX25_CBIT;
dptr[6] &= ~AX25_EBIT;
dptr[6] |= AX25_SSSID_SPARE;
dptr += AX25_ADDR_LEN;
skb_copy_from_linear_data(skb, dptr, AX25_ADDR_LEN);
dptr[6] &= ~AX25_CBIT;
dptr[6] |= AX25_EBIT;
dptr[6] |= AX25_SSSID_SPARE;
dptr += AX25_ADDR_LEN;
*dptr++ = sysctl_netrom_network_ttl_initialiser;
if (mine) {
*dptr++ = 0;
*dptr++ = 0;
*dptr++ = skb->data[15];
*dptr++ = skb->data[16];
} else {
*dptr++ = skb->data[15];
*dptr++ = skb->data[16];
*dptr++ = 0;
*dptr++ = 0;
}
*dptr++ = cmdflags;
*dptr++ = 0;
if (!nr_route_frame(skbn, NULL))
kfree_skb(skbn);
}
void nr_disconnect(struct sock *sk, int reason)
{
nr_stop_t1timer(sk);
nr_stop_t2timer(sk);
nr_stop_t4timer(sk);
nr_stop_idletimer(sk);
nr_clear_queues(sk);
nr_sk(sk)->state = NR_STATE_0;
sk->sk_state = TCP_CLOSE;
sk->sk_err = reason;
sk->sk_shutdown |= SEND_SHUTDOWN;
if (!sock_flag(sk, SOCK_DEAD)) {
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_DEAD);
}
}
| linux-master | net/netrom/nr_subr.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Copyright Jonathan Naylor G4KLX ([email protected])
* Copyright Alan Cox GW4PTS ([email protected])
* Copyright Tomi Manninen OH2BNS ([email protected])
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/slab.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <net/arp.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <linux/uaccess.h>
#include <linux/fcntl.h>
#include <linux/termios.h> /* For TIOCINQ/OUTQ */
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/notifier.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <net/netrom.h>
#include <linux/seq_file.h>
#include <linux/export.h>
static unsigned int nr_neigh_no = 1;
static HLIST_HEAD(nr_node_list);
static DEFINE_SPINLOCK(nr_node_list_lock);
static HLIST_HEAD(nr_neigh_list);
static DEFINE_SPINLOCK(nr_neigh_list_lock);
static struct nr_node *nr_node_get(ax25_address *callsign)
{
struct nr_node *found = NULL;
struct nr_node *nr_node;
spin_lock_bh(&nr_node_list_lock);
nr_node_for_each(nr_node, &nr_node_list)
if (ax25cmp(callsign, &nr_node->callsign) == 0) {
nr_node_hold(nr_node);
found = nr_node;
break;
}
spin_unlock_bh(&nr_node_list_lock);
return found;
}
static struct nr_neigh *nr_neigh_get_dev(ax25_address *callsign,
struct net_device *dev)
{
struct nr_neigh *found = NULL;
struct nr_neigh *nr_neigh;
spin_lock_bh(&nr_neigh_list_lock);
nr_neigh_for_each(nr_neigh, &nr_neigh_list)
if (ax25cmp(callsign, &nr_neigh->callsign) == 0 &&
nr_neigh->dev == dev) {
nr_neigh_hold(nr_neigh);
found = nr_neigh;
break;
}
spin_unlock_bh(&nr_neigh_list_lock);
return found;
}
static void nr_remove_neigh(struct nr_neigh *);
/* re-sort the routes in quality order. */
static void re_sort_routes(struct nr_node *nr_node, int x, int y)
{
if (nr_node->routes[y].quality > nr_node->routes[x].quality) {
if (nr_node->which == x)
nr_node->which = y;
else if (nr_node->which == y)
nr_node->which = x;
swap(nr_node->routes[x], nr_node->routes[y]);
}
}
/*
* Add a new route to a node, and in the process add the node and the
* neighbour if it is new.
*/
static int __must_check nr_add_node(ax25_address *nr, const char *mnemonic,
ax25_address *ax25, ax25_digi *ax25_digi, struct net_device *dev,
int quality, int obs_count)
{
struct nr_node *nr_node;
struct nr_neigh *nr_neigh;
int i, found;
struct net_device *odev;
if ((odev=nr_dev_get(nr)) != NULL) { /* Can't add routes to ourself */
dev_put(odev);
return -EINVAL;
}
nr_node = nr_node_get(nr);
nr_neigh = nr_neigh_get_dev(ax25, dev);
/*
* The L2 link to a neighbour has failed in the past
* and now a frame comes from this neighbour. We assume
* it was a temporary trouble with the link and reset the
* routes now (and not wait for a node broadcast).
*/
if (nr_neigh != NULL && nr_neigh->failed != 0 && quality == 0) {
struct nr_node *nr_nodet;
spin_lock_bh(&nr_node_list_lock);
nr_node_for_each(nr_nodet, &nr_node_list) {
nr_node_lock(nr_nodet);
for (i = 0; i < nr_nodet->count; i++)
if (nr_nodet->routes[i].neighbour == nr_neigh)
if (i < nr_nodet->which)
nr_nodet->which = i;
nr_node_unlock(nr_nodet);
}
spin_unlock_bh(&nr_node_list_lock);
}
if (nr_neigh != NULL)
nr_neigh->failed = 0;
if (quality == 0 && nr_neigh != NULL && nr_node != NULL) {
nr_neigh_put(nr_neigh);
nr_node_put(nr_node);
return 0;
}
if (nr_neigh == NULL) {
if ((nr_neigh = kmalloc(sizeof(*nr_neigh), GFP_ATOMIC)) == NULL) {
if (nr_node)
nr_node_put(nr_node);
return -ENOMEM;
}
nr_neigh->callsign = *ax25;
nr_neigh->digipeat = NULL;
nr_neigh->ax25 = NULL;
nr_neigh->dev = dev;
nr_neigh->quality = sysctl_netrom_default_path_quality;
nr_neigh->locked = 0;
nr_neigh->count = 0;
nr_neigh->number = nr_neigh_no++;
nr_neigh->failed = 0;
refcount_set(&nr_neigh->refcount, 1);
if (ax25_digi != NULL && ax25_digi->ndigi > 0) {
nr_neigh->digipeat = kmemdup(ax25_digi,
sizeof(*ax25_digi),
GFP_KERNEL);
if (nr_neigh->digipeat == NULL) {
kfree(nr_neigh);
if (nr_node)
nr_node_put(nr_node);
return -ENOMEM;
}
}
spin_lock_bh(&nr_neigh_list_lock);
hlist_add_head(&nr_neigh->neigh_node, &nr_neigh_list);
nr_neigh_hold(nr_neigh);
spin_unlock_bh(&nr_neigh_list_lock);
}
if (quality != 0 && ax25cmp(nr, ax25) == 0 && !nr_neigh->locked)
nr_neigh->quality = quality;
if (nr_node == NULL) {
if ((nr_node = kmalloc(sizeof(*nr_node), GFP_ATOMIC)) == NULL) {
if (nr_neigh)
nr_neigh_put(nr_neigh);
return -ENOMEM;
}
nr_node->callsign = *nr;
strcpy(nr_node->mnemonic, mnemonic);
nr_node->which = 0;
nr_node->count = 1;
refcount_set(&nr_node->refcount, 1);
spin_lock_init(&nr_node->node_lock);
nr_node->routes[0].quality = quality;
nr_node->routes[0].obs_count = obs_count;
nr_node->routes[0].neighbour = nr_neigh;
nr_neigh_hold(nr_neigh);
nr_neigh->count++;
spin_lock_bh(&nr_node_list_lock);
hlist_add_head(&nr_node->node_node, &nr_node_list);
/* refcount initialized at 1 */
spin_unlock_bh(&nr_node_list_lock);
nr_neigh_put(nr_neigh);
return 0;
}
nr_node_lock(nr_node);
if (quality != 0)
strcpy(nr_node->mnemonic, mnemonic);
for (found = 0, i = 0; i < nr_node->count; i++) {
if (nr_node->routes[i].neighbour == nr_neigh) {
nr_node->routes[i].quality = quality;
nr_node->routes[i].obs_count = obs_count;
found = 1;
break;
}
}
if (!found) {
/* We have space at the bottom, slot it in */
if (nr_node->count < 3) {
nr_node->routes[2] = nr_node->routes[1];
nr_node->routes[1] = nr_node->routes[0];
nr_node->routes[0].quality = quality;
nr_node->routes[0].obs_count = obs_count;
nr_node->routes[0].neighbour = nr_neigh;
nr_node->which++;
nr_node->count++;
nr_neigh_hold(nr_neigh);
nr_neigh->count++;
} else {
/* It must be better than the worst */
if (quality > nr_node->routes[2].quality) {
nr_node->routes[2].neighbour->count--;
nr_neigh_put(nr_node->routes[2].neighbour);
if (nr_node->routes[2].neighbour->count == 0 && !nr_node->routes[2].neighbour->locked)
nr_remove_neigh(nr_node->routes[2].neighbour);
nr_node->routes[2].quality = quality;
nr_node->routes[2].obs_count = obs_count;
nr_node->routes[2].neighbour = nr_neigh;
nr_neigh_hold(nr_neigh);
nr_neigh->count++;
}
}
}
/* Now re-sort the routes in quality order */
switch (nr_node->count) {
case 3:
re_sort_routes(nr_node, 0, 1);
re_sort_routes(nr_node, 1, 2);
fallthrough;
case 2:
re_sort_routes(nr_node, 0, 1);
break;
case 1:
break;
}
for (i = 0; i < nr_node->count; i++) {
if (nr_node->routes[i].neighbour == nr_neigh) {
if (i < nr_node->which)
nr_node->which = i;
break;
}
}
nr_neigh_put(nr_neigh);
nr_node_unlock(nr_node);
nr_node_put(nr_node);
return 0;
}
static inline void __nr_remove_node(struct nr_node *nr_node)
{
hlist_del_init(&nr_node->node_node);
nr_node_put(nr_node);
}
#define nr_remove_node_locked(__node) \
__nr_remove_node(__node)
static void nr_remove_node(struct nr_node *nr_node)
{
spin_lock_bh(&nr_node_list_lock);
__nr_remove_node(nr_node);
spin_unlock_bh(&nr_node_list_lock);
}
static inline void __nr_remove_neigh(struct nr_neigh *nr_neigh)
{
hlist_del_init(&nr_neigh->neigh_node);
nr_neigh_put(nr_neigh);
}
#define nr_remove_neigh_locked(__neigh) \
__nr_remove_neigh(__neigh)
static void nr_remove_neigh(struct nr_neigh *nr_neigh)
{
spin_lock_bh(&nr_neigh_list_lock);
__nr_remove_neigh(nr_neigh);
spin_unlock_bh(&nr_neigh_list_lock);
}
/*
* "Delete" a node. Strictly speaking remove a route to a node. The node
* is only deleted if no routes are left to it.
*/
static int nr_del_node(ax25_address *callsign, ax25_address *neighbour, struct net_device *dev)
{
struct nr_node *nr_node;
struct nr_neigh *nr_neigh;
int i;
nr_node = nr_node_get(callsign);
if (nr_node == NULL)
return -EINVAL;
nr_neigh = nr_neigh_get_dev(neighbour, dev);
if (nr_neigh == NULL) {
nr_node_put(nr_node);
return -EINVAL;
}
nr_node_lock(nr_node);
for (i = 0; i < nr_node->count; i++) {
if (nr_node->routes[i].neighbour == nr_neigh) {
nr_neigh->count--;
nr_neigh_put(nr_neigh);
if (nr_neigh->count == 0 && !nr_neigh->locked)
nr_remove_neigh(nr_neigh);
nr_neigh_put(nr_neigh);
nr_node->count--;
if (nr_node->count == 0) {
nr_remove_node(nr_node);
} else {
switch (i) {
case 0:
nr_node->routes[0] = nr_node->routes[1];
fallthrough;
case 1:
nr_node->routes[1] = nr_node->routes[2];
fallthrough;
case 2:
break;
}
nr_node_put(nr_node);
}
nr_node_unlock(nr_node);
return 0;
}
}
nr_neigh_put(nr_neigh);
nr_node_unlock(nr_node);
nr_node_put(nr_node);
return -EINVAL;
}
/*
* Lock a neighbour with a quality.
*/
static int __must_check nr_add_neigh(ax25_address *callsign,
ax25_digi *ax25_digi, struct net_device *dev, unsigned int quality)
{
struct nr_neigh *nr_neigh;
nr_neigh = nr_neigh_get_dev(callsign, dev);
if (nr_neigh) {
nr_neigh->quality = quality;
nr_neigh->locked = 1;
nr_neigh_put(nr_neigh);
return 0;
}
if ((nr_neigh = kmalloc(sizeof(*nr_neigh), GFP_ATOMIC)) == NULL)
return -ENOMEM;
nr_neigh->callsign = *callsign;
nr_neigh->digipeat = NULL;
nr_neigh->ax25 = NULL;
nr_neigh->dev = dev;
nr_neigh->quality = quality;
nr_neigh->locked = 1;
nr_neigh->count = 0;
nr_neigh->number = nr_neigh_no++;
nr_neigh->failed = 0;
refcount_set(&nr_neigh->refcount, 1);
if (ax25_digi != NULL && ax25_digi->ndigi > 0) {
nr_neigh->digipeat = kmemdup(ax25_digi, sizeof(*ax25_digi),
GFP_KERNEL);
if (nr_neigh->digipeat == NULL) {
kfree(nr_neigh);
return -ENOMEM;
}
}
spin_lock_bh(&nr_neigh_list_lock);
hlist_add_head(&nr_neigh->neigh_node, &nr_neigh_list);
/* refcount is initialized at 1 */
spin_unlock_bh(&nr_neigh_list_lock);
return 0;
}
/*
* "Delete" a neighbour. The neighbour is only removed if the number
* of nodes that may use it is zero.
*/
static int nr_del_neigh(ax25_address *callsign, struct net_device *dev, unsigned int quality)
{
struct nr_neigh *nr_neigh;
nr_neigh = nr_neigh_get_dev(callsign, dev);
if (nr_neigh == NULL) return -EINVAL;
nr_neigh->quality = quality;
nr_neigh->locked = 0;
if (nr_neigh->count == 0)
nr_remove_neigh(nr_neigh);
nr_neigh_put(nr_neigh);
return 0;
}
/*
* Decrement the obsolescence count by one. If a route is reduced to a
* count of zero, remove it. Also remove any unlocked neighbours with
* zero nodes routing via it.
*/
static int nr_dec_obs(void)
{
struct nr_neigh *nr_neigh;
struct nr_node *s;
struct hlist_node *nodet;
int i;
spin_lock_bh(&nr_node_list_lock);
nr_node_for_each_safe(s, nodet, &nr_node_list) {
nr_node_lock(s);
for (i = 0; i < s->count; i++) {
switch (s->routes[i].obs_count) {
case 0: /* A locked entry */
break;
case 1: /* From 1 -> 0 */
nr_neigh = s->routes[i].neighbour;
nr_neigh->count--;
nr_neigh_put(nr_neigh);
if (nr_neigh->count == 0 && !nr_neigh->locked)
nr_remove_neigh(nr_neigh);
s->count--;
switch (i) {
case 0:
s->routes[0] = s->routes[1];
fallthrough;
case 1:
s->routes[1] = s->routes[2];
break;
case 2:
break;
}
break;
default:
s->routes[i].obs_count--;
break;
}
}
if (s->count <= 0)
nr_remove_node_locked(s);
nr_node_unlock(s);
}
spin_unlock_bh(&nr_node_list_lock);
return 0;
}
/*
* A device has been removed. Remove its routes and neighbours.
*/
void nr_rt_device_down(struct net_device *dev)
{
struct nr_neigh *s;
struct hlist_node *nodet, *node2t;
struct nr_node *t;
int i;
spin_lock_bh(&nr_neigh_list_lock);
nr_neigh_for_each_safe(s, nodet, &nr_neigh_list) {
if (s->dev == dev) {
spin_lock_bh(&nr_node_list_lock);
nr_node_for_each_safe(t, node2t, &nr_node_list) {
nr_node_lock(t);
for (i = 0; i < t->count; i++) {
if (t->routes[i].neighbour == s) {
t->count--;
switch (i) {
case 0:
t->routes[0] = t->routes[1];
fallthrough;
case 1:
t->routes[1] = t->routes[2];
break;
case 2:
break;
}
}
}
if (t->count <= 0)
nr_remove_node_locked(t);
nr_node_unlock(t);
}
spin_unlock_bh(&nr_node_list_lock);
nr_remove_neigh_locked(s);
}
}
spin_unlock_bh(&nr_neigh_list_lock);
}
/*
* Check that the device given is a valid AX.25 interface that is "up".
* Or a valid ethernet interface with an AX.25 callsign binding.
*/
static struct net_device *nr_ax25_dev_get(char *devname)
{
struct net_device *dev;
if ((dev = dev_get_by_name(&init_net, devname)) == NULL)
return NULL;
if ((dev->flags & IFF_UP) && dev->type == ARPHRD_AX25)
return dev;
dev_put(dev);
return NULL;
}
/*
* Find the first active NET/ROM device, usually "nr0".
*/
struct net_device *nr_dev_first(void)
{
struct net_device *dev, *first = NULL;
rcu_read_lock();
for_each_netdev_rcu(&init_net, dev) {
if ((dev->flags & IFF_UP) && dev->type == ARPHRD_NETROM)
if (first == NULL || strncmp(dev->name, first->name, 3) < 0)
first = dev;
}
dev_hold(first);
rcu_read_unlock();
return first;
}
/*
* Find the NET/ROM device for the given callsign.
*/
struct net_device *nr_dev_get(ax25_address *addr)
{
struct net_device *dev;
rcu_read_lock();
for_each_netdev_rcu(&init_net, dev) {
if ((dev->flags & IFF_UP) && dev->type == ARPHRD_NETROM &&
ax25cmp(addr, (const ax25_address *)dev->dev_addr) == 0) {
dev_hold(dev);
goto out;
}
}
dev = NULL;
out:
rcu_read_unlock();
return dev;
}
static ax25_digi *nr_call_to_digi(ax25_digi *digi, int ndigis,
ax25_address *digipeaters)
{
int i;
if (ndigis == 0)
return NULL;
for (i = 0; i < ndigis; i++) {
digi->calls[i] = digipeaters[i];
digi->repeated[i] = 0;
}
digi->ndigi = ndigis;
digi->lastrepeat = -1;
return digi;
}
/*
* Handle the ioctls that control the routing functions.
*/
int nr_rt_ioctl(unsigned int cmd, void __user *arg)
{
struct nr_route_struct nr_route;
struct net_device *dev;
ax25_digi digi;
int ret;
switch (cmd) {
case SIOCADDRT:
if (copy_from_user(&nr_route, arg, sizeof(struct nr_route_struct)))
return -EFAULT;
if (nr_route.ndigis > AX25_MAX_DIGIS)
return -EINVAL;
if ((dev = nr_ax25_dev_get(nr_route.device)) == NULL)
return -EINVAL;
switch (nr_route.type) {
case NETROM_NODE:
if (strnlen(nr_route.mnemonic, 7) == 7) {
ret = -EINVAL;
break;
}
ret = nr_add_node(&nr_route.callsign,
nr_route.mnemonic,
&nr_route.neighbour,
nr_call_to_digi(&digi, nr_route.ndigis,
nr_route.digipeaters),
dev, nr_route.quality,
nr_route.obs_count);
break;
case NETROM_NEIGH:
ret = nr_add_neigh(&nr_route.callsign,
nr_call_to_digi(&digi, nr_route.ndigis,
nr_route.digipeaters),
dev, nr_route.quality);
break;
default:
ret = -EINVAL;
}
dev_put(dev);
return ret;
case SIOCDELRT:
if (copy_from_user(&nr_route, arg, sizeof(struct nr_route_struct)))
return -EFAULT;
if ((dev = nr_ax25_dev_get(nr_route.device)) == NULL)
return -EINVAL;
switch (nr_route.type) {
case NETROM_NODE:
ret = nr_del_node(&nr_route.callsign,
&nr_route.neighbour, dev);
break;
case NETROM_NEIGH:
ret = nr_del_neigh(&nr_route.callsign,
dev, nr_route.quality);
break;
default:
ret = -EINVAL;
}
dev_put(dev);
return ret;
case SIOCNRDECOBS:
return nr_dec_obs();
default:
return -EINVAL;
}
return 0;
}
/*
* A level 2 link has timed out, therefore it appears to be a poor link,
* then don't use that neighbour until it is reset.
*/
void nr_link_failed(ax25_cb *ax25, int reason)
{
struct nr_neigh *s, *nr_neigh = NULL;
struct nr_node *nr_node = NULL;
spin_lock_bh(&nr_neigh_list_lock);
nr_neigh_for_each(s, &nr_neigh_list) {
if (s->ax25 == ax25) {
nr_neigh_hold(s);
nr_neigh = s;
break;
}
}
spin_unlock_bh(&nr_neigh_list_lock);
if (nr_neigh == NULL)
return;
nr_neigh->ax25 = NULL;
ax25_cb_put(ax25);
if (++nr_neigh->failed < sysctl_netrom_link_fails_count) {
nr_neigh_put(nr_neigh);
return;
}
spin_lock_bh(&nr_node_list_lock);
nr_node_for_each(nr_node, &nr_node_list) {
nr_node_lock(nr_node);
if (nr_node->which < nr_node->count &&
nr_node->routes[nr_node->which].neighbour == nr_neigh)
nr_node->which++;
nr_node_unlock(nr_node);
}
spin_unlock_bh(&nr_node_list_lock);
nr_neigh_put(nr_neigh);
}
/*
* Route a frame to an appropriate AX.25 connection. A NULL ax25_cb
* indicates an internally generated frame.
*/
int nr_route_frame(struct sk_buff *skb, ax25_cb *ax25)
{
ax25_address *nr_src, *nr_dest;
struct nr_neigh *nr_neigh;
struct nr_node *nr_node;
struct net_device *dev;
unsigned char *dptr;
ax25_cb *ax25s;
int ret;
struct sk_buff *skbn;
nr_src = (ax25_address *)(skb->data + 0);
nr_dest = (ax25_address *)(skb->data + 7);
if (ax25 != NULL) {
ret = nr_add_node(nr_src, "", &ax25->dest_addr, ax25->digipeat,
ax25->ax25_dev->dev, 0,
sysctl_netrom_obsolescence_count_initialiser);
if (ret)
return ret;
}
if ((dev = nr_dev_get(nr_dest)) != NULL) { /* Its for me */
if (ax25 == NULL) /* Its from me */
ret = nr_loopback_queue(skb);
else
ret = nr_rx_frame(skb, dev);
dev_put(dev);
return ret;
}
if (!sysctl_netrom_routing_control && ax25 != NULL)
return 0;
/* Its Time-To-Live has expired */
if (skb->data[14] == 1) {
return 0;
}
nr_node = nr_node_get(nr_dest);
if (nr_node == NULL)
return 0;
nr_node_lock(nr_node);
if (nr_node->which >= nr_node->count) {
nr_node_unlock(nr_node);
nr_node_put(nr_node);
return 0;
}
nr_neigh = nr_node->routes[nr_node->which].neighbour;
if ((dev = nr_dev_first()) == NULL) {
nr_node_unlock(nr_node);
nr_node_put(nr_node);
return 0;
}
/* We are going to change the netrom headers so we should get our
own skb, we also did not know until now how much header space
we had to reserve... - RXQ */
if ((skbn=skb_copy_expand(skb, dev->hard_header_len, 0, GFP_ATOMIC)) == NULL) {
nr_node_unlock(nr_node);
nr_node_put(nr_node);
dev_put(dev);
return 0;
}
kfree_skb(skb);
skb=skbn;
skb->data[14]--;
dptr = skb_push(skb, 1);
*dptr = AX25_P_NETROM;
ax25s = nr_neigh->ax25;
nr_neigh->ax25 = ax25_send_frame(skb, 256,
(const ax25_address *)dev->dev_addr,
&nr_neigh->callsign,
nr_neigh->digipeat, nr_neigh->dev);
if (ax25s)
ax25_cb_put(ax25s);
dev_put(dev);
ret = (nr_neigh->ax25 != NULL);
nr_node_unlock(nr_node);
nr_node_put(nr_node);
return ret;
}
#ifdef CONFIG_PROC_FS
static void *nr_node_start(struct seq_file *seq, loff_t *pos)
__acquires(&nr_node_list_lock)
{
spin_lock_bh(&nr_node_list_lock);
return seq_hlist_start_head(&nr_node_list, *pos);
}
static void *nr_node_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_hlist_next(v, &nr_node_list, pos);
}
static void nr_node_stop(struct seq_file *seq, void *v)
__releases(&nr_node_list_lock)
{
spin_unlock_bh(&nr_node_list_lock);
}
static int nr_node_show(struct seq_file *seq, void *v)
{
char buf[11];
int i;
if (v == SEQ_START_TOKEN)
seq_puts(seq,
"callsign mnemonic w n qual obs neigh qual obs neigh qual obs neigh\n");
else {
struct nr_node *nr_node = hlist_entry(v, struct nr_node,
node_node);
nr_node_lock(nr_node);
seq_printf(seq, "%-9s %-7s %d %d",
ax2asc(buf, &nr_node->callsign),
(nr_node->mnemonic[0] == '\0') ? "*" : nr_node->mnemonic,
nr_node->which + 1,
nr_node->count);
for (i = 0; i < nr_node->count; i++) {
seq_printf(seq, " %3d %d %05d",
nr_node->routes[i].quality,
nr_node->routes[i].obs_count,
nr_node->routes[i].neighbour->number);
}
nr_node_unlock(nr_node);
seq_puts(seq, "\n");
}
return 0;
}
const struct seq_operations nr_node_seqops = {
.start = nr_node_start,
.next = nr_node_next,
.stop = nr_node_stop,
.show = nr_node_show,
};
static void *nr_neigh_start(struct seq_file *seq, loff_t *pos)
__acquires(&nr_neigh_list_lock)
{
spin_lock_bh(&nr_neigh_list_lock);
return seq_hlist_start_head(&nr_neigh_list, *pos);
}
static void *nr_neigh_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_hlist_next(v, &nr_neigh_list, pos);
}
static void nr_neigh_stop(struct seq_file *seq, void *v)
__releases(&nr_neigh_list_lock)
{
spin_unlock_bh(&nr_neigh_list_lock);
}
static int nr_neigh_show(struct seq_file *seq, void *v)
{
char buf[11];
int i;
if (v == SEQ_START_TOKEN)
seq_puts(seq, "addr callsign dev qual lock count failed digipeaters\n");
else {
struct nr_neigh *nr_neigh;
nr_neigh = hlist_entry(v, struct nr_neigh, neigh_node);
seq_printf(seq, "%05d %-9s %-4s %3d %d %3d %3d",
nr_neigh->number,
ax2asc(buf, &nr_neigh->callsign),
nr_neigh->dev ? nr_neigh->dev->name : "???",
nr_neigh->quality,
nr_neigh->locked,
nr_neigh->count,
nr_neigh->failed);
if (nr_neigh->digipeat != NULL) {
for (i = 0; i < nr_neigh->digipeat->ndigi; i++)
seq_printf(seq, " %s",
ax2asc(buf, &nr_neigh->digipeat->calls[i]));
}
seq_puts(seq, "\n");
}
return 0;
}
const struct seq_operations nr_neigh_seqops = {
.start = nr_neigh_start,
.next = nr_neigh_next,
.stop = nr_neigh_stop,
.show = nr_neigh_show,
};
#endif
/*
* Free all memory associated with the nodes and routes lists.
*/
void nr_rt_free(void)
{
struct nr_neigh *s = NULL;
struct nr_node *t = NULL;
struct hlist_node *nodet;
spin_lock_bh(&nr_neigh_list_lock);
spin_lock_bh(&nr_node_list_lock);
nr_node_for_each_safe(t, nodet, &nr_node_list) {
nr_node_lock(t);
nr_remove_node_locked(t);
nr_node_unlock(t);
}
nr_neigh_for_each_safe(s, nodet, &nr_neigh_list) {
while(s->count) {
s->count--;
nr_neigh_put(s);
}
nr_remove_neigh_locked(s);
}
spin_unlock_bh(&nr_node_list_lock);
spin_unlock_bh(&nr_neigh_list_lock);
}
| linux-master | net/netrom/nr_route.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Copyright Jonathan Naylor G4KLX ([email protected])
* Copyright Darryl Miles G7LED ([email protected])
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/slab.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <linux/uaccess.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <net/netrom.h>
static int nr_queue_rx_frame(struct sock *sk, struct sk_buff *skb, int more)
{
struct sk_buff *skbo, *skbn = skb;
struct nr_sock *nr = nr_sk(sk);
skb_pull(skb, NR_NETWORK_LEN + NR_TRANSPORT_LEN);
nr_start_idletimer(sk);
if (more) {
nr->fraglen += skb->len;
skb_queue_tail(&nr->frag_queue, skb);
return 0;
}
if (!more && nr->fraglen > 0) { /* End of fragment */
nr->fraglen += skb->len;
skb_queue_tail(&nr->frag_queue, skb);
if ((skbn = alloc_skb(nr->fraglen, GFP_ATOMIC)) == NULL)
return 1;
skb_reset_transport_header(skbn);
while ((skbo = skb_dequeue(&nr->frag_queue)) != NULL) {
skb_copy_from_linear_data(skbo,
skb_put(skbn, skbo->len),
skbo->len);
kfree_skb(skbo);
}
nr->fraglen = 0;
}
return sock_queue_rcv_skb(sk, skbn);
}
/*
* State machine for state 1, Awaiting Connection State.
* The handling of the timer(s) is in file nr_timer.c.
* Handling of state 0 and connection release is in netrom.c.
*/
static int nr_state1_machine(struct sock *sk, struct sk_buff *skb,
int frametype)
{
switch (frametype) {
case NR_CONNACK: {
struct nr_sock *nr = nr_sk(sk);
nr_stop_t1timer(sk);
nr_start_idletimer(sk);
nr->your_index = skb->data[17];
nr->your_id = skb->data[18];
nr->vs = 0;
nr->va = 0;
nr->vr = 0;
nr->vl = 0;
nr->state = NR_STATE_3;
nr->n2count = 0;
nr->window = skb->data[20];
sk->sk_state = TCP_ESTABLISHED;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_state_change(sk);
break;
}
case NR_CONNACK | NR_CHOKE_FLAG:
nr_disconnect(sk, ECONNREFUSED);
break;
case NR_RESET:
if (sysctl_netrom_reset_circuit)
nr_disconnect(sk, ECONNRESET);
break;
default:
break;
}
return 0;
}
/*
* State machine for state 2, Awaiting Release State.
* The handling of the timer(s) is in file nr_timer.c
* Handling of state 0 and connection release is in netrom.c.
*/
static int nr_state2_machine(struct sock *sk, struct sk_buff *skb,
int frametype)
{
switch (frametype) {
case NR_CONNACK | NR_CHOKE_FLAG:
nr_disconnect(sk, ECONNRESET);
break;
case NR_DISCREQ:
nr_write_internal(sk, NR_DISCACK);
fallthrough;
case NR_DISCACK:
nr_disconnect(sk, 0);
break;
case NR_RESET:
if (sysctl_netrom_reset_circuit)
nr_disconnect(sk, ECONNRESET);
break;
default:
break;
}
return 0;
}
/*
* State machine for state 3, Connected State.
* The handling of the timer(s) is in file nr_timer.c
* Handling of state 0 and connection release is in netrom.c.
*/
static int nr_state3_machine(struct sock *sk, struct sk_buff *skb, int frametype)
{
struct nr_sock *nrom = nr_sk(sk);
struct sk_buff_head temp_queue;
struct sk_buff *skbn;
unsigned short save_vr;
unsigned short nr, ns;
int queued = 0;
nr = skb->data[18];
switch (frametype) {
case NR_CONNREQ:
nr_write_internal(sk, NR_CONNACK);
break;
case NR_DISCREQ:
nr_write_internal(sk, NR_DISCACK);
nr_disconnect(sk, 0);
break;
case NR_CONNACK | NR_CHOKE_FLAG:
case NR_DISCACK:
nr_disconnect(sk, ECONNRESET);
break;
case NR_INFOACK:
case NR_INFOACK | NR_CHOKE_FLAG:
case NR_INFOACK | NR_NAK_FLAG:
case NR_INFOACK | NR_NAK_FLAG | NR_CHOKE_FLAG:
if (frametype & NR_CHOKE_FLAG) {
nrom->condition |= NR_COND_PEER_RX_BUSY;
nr_start_t4timer(sk);
} else {
nrom->condition &= ~NR_COND_PEER_RX_BUSY;
nr_stop_t4timer(sk);
}
if (!nr_validate_nr(sk, nr)) {
break;
}
if (frametype & NR_NAK_FLAG) {
nr_frames_acked(sk, nr);
nr_send_nak_frame(sk);
} else {
if (nrom->condition & NR_COND_PEER_RX_BUSY) {
nr_frames_acked(sk, nr);
} else {
nr_check_iframes_acked(sk, nr);
}
}
break;
case NR_INFO:
case NR_INFO | NR_NAK_FLAG:
case NR_INFO | NR_CHOKE_FLAG:
case NR_INFO | NR_MORE_FLAG:
case NR_INFO | NR_NAK_FLAG | NR_CHOKE_FLAG:
case NR_INFO | NR_CHOKE_FLAG | NR_MORE_FLAG:
case NR_INFO | NR_NAK_FLAG | NR_MORE_FLAG:
case NR_INFO | NR_NAK_FLAG | NR_CHOKE_FLAG | NR_MORE_FLAG:
if (frametype & NR_CHOKE_FLAG) {
nrom->condition |= NR_COND_PEER_RX_BUSY;
nr_start_t4timer(sk);
} else {
nrom->condition &= ~NR_COND_PEER_RX_BUSY;
nr_stop_t4timer(sk);
}
if (nr_validate_nr(sk, nr)) {
if (frametype & NR_NAK_FLAG) {
nr_frames_acked(sk, nr);
nr_send_nak_frame(sk);
} else {
if (nrom->condition & NR_COND_PEER_RX_BUSY) {
nr_frames_acked(sk, nr);
} else {
nr_check_iframes_acked(sk, nr);
}
}
}
queued = 1;
skb_queue_head(&nrom->reseq_queue, skb);
if (nrom->condition & NR_COND_OWN_RX_BUSY)
break;
skb_queue_head_init(&temp_queue);
do {
save_vr = nrom->vr;
while ((skbn = skb_dequeue(&nrom->reseq_queue)) != NULL) {
ns = skbn->data[17];
if (ns == nrom->vr) {
if (nr_queue_rx_frame(sk, skbn, frametype & NR_MORE_FLAG) == 0) {
nrom->vr = (nrom->vr + 1) % NR_MODULUS;
} else {
nrom->condition |= NR_COND_OWN_RX_BUSY;
skb_queue_tail(&temp_queue, skbn);
}
} else if (nr_in_rx_window(sk, ns)) {
skb_queue_tail(&temp_queue, skbn);
} else {
kfree_skb(skbn);
}
}
while ((skbn = skb_dequeue(&temp_queue)) != NULL) {
skb_queue_tail(&nrom->reseq_queue, skbn);
}
} while (save_vr != nrom->vr);
/*
* Window is full, ack it immediately.
*/
if (((nrom->vl + nrom->window) % NR_MODULUS) == nrom->vr) {
nr_enquiry_response(sk);
} else {
if (!(nrom->condition & NR_COND_ACK_PENDING)) {
nrom->condition |= NR_COND_ACK_PENDING;
nr_start_t2timer(sk);
}
}
break;
case NR_RESET:
if (sysctl_netrom_reset_circuit)
nr_disconnect(sk, ECONNRESET);
break;
default:
break;
}
return queued;
}
/* Higher level upcall for a LAPB frame - called with sk locked */
int nr_process_rx_frame(struct sock *sk, struct sk_buff *skb)
{
struct nr_sock *nr = nr_sk(sk);
int queued = 0, frametype;
if (nr->state == NR_STATE_0)
return 0;
frametype = skb->data[19];
switch (nr->state) {
case NR_STATE_1:
queued = nr_state1_machine(sk, skb, frametype);
break;
case NR_STATE_2:
queued = nr_state2_machine(sk, skb, frametype);
break;
case NR_STATE_3:
queued = nr_state3_machine(sk, skb, frametype);
break;
}
nr_kick(sk);
return queued;
}
| linux-master | net/netrom/nr_in.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Copyright Jonathan Naylor G4KLX ([email protected])
* Copyright Darryl Miles G7LED ([email protected])
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/slab.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <linux/uaccess.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <net/netrom.h>
/*
* This is where all NET/ROM frames pass, except for IP-over-NET/ROM which
* cannot be fragmented in this manner.
*/
void nr_output(struct sock *sk, struct sk_buff *skb)
{
struct sk_buff *skbn;
unsigned char transport[NR_TRANSPORT_LEN];
int err, frontlen, len;
if (skb->len - NR_TRANSPORT_LEN > NR_MAX_PACKET_SIZE) {
/* Save a copy of the Transport Header */
skb_copy_from_linear_data(skb, transport, NR_TRANSPORT_LEN);
skb_pull(skb, NR_TRANSPORT_LEN);
frontlen = skb_headroom(skb);
while (skb->len > 0) {
if ((skbn = sock_alloc_send_skb(sk, frontlen + NR_MAX_PACKET_SIZE, 0, &err)) == NULL)
return;
skb_reserve(skbn, frontlen);
len = (NR_MAX_PACKET_SIZE > skb->len) ? skb->len : NR_MAX_PACKET_SIZE;
/* Copy the user data */
skb_copy_from_linear_data(skb, skb_put(skbn, len), len);
skb_pull(skb, len);
/* Duplicate the Transport Header */
skb_push(skbn, NR_TRANSPORT_LEN);
skb_copy_to_linear_data(skbn, transport,
NR_TRANSPORT_LEN);
if (skb->len > 0)
skbn->data[4] |= NR_MORE_FLAG;
skb_queue_tail(&sk->sk_write_queue, skbn); /* Throw it on the queue */
}
kfree_skb(skb);
} else {
skb_queue_tail(&sk->sk_write_queue, skb); /* Throw it on the queue */
}
nr_kick(sk);
}
/*
* This procedure is passed a buffer descriptor for an iframe. It builds
* the rest of the control part of the frame and then writes it out.
*/
static void nr_send_iframe(struct sock *sk, struct sk_buff *skb)
{
struct nr_sock *nr = nr_sk(sk);
if (skb == NULL)
return;
skb->data[2] = nr->vs;
skb->data[3] = nr->vr;
if (nr->condition & NR_COND_OWN_RX_BUSY)
skb->data[4] |= NR_CHOKE_FLAG;
nr_start_idletimer(sk);
nr_transmit_buffer(sk, skb);
}
void nr_send_nak_frame(struct sock *sk)
{
struct sk_buff *skb, *skbn;
struct nr_sock *nr = nr_sk(sk);
if ((skb = skb_peek(&nr->ack_queue)) == NULL)
return;
if ((skbn = skb_clone(skb, GFP_ATOMIC)) == NULL)
return;
skbn->data[2] = nr->va;
skbn->data[3] = nr->vr;
if (nr->condition & NR_COND_OWN_RX_BUSY)
skbn->data[4] |= NR_CHOKE_FLAG;
nr_transmit_buffer(sk, skbn);
nr->condition &= ~NR_COND_ACK_PENDING;
nr->vl = nr->vr;
nr_stop_t1timer(sk);
}
void nr_kick(struct sock *sk)
{
struct nr_sock *nr = nr_sk(sk);
struct sk_buff *skb, *skbn;
unsigned short start, end;
if (nr->state != NR_STATE_3)
return;
if (nr->condition & NR_COND_PEER_RX_BUSY)
return;
if (!skb_peek(&sk->sk_write_queue))
return;
start = (skb_peek(&nr->ack_queue) == NULL) ? nr->va : nr->vs;
end = (nr->va + nr->window) % NR_MODULUS;
if (start == end)
return;
nr->vs = start;
/*
* Transmit data until either we're out of data to send or
* the window is full.
*/
/*
* Dequeue the frame and copy it.
*/
skb = skb_dequeue(&sk->sk_write_queue);
do {
if ((skbn = skb_clone(skb, GFP_ATOMIC)) == NULL) {
skb_queue_head(&sk->sk_write_queue, skb);
break;
}
skb_set_owner_w(skbn, sk);
/*
* Transmit the frame copy.
*/
nr_send_iframe(sk, skbn);
nr->vs = (nr->vs + 1) % NR_MODULUS;
/*
* Requeue the original data frame.
*/
skb_queue_tail(&nr->ack_queue, skb);
} while (nr->vs != end &&
(skb = skb_dequeue(&sk->sk_write_queue)) != NULL);
nr->vl = nr->vr;
nr->condition &= ~NR_COND_ACK_PENDING;
if (!nr_t1timer_running(sk))
nr_start_t1timer(sk);
}
void nr_transmit_buffer(struct sock *sk, struct sk_buff *skb)
{
struct nr_sock *nr = nr_sk(sk);
unsigned char *dptr;
/*
* Add the protocol byte and network header.
*/
dptr = skb_push(skb, NR_NETWORK_LEN);
memcpy(dptr, &nr->source_addr, AX25_ADDR_LEN);
dptr[6] &= ~AX25_CBIT;
dptr[6] &= ~AX25_EBIT;
dptr[6] |= AX25_SSSID_SPARE;
dptr += AX25_ADDR_LEN;
memcpy(dptr, &nr->dest_addr, AX25_ADDR_LEN);
dptr[6] &= ~AX25_CBIT;
dptr[6] |= AX25_EBIT;
dptr[6] |= AX25_SSSID_SPARE;
dptr += AX25_ADDR_LEN;
*dptr++ = sysctl_netrom_network_ttl_initialiser;
if (!nr_route_frame(skb, NULL)) {
kfree_skb(skb);
nr_disconnect(sk, ENETUNREACH);
}
}
/*
* The following routines are taken from page 170 of the 7th ARRL Computer
* Networking Conference paper, as is the whole state machine.
*/
void nr_establish_data_link(struct sock *sk)
{
struct nr_sock *nr = nr_sk(sk);
nr->condition = 0x00;
nr->n2count = 0;
nr_write_internal(sk, NR_CONNREQ);
nr_stop_t2timer(sk);
nr_stop_t4timer(sk);
nr_stop_idletimer(sk);
nr_start_t1timer(sk);
}
/*
* Never send a NAK when we are CHOKEd.
*/
void nr_enquiry_response(struct sock *sk)
{
struct nr_sock *nr = nr_sk(sk);
int frametype = NR_INFOACK;
if (nr->condition & NR_COND_OWN_RX_BUSY) {
frametype |= NR_CHOKE_FLAG;
} else {
if (skb_peek(&nr->reseq_queue) != NULL)
frametype |= NR_NAK_FLAG;
}
nr_write_internal(sk, frametype);
nr->vl = nr->vr;
nr->condition &= ~NR_COND_ACK_PENDING;
}
void nr_check_iframes_acked(struct sock *sk, unsigned short nr)
{
struct nr_sock *nrom = nr_sk(sk);
if (nrom->vs == nr) {
nr_frames_acked(sk, nr);
nr_stop_t1timer(sk);
nrom->n2count = 0;
} else {
if (nrom->va != nr) {
nr_frames_acked(sk, nr);
nr_start_t1timer(sk);
}
}
}
| linux-master | net/netrom/nr_out.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Copyright Tomi Manninen OH2BNS ([email protected])
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/socket.h>
#include <linux/timer.h>
#include <net/ax25.h>
#include <linux/skbuff.h>
#include <net/netrom.h>
#include <linux/init.h>
static void nr_loopback_timer(struct timer_list *);
static struct sk_buff_head loopback_queue;
static DEFINE_TIMER(loopback_timer, nr_loopback_timer);
void __init nr_loopback_init(void)
{
skb_queue_head_init(&loopback_queue);
}
static inline int nr_loopback_running(void)
{
return timer_pending(&loopback_timer);
}
int nr_loopback_queue(struct sk_buff *skb)
{
struct sk_buff *skbn;
if ((skbn = alloc_skb(skb->len, GFP_ATOMIC)) != NULL) {
skb_copy_from_linear_data(skb, skb_put(skbn, skb->len), skb->len);
skb_reset_transport_header(skbn);
skb_queue_tail(&loopback_queue, skbn);
if (!nr_loopback_running())
mod_timer(&loopback_timer, jiffies + 10);
}
kfree_skb(skb);
return 1;
}
static void nr_loopback_timer(struct timer_list *unused)
{
struct sk_buff *skb;
ax25_address *nr_dest;
struct net_device *dev;
if ((skb = skb_dequeue(&loopback_queue)) != NULL) {
nr_dest = (ax25_address *)(skb->data + 7);
dev = nr_dev_get(nr_dest);
if (dev == NULL || nr_rx_frame(skb, dev) == 0)
kfree_skb(skb);
dev_put(dev);
if (!skb_queue_empty(&loopback_queue) && !nr_loopback_running())
mod_timer(&loopback_timer, jiffies + 10);
}
}
void nr_loopback_clear(void)
{
del_timer_sync(&loopback_timer);
skb_queue_purge(&loopback_queue);
}
| linux-master | net/netrom/nr_loopback.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Copyright Jonathan Naylor G4KLX ([email protected])
*/
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/sysctl.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/errno.h>
#include <linux/fcntl.h>
#include <linux/in.h>
#include <linux/if_ether.h> /* For the statistics structure. */
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <asm/io.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <net/ip.h>
#include <net/arp.h>
#include <net/ax25.h>
#include <net/netrom.h>
/*
* Only allow IP over NET/ROM frames through if the netrom device is up.
*/
int nr_rx_ip(struct sk_buff *skb, struct net_device *dev)
{
struct net_device_stats *stats = &dev->stats;
if (!netif_running(dev)) {
stats->rx_dropped++;
return 0;
}
stats->rx_packets++;
stats->rx_bytes += skb->len;
skb->protocol = htons(ETH_P_IP);
/* Spoof incoming device */
skb->dev = dev;
skb->mac_header = skb->network_header;
skb_reset_network_header(skb);
skb->pkt_type = PACKET_HOST;
netif_rx(skb);
return 1;
}
static int nr_header(struct sk_buff *skb, struct net_device *dev,
unsigned short type,
const void *daddr, const void *saddr, unsigned int len)
{
unsigned char *buff = skb_push(skb, NR_NETWORK_LEN + NR_TRANSPORT_LEN);
memcpy(buff, (saddr != NULL) ? saddr : dev->dev_addr, dev->addr_len);
buff[6] &= ~AX25_CBIT;
buff[6] &= ~AX25_EBIT;
buff[6] |= AX25_SSSID_SPARE;
buff += AX25_ADDR_LEN;
if (daddr != NULL)
memcpy(buff, daddr, dev->addr_len);
buff[6] &= ~AX25_CBIT;
buff[6] |= AX25_EBIT;
buff[6] |= AX25_SSSID_SPARE;
buff += AX25_ADDR_LEN;
*buff++ = sysctl_netrom_network_ttl_initialiser;
*buff++ = NR_PROTO_IP;
*buff++ = NR_PROTO_IP;
*buff++ = 0;
*buff++ = 0;
*buff++ = NR_PROTOEXT;
if (daddr != NULL)
return 37;
return -37;
}
static int __must_check nr_set_mac_address(struct net_device *dev, void *addr)
{
struct sockaddr *sa = addr;
int err;
if (!memcmp(dev->dev_addr, sa->sa_data, dev->addr_len))
return 0;
if (dev->flags & IFF_UP) {
err = ax25_listen_register((ax25_address *)sa->sa_data, NULL);
if (err)
return err;
ax25_listen_release((const ax25_address *)dev->dev_addr, NULL);
}
dev_addr_set(dev, sa->sa_data);
return 0;
}
static int nr_open(struct net_device *dev)
{
int err;
err = ax25_listen_register((const ax25_address *)dev->dev_addr, NULL);
if (err)
return err;
netif_start_queue(dev);
return 0;
}
static int nr_close(struct net_device *dev)
{
ax25_listen_release((const ax25_address *)dev->dev_addr, NULL);
netif_stop_queue(dev);
return 0;
}
static netdev_tx_t nr_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct net_device_stats *stats = &dev->stats;
unsigned int len = skb->len;
if (!nr_route_frame(skb, NULL)) {
kfree_skb(skb);
stats->tx_errors++;
return NETDEV_TX_OK;
}
stats->tx_packets++;
stats->tx_bytes += len;
return NETDEV_TX_OK;
}
static const struct header_ops nr_header_ops = {
.create = nr_header,
};
static const struct net_device_ops nr_netdev_ops = {
.ndo_open = nr_open,
.ndo_stop = nr_close,
.ndo_start_xmit = nr_xmit,
.ndo_set_mac_address = nr_set_mac_address,
};
void nr_setup(struct net_device *dev)
{
dev->mtu = NR_MAX_PACKET_SIZE;
dev->netdev_ops = &nr_netdev_ops;
dev->header_ops = &nr_header_ops;
dev->hard_header_len = NR_NETWORK_LEN + NR_TRANSPORT_LEN;
dev->addr_len = AX25_ADDR_LEN;
dev->type = ARPHRD_NETROM;
/* New-style flags. */
dev->flags = IFF_NOARP;
}
| linux-master | net/netrom/nr_dev.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Copyright (C) 1996 Mike Shaver ([email protected])
*/
#include <linux/mm.h>
#include <linux/sysctl.h>
#include <linux/init.h>
#include <net/ax25.h>
#include <net/netrom.h>
/*
* Values taken from NET/ROM documentation.
*/
static int min_quality[] = {0}, max_quality[] = {255};
static int min_obs[] = {0}, max_obs[] = {255};
static int min_ttl[] = {0}, max_ttl[] = {255};
static int min_t1[] = {5 * HZ};
static int max_t1[] = {600 * HZ};
static int min_n2[] = {2}, max_n2[] = {127};
static int min_t2[] = {1 * HZ};
static int max_t2[] = {60 * HZ};
static int min_t4[] = {1 * HZ};
static int max_t4[] = {1000 * HZ};
static int min_window[] = {1}, max_window[] = {127};
static int min_idle[] = {0 * HZ};
static int max_idle[] = {65535 * HZ};
static int min_route[] = {0}, max_route[] = {1};
static int min_fails[] = {1}, max_fails[] = {10};
static int min_reset[] = {0}, max_reset[] = {1};
static struct ctl_table_header *nr_table_header;
static struct ctl_table nr_table[] = {
{
.procname = "default_path_quality",
.data = &sysctl_netrom_default_path_quality,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_quality,
.extra2 = &max_quality
},
{
.procname = "obsolescence_count_initialiser",
.data = &sysctl_netrom_obsolescence_count_initialiser,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_obs,
.extra2 = &max_obs
},
{
.procname = "network_ttl_initialiser",
.data = &sysctl_netrom_network_ttl_initialiser,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_ttl,
.extra2 = &max_ttl
},
{
.procname = "transport_timeout",
.data = &sysctl_netrom_transport_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_t1,
.extra2 = &max_t1
},
{
.procname = "transport_maximum_tries",
.data = &sysctl_netrom_transport_maximum_tries,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_n2,
.extra2 = &max_n2
},
{
.procname = "transport_acknowledge_delay",
.data = &sysctl_netrom_transport_acknowledge_delay,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_t2,
.extra2 = &max_t2
},
{
.procname = "transport_busy_delay",
.data = &sysctl_netrom_transport_busy_delay,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_t4,
.extra2 = &max_t4
},
{
.procname = "transport_requested_window_size",
.data = &sysctl_netrom_transport_requested_window_size,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_window,
.extra2 = &max_window
},
{
.procname = "transport_no_activity_timeout",
.data = &sysctl_netrom_transport_no_activity_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_idle,
.extra2 = &max_idle
},
{
.procname = "routing_control",
.data = &sysctl_netrom_routing_control,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_route,
.extra2 = &max_route
},
{
.procname = "link_fails_count",
.data = &sysctl_netrom_link_fails_count,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_fails,
.extra2 = &max_fails
},
{
.procname = "reset",
.data = &sysctl_netrom_reset_circuit,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_reset,
.extra2 = &max_reset
},
{ }
};
int __init nr_register_sysctl(void)
{
nr_table_header = register_net_sysctl(&init_net, "net/netrom", nr_table);
if (!nr_table_header)
return -ENOMEM;
return 0;
}
void nr_unregister_sysctl(void)
{
unregister_net_sysctl_table(nr_table_header);
}
| linux-master | net/netrom/sysctl_net_netrom.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Copyright Jonathan Naylor G4KLX ([email protected])
* Copyright Alan Cox GW4PTS ([email protected])
* Copyright Darryl Miles G7LED ([email protected])
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/sched/signal.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/stat.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <linux/uaccess.h>
#include <linux/fcntl.h>
#include <linux/termios.h> /* For TIOCINQ/OUTQ */
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/notifier.h>
#include <net/netrom.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <net/ip.h>
#include <net/tcp_states.h>
#include <net/arp.h>
#include <linux/init.h>
static int nr_ndevs = 4;
int sysctl_netrom_default_path_quality = NR_DEFAULT_QUAL;
int sysctl_netrom_obsolescence_count_initialiser = NR_DEFAULT_OBS;
int sysctl_netrom_network_ttl_initialiser = NR_DEFAULT_TTL;
int sysctl_netrom_transport_timeout = NR_DEFAULT_T1;
int sysctl_netrom_transport_maximum_tries = NR_DEFAULT_N2;
int sysctl_netrom_transport_acknowledge_delay = NR_DEFAULT_T2;
int sysctl_netrom_transport_busy_delay = NR_DEFAULT_T4;
int sysctl_netrom_transport_requested_window_size = NR_DEFAULT_WINDOW;
int sysctl_netrom_transport_no_activity_timeout = NR_DEFAULT_IDLE;
int sysctl_netrom_routing_control = NR_DEFAULT_ROUTING;
int sysctl_netrom_link_fails_count = NR_DEFAULT_FAILS;
int sysctl_netrom_reset_circuit = NR_DEFAULT_RESET;
static unsigned short circuit = 0x101;
static HLIST_HEAD(nr_list);
static DEFINE_SPINLOCK(nr_list_lock);
static const struct proto_ops nr_proto_ops;
/*
* NETROM network devices are virtual network devices encapsulating NETROM
* frames into AX.25 which will be sent through an AX.25 device, so form a
* special "super class" of normal net devices; split their locks off into a
* separate class since they always nest.
*/
static struct lock_class_key nr_netdev_xmit_lock_key;
static struct lock_class_key nr_netdev_addr_lock_key;
static void nr_set_lockdep_one(struct net_device *dev,
struct netdev_queue *txq,
void *_unused)
{
lockdep_set_class(&txq->_xmit_lock, &nr_netdev_xmit_lock_key);
}
static void nr_set_lockdep_key(struct net_device *dev)
{
lockdep_set_class(&dev->addr_list_lock, &nr_netdev_addr_lock_key);
netdev_for_each_tx_queue(dev, nr_set_lockdep_one, NULL);
}
/*
* Socket removal during an interrupt is now safe.
*/
static void nr_remove_socket(struct sock *sk)
{
spin_lock_bh(&nr_list_lock);
sk_del_node_init(sk);
spin_unlock_bh(&nr_list_lock);
}
/*
* Kill all bound sockets on a dropped device.
*/
static void nr_kill_by_device(struct net_device *dev)
{
struct sock *s;
spin_lock_bh(&nr_list_lock);
sk_for_each(s, &nr_list)
if (nr_sk(s)->device == dev)
nr_disconnect(s, ENETUNREACH);
spin_unlock_bh(&nr_list_lock);
}
/*
* Handle device status changes.
*/
static int nr_device_event(struct notifier_block *this, unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
if (event != NETDEV_DOWN)
return NOTIFY_DONE;
nr_kill_by_device(dev);
nr_rt_device_down(dev);
return NOTIFY_DONE;
}
/*
* Add a socket to the bound sockets list.
*/
static void nr_insert_socket(struct sock *sk)
{
spin_lock_bh(&nr_list_lock);
sk_add_node(sk, &nr_list);
spin_unlock_bh(&nr_list_lock);
}
/*
* Find a socket that wants to accept the Connect Request we just
* received.
*/
static struct sock *nr_find_listener(ax25_address *addr)
{
struct sock *s;
spin_lock_bh(&nr_list_lock);
sk_for_each(s, &nr_list)
if (!ax25cmp(&nr_sk(s)->source_addr, addr) &&
s->sk_state == TCP_LISTEN) {
sock_hold(s);
goto found;
}
s = NULL;
found:
spin_unlock_bh(&nr_list_lock);
return s;
}
/*
* Find a connected NET/ROM socket given my circuit IDs.
*/
static struct sock *nr_find_socket(unsigned char index, unsigned char id)
{
struct sock *s;
spin_lock_bh(&nr_list_lock);
sk_for_each(s, &nr_list) {
struct nr_sock *nr = nr_sk(s);
if (nr->my_index == index && nr->my_id == id) {
sock_hold(s);
goto found;
}
}
s = NULL;
found:
spin_unlock_bh(&nr_list_lock);
return s;
}
/*
* Find a connected NET/ROM socket given their circuit IDs.
*/
static struct sock *nr_find_peer(unsigned char index, unsigned char id,
ax25_address *dest)
{
struct sock *s;
spin_lock_bh(&nr_list_lock);
sk_for_each(s, &nr_list) {
struct nr_sock *nr = nr_sk(s);
if (nr->your_index == index && nr->your_id == id &&
!ax25cmp(&nr->dest_addr, dest)) {
sock_hold(s);
goto found;
}
}
s = NULL;
found:
spin_unlock_bh(&nr_list_lock);
return s;
}
/*
* Find next free circuit ID.
*/
static unsigned short nr_find_next_circuit(void)
{
unsigned short id = circuit;
unsigned char i, j;
struct sock *sk;
for (;;) {
i = id / 256;
j = id % 256;
if (i != 0 && j != 0) {
if ((sk=nr_find_socket(i, j)) == NULL)
break;
sock_put(sk);
}
id++;
}
return id;
}
/*
* Deferred destroy.
*/
void nr_destroy_socket(struct sock *);
/*
* Handler for deferred kills.
*/
static void nr_destroy_timer(struct timer_list *t)
{
struct sock *sk = from_timer(sk, t, sk_timer);
bh_lock_sock(sk);
sock_hold(sk);
nr_destroy_socket(sk);
bh_unlock_sock(sk);
sock_put(sk);
}
/*
* This is called from user mode and the timers. Thus it protects itself
* against interrupt users but doesn't worry about being called during
* work. Once it is removed from the queue no interrupt or bottom half
* will touch it and we are (fairly 8-) ) safe.
*/
void nr_destroy_socket(struct sock *sk)
{
struct sk_buff *skb;
nr_remove_socket(sk);
nr_stop_heartbeat(sk);
nr_stop_t1timer(sk);
nr_stop_t2timer(sk);
nr_stop_t4timer(sk);
nr_stop_idletimer(sk);
nr_clear_queues(sk); /* Flush the queues */
while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
if (skb->sk != sk) { /* A pending connection */
/* Queue the unaccepted socket for death */
sock_set_flag(skb->sk, SOCK_DEAD);
nr_start_heartbeat(skb->sk);
nr_sk(skb->sk)->state = NR_STATE_0;
}
kfree_skb(skb);
}
if (sk_has_allocations(sk)) {
/* Defer: outstanding buffers */
sk->sk_timer.function = nr_destroy_timer;
sk->sk_timer.expires = jiffies + 2 * HZ;
add_timer(&sk->sk_timer);
} else
sock_put(sk);
}
/*
* Handling for system calls applied via the various interfaces to a
* NET/ROM socket object.
*/
static int nr_setsockopt(struct socket *sock, int level, int optname,
sockptr_t optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct nr_sock *nr = nr_sk(sk);
unsigned int opt;
if (level != SOL_NETROM)
return -ENOPROTOOPT;
if (optlen < sizeof(unsigned int))
return -EINVAL;
if (copy_from_sockptr(&opt, optval, sizeof(opt)))
return -EFAULT;
switch (optname) {
case NETROM_T1:
if (opt < 1 || opt > UINT_MAX / HZ)
return -EINVAL;
nr->t1 = opt * HZ;
return 0;
case NETROM_T2:
if (opt < 1 || opt > UINT_MAX / HZ)
return -EINVAL;
nr->t2 = opt * HZ;
return 0;
case NETROM_N2:
if (opt < 1 || opt > 31)
return -EINVAL;
nr->n2 = opt;
return 0;
case NETROM_T4:
if (opt < 1 || opt > UINT_MAX / HZ)
return -EINVAL;
nr->t4 = opt * HZ;
return 0;
case NETROM_IDLE:
if (opt > UINT_MAX / (60 * HZ))
return -EINVAL;
nr->idle = opt * 60 * HZ;
return 0;
default:
return -ENOPROTOOPT;
}
}
static int nr_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct nr_sock *nr = nr_sk(sk);
int val = 0;
int len;
if (level != SOL_NETROM)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
switch (optname) {
case NETROM_T1:
val = nr->t1 / HZ;
break;
case NETROM_T2:
val = nr->t2 / HZ;
break;
case NETROM_N2:
val = nr->n2;
break;
case NETROM_T4:
val = nr->t4 / HZ;
break;
case NETROM_IDLE:
val = nr->idle / (60 * HZ);
break;
default:
return -ENOPROTOOPT;
}
len = min_t(unsigned int, len, sizeof(int));
if (put_user(len, optlen))
return -EFAULT;
return copy_to_user(optval, &val, len) ? -EFAULT : 0;
}
static int nr_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
lock_sock(sk);
if (sock->state != SS_UNCONNECTED) {
release_sock(sk);
return -EINVAL;
}
if (sk->sk_state != TCP_LISTEN) {
memset(&nr_sk(sk)->user_addr, 0, AX25_ADDR_LEN);
sk->sk_max_ack_backlog = backlog;
sk->sk_state = TCP_LISTEN;
release_sock(sk);
return 0;
}
release_sock(sk);
return -EOPNOTSUPP;
}
static struct proto nr_proto = {
.name = "NETROM",
.owner = THIS_MODULE,
.obj_size = sizeof(struct nr_sock),
};
static int nr_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct nr_sock *nr;
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
if (sock->type != SOCK_SEQPACKET || protocol != 0)
return -ESOCKTNOSUPPORT;
sk = sk_alloc(net, PF_NETROM, GFP_ATOMIC, &nr_proto, kern);
if (sk == NULL)
return -ENOMEM;
nr = nr_sk(sk);
sock_init_data(sock, sk);
sock->ops = &nr_proto_ops;
sk->sk_protocol = protocol;
skb_queue_head_init(&nr->ack_queue);
skb_queue_head_init(&nr->reseq_queue);
skb_queue_head_init(&nr->frag_queue);
nr_init_timers(sk);
nr->t1 =
msecs_to_jiffies(sysctl_netrom_transport_timeout);
nr->t2 =
msecs_to_jiffies(sysctl_netrom_transport_acknowledge_delay);
nr->n2 =
msecs_to_jiffies(sysctl_netrom_transport_maximum_tries);
nr->t4 =
msecs_to_jiffies(sysctl_netrom_transport_busy_delay);
nr->idle =
msecs_to_jiffies(sysctl_netrom_transport_no_activity_timeout);
nr->window = sysctl_netrom_transport_requested_window_size;
nr->bpqext = 1;
nr->state = NR_STATE_0;
return 0;
}
static struct sock *nr_make_new(struct sock *osk)
{
struct sock *sk;
struct nr_sock *nr, *onr;
if (osk->sk_type != SOCK_SEQPACKET)
return NULL;
sk = sk_alloc(sock_net(osk), PF_NETROM, GFP_ATOMIC, osk->sk_prot, 0);
if (sk == NULL)
return NULL;
nr = nr_sk(sk);
sock_init_data(NULL, sk);
sk->sk_type = osk->sk_type;
sk->sk_priority = osk->sk_priority;
sk->sk_protocol = osk->sk_protocol;
sk->sk_rcvbuf = osk->sk_rcvbuf;
sk->sk_sndbuf = osk->sk_sndbuf;
sk->sk_state = TCP_ESTABLISHED;
sock_copy_flags(sk, osk);
skb_queue_head_init(&nr->ack_queue);
skb_queue_head_init(&nr->reseq_queue);
skb_queue_head_init(&nr->frag_queue);
nr_init_timers(sk);
onr = nr_sk(osk);
nr->t1 = onr->t1;
nr->t2 = onr->t2;
nr->n2 = onr->n2;
nr->t4 = onr->t4;
nr->idle = onr->idle;
nr->window = onr->window;
nr->device = onr->device;
nr->bpqext = onr->bpqext;
return sk;
}
static int nr_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct nr_sock *nr;
if (sk == NULL) return 0;
sock_hold(sk);
sock_orphan(sk);
lock_sock(sk);
nr = nr_sk(sk);
switch (nr->state) {
case NR_STATE_0:
case NR_STATE_1:
case NR_STATE_2:
nr_disconnect(sk, 0);
nr_destroy_socket(sk);
break;
case NR_STATE_3:
nr_clear_queues(sk);
nr->n2count = 0;
nr_write_internal(sk, NR_DISCREQ);
nr_start_t1timer(sk);
nr_stop_t2timer(sk);
nr_stop_t4timer(sk);
nr_stop_idletimer(sk);
nr->state = NR_STATE_2;
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_DESTROY);
break;
default:
break;
}
sock->sk = NULL;
release_sock(sk);
sock_put(sk);
return 0;
}
static int nr_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct nr_sock *nr = nr_sk(sk);
struct full_sockaddr_ax25 *addr = (struct full_sockaddr_ax25 *)uaddr;
struct net_device *dev;
ax25_uid_assoc *user;
ax25_address *source;
lock_sock(sk);
if (!sock_flag(sk, SOCK_ZAPPED)) {
release_sock(sk);
return -EINVAL;
}
if (addr_len < sizeof(struct sockaddr_ax25) || addr_len > sizeof(struct full_sockaddr_ax25)) {
release_sock(sk);
return -EINVAL;
}
if (addr_len < (addr->fsa_ax25.sax25_ndigis * sizeof(ax25_address) + sizeof(struct sockaddr_ax25))) {
release_sock(sk);
return -EINVAL;
}
if (addr->fsa_ax25.sax25_family != AF_NETROM) {
release_sock(sk);
return -EINVAL;
}
if ((dev = nr_dev_get(&addr->fsa_ax25.sax25_call)) == NULL) {
release_sock(sk);
return -EADDRNOTAVAIL;
}
/*
* Only the super user can set an arbitrary user callsign.
*/
if (addr->fsa_ax25.sax25_ndigis == 1) {
if (!capable(CAP_NET_BIND_SERVICE)) {
dev_put(dev);
release_sock(sk);
return -EPERM;
}
nr->user_addr = addr->fsa_digipeater[0];
nr->source_addr = addr->fsa_ax25.sax25_call;
} else {
source = &addr->fsa_ax25.sax25_call;
user = ax25_findbyuid(current_euid());
if (user) {
nr->user_addr = user->call;
ax25_uid_put(user);
} else {
if (ax25_uid_policy && !capable(CAP_NET_BIND_SERVICE)) {
release_sock(sk);
dev_put(dev);
return -EPERM;
}
nr->user_addr = *source;
}
nr->source_addr = *source;
}
nr->device = dev;
nr_insert_socket(sk);
sock_reset_flag(sk, SOCK_ZAPPED);
dev_put(dev);
release_sock(sk);
return 0;
}
static int nr_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sock *sk = sock->sk;
struct nr_sock *nr = nr_sk(sk);
struct sockaddr_ax25 *addr = (struct sockaddr_ax25 *)uaddr;
const ax25_address *source = NULL;
ax25_uid_assoc *user;
struct net_device *dev;
int err = 0;
lock_sock(sk);
if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) {
sock->state = SS_CONNECTED;
goto out_release; /* Connect completed during a ERESTARTSYS event */
}
if (sk->sk_state == TCP_CLOSE && sock->state == SS_CONNECTING) {
sock->state = SS_UNCONNECTED;
err = -ECONNREFUSED;
goto out_release;
}
if (sk->sk_state == TCP_ESTABLISHED) {
err = -EISCONN; /* No reconnect on a seqpacket socket */
goto out_release;
}
if (sock->state == SS_CONNECTING) {
err = -EALREADY;
goto out_release;
}
sk->sk_state = TCP_CLOSE;
sock->state = SS_UNCONNECTED;
if (addr_len != sizeof(struct sockaddr_ax25) && addr_len != sizeof(struct full_sockaddr_ax25)) {
err = -EINVAL;
goto out_release;
}
if (addr->sax25_family != AF_NETROM) {
err = -EINVAL;
goto out_release;
}
if (sock_flag(sk, SOCK_ZAPPED)) { /* Must bind first - autobinding in this may or may not work */
sock_reset_flag(sk, SOCK_ZAPPED);
if ((dev = nr_dev_first()) == NULL) {
err = -ENETUNREACH;
goto out_release;
}
source = (const ax25_address *)dev->dev_addr;
user = ax25_findbyuid(current_euid());
if (user) {
nr->user_addr = user->call;
ax25_uid_put(user);
} else {
if (ax25_uid_policy && !capable(CAP_NET_ADMIN)) {
dev_put(dev);
err = -EPERM;
goto out_release;
}
nr->user_addr = *source;
}
nr->source_addr = *source;
nr->device = dev;
dev_put(dev);
nr_insert_socket(sk); /* Finish the bind */
}
nr->dest_addr = addr->sax25_call;
release_sock(sk);
circuit = nr_find_next_circuit();
lock_sock(sk);
nr->my_index = circuit / 256;
nr->my_id = circuit % 256;
circuit++;
/* Move to connecting socket, start sending Connect Requests */
sock->state = SS_CONNECTING;
sk->sk_state = TCP_SYN_SENT;
nr_establish_data_link(sk);
nr->state = NR_STATE_1;
nr_start_heartbeat(sk);
/* Now the loop */
if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK)) {
err = -EINPROGRESS;
goto out_release;
}
/*
* A Connect Ack with Choke or timeout or failed routing will go to
* closed.
*/
if (sk->sk_state == TCP_SYN_SENT) {
DEFINE_WAIT(wait);
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
if (sk->sk_state != TCP_SYN_SENT)
break;
if (!signal_pending(current)) {
release_sock(sk);
schedule();
lock_sock(sk);
continue;
}
err = -ERESTARTSYS;
break;
}
finish_wait(sk_sleep(sk), &wait);
if (err)
goto out_release;
}
if (sk->sk_state != TCP_ESTABLISHED) {
sock->state = SS_UNCONNECTED;
err = sock_error(sk); /* Always set at this point */
goto out_release;
}
sock->state = SS_CONNECTED;
out_release:
release_sock(sk);
return err;
}
static int nr_accept(struct socket *sock, struct socket *newsock, int flags,
bool kern)
{
struct sk_buff *skb;
struct sock *newsk;
DEFINE_WAIT(wait);
struct sock *sk;
int err = 0;
if ((sk = sock->sk) == NULL)
return -EINVAL;
lock_sock(sk);
if (sk->sk_type != SOCK_SEQPACKET) {
err = -EOPNOTSUPP;
goto out_release;
}
if (sk->sk_state != TCP_LISTEN) {
err = -EINVAL;
goto out_release;
}
/*
* The write queue this time is holding sockets ready to use
* hooked into the SABM we saved
*/
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
skb = skb_dequeue(&sk->sk_receive_queue);
if (skb)
break;
if (flags & O_NONBLOCK) {
err = -EWOULDBLOCK;
break;
}
if (!signal_pending(current)) {
release_sock(sk);
schedule();
lock_sock(sk);
continue;
}
err = -ERESTARTSYS;
break;
}
finish_wait(sk_sleep(sk), &wait);
if (err)
goto out_release;
newsk = skb->sk;
sock_graft(newsk, newsock);
/* Now attach up the new socket */
kfree_skb(skb);
sk_acceptq_removed(sk);
out_release:
release_sock(sk);
return err;
}
static int nr_getname(struct socket *sock, struct sockaddr *uaddr,
int peer)
{
struct full_sockaddr_ax25 *sax = (struct full_sockaddr_ax25 *)uaddr;
struct sock *sk = sock->sk;
struct nr_sock *nr = nr_sk(sk);
int uaddr_len;
memset(&sax->fsa_ax25, 0, sizeof(struct sockaddr_ax25));
lock_sock(sk);
if (peer != 0) {
if (sk->sk_state != TCP_ESTABLISHED) {
release_sock(sk);
return -ENOTCONN;
}
sax->fsa_ax25.sax25_family = AF_NETROM;
sax->fsa_ax25.sax25_ndigis = 1;
sax->fsa_ax25.sax25_call = nr->user_addr;
memset(sax->fsa_digipeater, 0, sizeof(sax->fsa_digipeater));
sax->fsa_digipeater[0] = nr->dest_addr;
uaddr_len = sizeof(struct full_sockaddr_ax25);
} else {
sax->fsa_ax25.sax25_family = AF_NETROM;
sax->fsa_ax25.sax25_ndigis = 0;
sax->fsa_ax25.sax25_call = nr->source_addr;
uaddr_len = sizeof(struct sockaddr_ax25);
}
release_sock(sk);
return uaddr_len;
}
int nr_rx_frame(struct sk_buff *skb, struct net_device *dev)
{
struct sock *sk;
struct sock *make;
struct nr_sock *nr_make;
ax25_address *src, *dest, *user;
unsigned short circuit_index, circuit_id;
unsigned short peer_circuit_index, peer_circuit_id;
unsigned short frametype, flags, window, timeout;
int ret;
skb_orphan(skb);
/*
* skb->data points to the netrom frame start
*/
src = (ax25_address *)(skb->data + 0);
dest = (ax25_address *)(skb->data + 7);
circuit_index = skb->data[15];
circuit_id = skb->data[16];
peer_circuit_index = skb->data[17];
peer_circuit_id = skb->data[18];
frametype = skb->data[19] & 0x0F;
flags = skb->data[19] & 0xF0;
/*
* Check for an incoming IP over NET/ROM frame.
*/
if (frametype == NR_PROTOEXT &&
circuit_index == NR_PROTO_IP && circuit_id == NR_PROTO_IP) {
skb_pull(skb, NR_NETWORK_LEN + NR_TRANSPORT_LEN);
skb_reset_transport_header(skb);
return nr_rx_ip(skb, dev);
}
/*
* Find an existing socket connection, based on circuit ID, if it's
* a Connect Request base it on their circuit ID.
*
* Circuit ID 0/0 is not valid but it could still be a "reset" for a
* circuit that no longer exists at the other end ...
*/
sk = NULL;
if (circuit_index == 0 && circuit_id == 0) {
if (frametype == NR_CONNACK && flags == NR_CHOKE_FLAG)
sk = nr_find_peer(peer_circuit_index, peer_circuit_id, src);
} else {
if (frametype == NR_CONNREQ)
sk = nr_find_peer(circuit_index, circuit_id, src);
else
sk = nr_find_socket(circuit_index, circuit_id);
}
if (sk != NULL) {
bh_lock_sock(sk);
skb_reset_transport_header(skb);
if (frametype == NR_CONNACK && skb->len == 22)
nr_sk(sk)->bpqext = 1;
else
nr_sk(sk)->bpqext = 0;
ret = nr_process_rx_frame(sk, skb);
bh_unlock_sock(sk);
sock_put(sk);
return ret;
}
/*
* Now it should be a CONNREQ.
*/
if (frametype != NR_CONNREQ) {
/*
* Here it would be nice to be able to send a reset but
* NET/ROM doesn't have one. We've tried to extend the protocol
* by sending NR_CONNACK | NR_CHOKE_FLAGS replies but that
* apparently kills BPQ boxes... :-(
* So now we try to follow the established behaviour of
* G8PZT's Xrouter which is sending packets with command type 7
* as an extension of the protocol.
*/
if (sysctl_netrom_reset_circuit &&
(frametype != NR_RESET || flags != 0))
nr_transmit_reset(skb, 1);
return 0;
}
sk = nr_find_listener(dest);
user = (ax25_address *)(skb->data + 21);
if (sk == NULL || sk_acceptq_is_full(sk) ||
(make = nr_make_new(sk)) == NULL) {
nr_transmit_refusal(skb, 0);
if (sk)
sock_put(sk);
return 0;
}
bh_lock_sock(sk);
window = skb->data[20];
sock_hold(make);
skb->sk = make;
skb->destructor = sock_efree;
make->sk_state = TCP_ESTABLISHED;
/* Fill in his circuit details */
nr_make = nr_sk(make);
nr_make->source_addr = *dest;
nr_make->dest_addr = *src;
nr_make->user_addr = *user;
nr_make->your_index = circuit_index;
nr_make->your_id = circuit_id;
bh_unlock_sock(sk);
circuit = nr_find_next_circuit();
bh_lock_sock(sk);
nr_make->my_index = circuit / 256;
nr_make->my_id = circuit % 256;
circuit++;
/* Window negotiation */
if (window < nr_make->window)
nr_make->window = window;
/* L4 timeout negotiation */
if (skb->len == 37) {
timeout = skb->data[36] * 256 + skb->data[35];
if (timeout * HZ < nr_make->t1)
nr_make->t1 = timeout * HZ;
nr_make->bpqext = 1;
} else {
nr_make->bpqext = 0;
}
nr_write_internal(make, NR_CONNACK);
nr_make->condition = 0x00;
nr_make->vs = 0;
nr_make->va = 0;
nr_make->vr = 0;
nr_make->vl = 0;
nr_make->state = NR_STATE_3;
sk_acceptq_added(sk);
skb_queue_head(&sk->sk_receive_queue, skb);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk);
bh_unlock_sock(sk);
sock_put(sk);
nr_insert_socket(make);
nr_start_heartbeat(make);
nr_start_idletimer(make);
return 1;
}
static int nr_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct nr_sock *nr = nr_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_ax25 *, usax, msg->msg_name);
int err;
struct sockaddr_ax25 sax;
struct sk_buff *skb;
unsigned char *asmptr;
int size;
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_CMSG_COMPAT))
return -EINVAL;
lock_sock(sk);
if (sock_flag(sk, SOCK_ZAPPED)) {
err = -EADDRNOTAVAIL;
goto out;
}
if (sk->sk_shutdown & SEND_SHUTDOWN) {
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
goto out;
}
if (nr->device == NULL) {
err = -ENETUNREACH;
goto out;
}
if (usax) {
if (msg->msg_namelen < sizeof(sax)) {
err = -EINVAL;
goto out;
}
sax = *usax;
if (ax25cmp(&nr->dest_addr, &sax.sax25_call) != 0) {
err = -EISCONN;
goto out;
}
if (sax.sax25_family != AF_NETROM) {
err = -EINVAL;
goto out;
}
} else {
if (sk->sk_state != TCP_ESTABLISHED) {
err = -ENOTCONN;
goto out;
}
sax.sax25_family = AF_NETROM;
sax.sax25_call = nr->dest_addr;
}
/* Build a packet - the conventional user limit is 236 bytes. We can
do ludicrously large NetROM frames but must not overflow */
if (len > 65536) {
err = -EMSGSIZE;
goto out;
}
size = len + NR_NETWORK_LEN + NR_TRANSPORT_LEN;
if ((skb = sock_alloc_send_skb(sk, size, msg->msg_flags & MSG_DONTWAIT, &err)) == NULL)
goto out;
skb_reserve(skb, size - len);
skb_reset_transport_header(skb);
/*
* Push down the NET/ROM header
*/
asmptr = skb_push(skb, NR_TRANSPORT_LEN);
/* Build a NET/ROM Transport header */
*asmptr++ = nr->your_index;
*asmptr++ = nr->your_id;
*asmptr++ = 0; /* To be filled in later */
*asmptr++ = 0; /* Ditto */
*asmptr++ = NR_INFO;
/*
* Put the data on the end
*/
skb_put(skb, len);
/* User data follows immediately after the NET/ROM transport header */
if (memcpy_from_msg(skb_transport_header(skb), msg, len)) {
kfree_skb(skb);
err = -EFAULT;
goto out;
}
if (sk->sk_state != TCP_ESTABLISHED) {
kfree_skb(skb);
err = -ENOTCONN;
goto out;
}
nr_output(sk, skb); /* Shove it onto the queue */
err = len;
out:
release_sock(sk);
return err;
}
static int nr_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
DECLARE_SOCKADDR(struct sockaddr_ax25 *, sax, msg->msg_name);
size_t copied;
struct sk_buff *skb;
int er;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
lock_sock(sk);
if (sk->sk_state != TCP_ESTABLISHED) {
release_sock(sk);
return -ENOTCONN;
}
/* Now we can treat all alike */
skb = skb_recv_datagram(sk, flags, &er);
if (!skb) {
release_sock(sk);
return er;
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
er = skb_copy_datagram_msg(skb, 0, msg, copied);
if (er < 0) {
skb_free_datagram(sk, skb);
release_sock(sk);
return er;
}
if (sax != NULL) {
memset(sax, 0, sizeof(*sax));
sax->sax25_family = AF_NETROM;
skb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call,
AX25_ADDR_LEN);
msg->msg_namelen = sizeof(*sax);
}
skb_free_datagram(sk, skb);
release_sock(sk);
return copied;
}
static int nr_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
void __user *argp = (void __user *)arg;
switch (cmd) {
case TIOCOUTQ: {
long amount;
lock_sock(sk);
amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amount < 0)
amount = 0;
release_sock(sk);
return put_user(amount, (int __user *)argp);
}
case TIOCINQ: {
struct sk_buff *skb;
long amount = 0L;
lock_sock(sk);
/* These two are safe on a single CPU system as only user tasks fiddle here */
if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL)
amount = skb->len;
release_sock(sk);
return put_user(amount, (int __user *)argp);
}
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFMETRIC:
case SIOCSIFMETRIC:
return -EINVAL;
case SIOCADDRT:
case SIOCDELRT:
case SIOCNRDECOBS:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return nr_rt_ioctl(cmd, argp);
default:
return -ENOIOCTLCMD;
}
return 0;
}
#ifdef CONFIG_PROC_FS
static void *nr_info_start(struct seq_file *seq, loff_t *pos)
__acquires(&nr_list_lock)
{
spin_lock_bh(&nr_list_lock);
return seq_hlist_start_head(&nr_list, *pos);
}
static void *nr_info_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_hlist_next(v, &nr_list, pos);
}
static void nr_info_stop(struct seq_file *seq, void *v)
__releases(&nr_list_lock)
{
spin_unlock_bh(&nr_list_lock);
}
static int nr_info_show(struct seq_file *seq, void *v)
{
struct sock *s = sk_entry(v);
struct net_device *dev;
struct nr_sock *nr;
const char *devname;
char buf[11];
if (v == SEQ_START_TOKEN)
seq_puts(seq,
"user_addr dest_node src_node dev my your st vs vr va t1 t2 t4 idle n2 wnd Snd-Q Rcv-Q inode\n");
else {
bh_lock_sock(s);
nr = nr_sk(s);
if ((dev = nr->device) == NULL)
devname = "???";
else
devname = dev->name;
seq_printf(seq, "%-9s ", ax2asc(buf, &nr->user_addr));
seq_printf(seq, "%-9s ", ax2asc(buf, &nr->dest_addr));
seq_printf(seq,
"%-9s %-3s %02X/%02X %02X/%02X %2d %3d %3d %3d %3lu/%03lu %2lu/%02lu %3lu/%03lu %3lu/%03lu %2d/%02d %3d %5d %5d %ld\n",
ax2asc(buf, &nr->source_addr),
devname,
nr->my_index,
nr->my_id,
nr->your_index,
nr->your_id,
nr->state,
nr->vs,
nr->vr,
nr->va,
ax25_display_timer(&nr->t1timer) / HZ,
nr->t1 / HZ,
ax25_display_timer(&nr->t2timer) / HZ,
nr->t2 / HZ,
ax25_display_timer(&nr->t4timer) / HZ,
nr->t4 / HZ,
ax25_display_timer(&nr->idletimer) / (60 * HZ),
nr->idle / (60 * HZ),
nr->n2count,
nr->n2,
nr->window,
sk_wmem_alloc_get(s),
sk_rmem_alloc_get(s),
s->sk_socket ? SOCK_INODE(s->sk_socket)->i_ino : 0L);
bh_unlock_sock(s);
}
return 0;
}
static const struct seq_operations nr_info_seqops = {
.start = nr_info_start,
.next = nr_info_next,
.stop = nr_info_stop,
.show = nr_info_show,
};
#endif /* CONFIG_PROC_FS */
static const struct net_proto_family nr_family_ops = {
.family = PF_NETROM,
.create = nr_create,
.owner = THIS_MODULE,
};
static const struct proto_ops nr_proto_ops = {
.family = PF_NETROM,
.owner = THIS_MODULE,
.release = nr_release,
.bind = nr_bind,
.connect = nr_connect,
.socketpair = sock_no_socketpair,
.accept = nr_accept,
.getname = nr_getname,
.poll = datagram_poll,
.ioctl = nr_ioctl,
.gettstamp = sock_gettstamp,
.listen = nr_listen,
.shutdown = sock_no_shutdown,
.setsockopt = nr_setsockopt,
.getsockopt = nr_getsockopt,
.sendmsg = nr_sendmsg,
.recvmsg = nr_recvmsg,
.mmap = sock_no_mmap,
};
static struct notifier_block nr_dev_notifier = {
.notifier_call = nr_device_event,
};
static struct net_device **dev_nr;
static struct ax25_protocol nr_pid = {
.pid = AX25_P_NETROM,
.func = nr_route_frame
};
static struct ax25_linkfail nr_linkfail_notifier = {
.func = nr_link_failed,
};
static int __init nr_proto_init(void)
{
int i;
int rc = proto_register(&nr_proto, 0);
if (rc)
return rc;
if (nr_ndevs > 0x7fffffff/sizeof(struct net_device *)) {
pr_err("NET/ROM: %s - nr_ndevs parameter too large\n",
__func__);
rc = -EINVAL;
goto unregister_proto;
}
dev_nr = kcalloc(nr_ndevs, sizeof(struct net_device *), GFP_KERNEL);
if (!dev_nr) {
pr_err("NET/ROM: %s - unable to allocate device array\n",
__func__);
rc = -ENOMEM;
goto unregister_proto;
}
for (i = 0; i < nr_ndevs; i++) {
char name[IFNAMSIZ];
struct net_device *dev;
sprintf(name, "nr%d", i);
dev = alloc_netdev(0, name, NET_NAME_UNKNOWN, nr_setup);
if (!dev) {
rc = -ENOMEM;
goto fail;
}
dev->base_addr = i;
rc = register_netdev(dev);
if (rc) {
free_netdev(dev);
goto fail;
}
nr_set_lockdep_key(dev);
dev_nr[i] = dev;
}
rc = sock_register(&nr_family_ops);
if (rc)
goto fail;
rc = register_netdevice_notifier(&nr_dev_notifier);
if (rc)
goto out_sock;
ax25_register_pid(&nr_pid);
ax25_linkfail_register(&nr_linkfail_notifier);
#ifdef CONFIG_SYSCTL
rc = nr_register_sysctl();
if (rc)
goto out_sysctl;
#endif
nr_loopback_init();
rc = -ENOMEM;
if (!proc_create_seq("nr", 0444, init_net.proc_net, &nr_info_seqops))
goto proc_remove1;
if (!proc_create_seq("nr_neigh", 0444, init_net.proc_net,
&nr_neigh_seqops))
goto proc_remove2;
if (!proc_create_seq("nr_nodes", 0444, init_net.proc_net,
&nr_node_seqops))
goto proc_remove3;
return 0;
proc_remove3:
remove_proc_entry("nr_neigh", init_net.proc_net);
proc_remove2:
remove_proc_entry("nr", init_net.proc_net);
proc_remove1:
nr_loopback_clear();
nr_rt_free();
#ifdef CONFIG_SYSCTL
nr_unregister_sysctl();
out_sysctl:
#endif
ax25_linkfail_release(&nr_linkfail_notifier);
ax25_protocol_release(AX25_P_NETROM);
unregister_netdevice_notifier(&nr_dev_notifier);
out_sock:
sock_unregister(PF_NETROM);
fail:
while (--i >= 0) {
unregister_netdev(dev_nr[i]);
free_netdev(dev_nr[i]);
}
kfree(dev_nr);
unregister_proto:
proto_unregister(&nr_proto);
return rc;
}
module_init(nr_proto_init);
module_param(nr_ndevs, int, 0);
MODULE_PARM_DESC(nr_ndevs, "number of NET/ROM devices");
MODULE_AUTHOR("Jonathan Naylor G4KLX <[email protected]>");
MODULE_DESCRIPTION("The amateur radio NET/ROM network and transport layer protocol");
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_NETROM);
static void __exit nr_exit(void)
{
int i;
remove_proc_entry("nr", init_net.proc_net);
remove_proc_entry("nr_neigh", init_net.proc_net);
remove_proc_entry("nr_nodes", init_net.proc_net);
nr_loopback_clear();
nr_rt_free();
#ifdef CONFIG_SYSCTL
nr_unregister_sysctl();
#endif
ax25_linkfail_release(&nr_linkfail_notifier);
ax25_protocol_release(AX25_P_NETROM);
unregister_netdevice_notifier(&nr_dev_notifier);
sock_unregister(PF_NETROM);
for (i = 0; i < nr_ndevs; i++) {
struct net_device *dev = dev_nr[i];
if (dev) {
unregister_netdev(dev);
free_netdev(dev);
}
}
kfree(dev_nr);
proto_unregister(&nr_proto);
}
module_exit(nr_exit);
| linux-master | net/netrom/af_netrom.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
*
* Copyright (C) Jonathan Naylor G4KLX ([email protected])
* Copyright (C) 2002 Ralf Baechle DO1GRB ([email protected])
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <linux/uaccess.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <net/netrom.h>
static void nr_heartbeat_expiry(struct timer_list *);
static void nr_t1timer_expiry(struct timer_list *);
static void nr_t2timer_expiry(struct timer_list *);
static void nr_t4timer_expiry(struct timer_list *);
static void nr_idletimer_expiry(struct timer_list *);
void nr_init_timers(struct sock *sk)
{
struct nr_sock *nr = nr_sk(sk);
timer_setup(&nr->t1timer, nr_t1timer_expiry, 0);
timer_setup(&nr->t2timer, nr_t2timer_expiry, 0);
timer_setup(&nr->t4timer, nr_t4timer_expiry, 0);
timer_setup(&nr->idletimer, nr_idletimer_expiry, 0);
/* initialized by sock_init_data */
sk->sk_timer.function = nr_heartbeat_expiry;
}
void nr_start_t1timer(struct sock *sk)
{
struct nr_sock *nr = nr_sk(sk);
sk_reset_timer(sk, &nr->t1timer, jiffies + nr->t1);
}
void nr_start_t2timer(struct sock *sk)
{
struct nr_sock *nr = nr_sk(sk);
sk_reset_timer(sk, &nr->t2timer, jiffies + nr->t2);
}
void nr_start_t4timer(struct sock *sk)
{
struct nr_sock *nr = nr_sk(sk);
sk_reset_timer(sk, &nr->t4timer, jiffies + nr->t4);
}
void nr_start_idletimer(struct sock *sk)
{
struct nr_sock *nr = nr_sk(sk);
if (nr->idle > 0)
sk_reset_timer(sk, &nr->idletimer, jiffies + nr->idle);
}
void nr_start_heartbeat(struct sock *sk)
{
sk_reset_timer(sk, &sk->sk_timer, jiffies + 5 * HZ);
}
void nr_stop_t1timer(struct sock *sk)
{
sk_stop_timer(sk, &nr_sk(sk)->t1timer);
}
void nr_stop_t2timer(struct sock *sk)
{
sk_stop_timer(sk, &nr_sk(sk)->t2timer);
}
void nr_stop_t4timer(struct sock *sk)
{
sk_stop_timer(sk, &nr_sk(sk)->t4timer);
}
void nr_stop_idletimer(struct sock *sk)
{
sk_stop_timer(sk, &nr_sk(sk)->idletimer);
}
void nr_stop_heartbeat(struct sock *sk)
{
sk_stop_timer(sk, &sk->sk_timer);
}
int nr_t1timer_running(struct sock *sk)
{
return timer_pending(&nr_sk(sk)->t1timer);
}
static void nr_heartbeat_expiry(struct timer_list *t)
{
struct sock *sk = from_timer(sk, t, sk_timer);
struct nr_sock *nr = nr_sk(sk);
bh_lock_sock(sk);
switch (nr->state) {
case NR_STATE_0:
/* Magic here: If we listen() and a new link dies before it
is accepted() it isn't 'dead' so doesn't get removed. */
if (sock_flag(sk, SOCK_DESTROY) ||
(sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_DEAD))) {
sock_hold(sk);
bh_unlock_sock(sk);
nr_destroy_socket(sk);
goto out;
}
break;
case NR_STATE_3:
/*
* Check for the state of the receive buffer.
*/
if (atomic_read(&sk->sk_rmem_alloc) < (sk->sk_rcvbuf / 2) &&
(nr->condition & NR_COND_OWN_RX_BUSY)) {
nr->condition &= ~NR_COND_OWN_RX_BUSY;
nr->condition &= ~NR_COND_ACK_PENDING;
nr->vl = nr->vr;
nr_write_internal(sk, NR_INFOACK);
break;
}
break;
}
nr_start_heartbeat(sk);
bh_unlock_sock(sk);
out:
sock_put(sk);
}
static void nr_t2timer_expiry(struct timer_list *t)
{
struct nr_sock *nr = from_timer(nr, t, t2timer);
struct sock *sk = &nr->sock;
bh_lock_sock(sk);
if (nr->condition & NR_COND_ACK_PENDING) {
nr->condition &= ~NR_COND_ACK_PENDING;
nr_enquiry_response(sk);
}
bh_unlock_sock(sk);
sock_put(sk);
}
static void nr_t4timer_expiry(struct timer_list *t)
{
struct nr_sock *nr = from_timer(nr, t, t4timer);
struct sock *sk = &nr->sock;
bh_lock_sock(sk);
nr_sk(sk)->condition &= ~NR_COND_PEER_RX_BUSY;
bh_unlock_sock(sk);
sock_put(sk);
}
static void nr_idletimer_expiry(struct timer_list *t)
{
struct nr_sock *nr = from_timer(nr, t, idletimer);
struct sock *sk = &nr->sock;
bh_lock_sock(sk);
nr_clear_queues(sk);
nr->n2count = 0;
nr_write_internal(sk, NR_DISCREQ);
nr->state = NR_STATE_2;
nr_start_t1timer(sk);
nr_stop_t2timer(sk);
nr_stop_t4timer(sk);
sk->sk_state = TCP_CLOSE;
sk->sk_err = 0;
sk->sk_shutdown |= SEND_SHUTDOWN;
if (!sock_flag(sk, SOCK_DEAD)) {
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_DEAD);
}
bh_unlock_sock(sk);
sock_put(sk);
}
static void nr_t1timer_expiry(struct timer_list *t)
{
struct nr_sock *nr = from_timer(nr, t, t1timer);
struct sock *sk = &nr->sock;
bh_lock_sock(sk);
switch (nr->state) {
case NR_STATE_1:
if (nr->n2count == nr->n2) {
nr_disconnect(sk, ETIMEDOUT);
goto out;
} else {
nr->n2count++;
nr_write_internal(sk, NR_CONNREQ);
}
break;
case NR_STATE_2:
if (nr->n2count == nr->n2) {
nr_disconnect(sk, ETIMEDOUT);
goto out;
} else {
nr->n2count++;
nr_write_internal(sk, NR_DISCREQ);
}
break;
case NR_STATE_3:
if (nr->n2count == nr->n2) {
nr_disconnect(sk, ETIMEDOUT);
goto out;
} else {
nr->n2count++;
nr_requeue_frames(sk);
}
break;
}
nr_start_t1timer(sk);
out:
bh_unlock_sock(sk);
sock_put(sk);
}
| linux-master | net/netrom/nr_timer.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/ethtool.h>
#include <linux/phy.h>
#include "netlink.h"
#include "common.h"
struct strset_info {
bool per_dev;
bool free_strings;
unsigned int count;
const char (*strings)[ETH_GSTRING_LEN];
};
static const struct strset_info info_template[] = {
[ETH_SS_TEST] = {
.per_dev = true,
},
[ETH_SS_STATS] = {
.per_dev = true,
},
[ETH_SS_PRIV_FLAGS] = {
.per_dev = true,
},
[ETH_SS_FEATURES] = {
.per_dev = false,
.count = ARRAY_SIZE(netdev_features_strings),
.strings = netdev_features_strings,
},
[ETH_SS_RSS_HASH_FUNCS] = {
.per_dev = false,
.count = ARRAY_SIZE(rss_hash_func_strings),
.strings = rss_hash_func_strings,
},
[ETH_SS_TUNABLES] = {
.per_dev = false,
.count = ARRAY_SIZE(tunable_strings),
.strings = tunable_strings,
},
[ETH_SS_PHY_STATS] = {
.per_dev = true,
},
[ETH_SS_PHY_TUNABLES] = {
.per_dev = false,
.count = ARRAY_SIZE(phy_tunable_strings),
.strings = phy_tunable_strings,
},
[ETH_SS_LINK_MODES] = {
.per_dev = false,
.count = __ETHTOOL_LINK_MODE_MASK_NBITS,
.strings = link_mode_names,
},
[ETH_SS_MSG_CLASSES] = {
.per_dev = false,
.count = NETIF_MSG_CLASS_COUNT,
.strings = netif_msg_class_names,
},
[ETH_SS_WOL_MODES] = {
.per_dev = false,
.count = WOL_MODE_COUNT,
.strings = wol_mode_names,
},
[ETH_SS_SOF_TIMESTAMPING] = {
.per_dev = false,
.count = __SOF_TIMESTAMPING_CNT,
.strings = sof_timestamping_names,
},
[ETH_SS_TS_TX_TYPES] = {
.per_dev = false,
.count = __HWTSTAMP_TX_CNT,
.strings = ts_tx_type_names,
},
[ETH_SS_TS_RX_FILTERS] = {
.per_dev = false,
.count = __HWTSTAMP_FILTER_CNT,
.strings = ts_rx_filter_names,
},
[ETH_SS_UDP_TUNNEL_TYPES] = {
.per_dev = false,
.count = __ETHTOOL_UDP_TUNNEL_TYPE_CNT,
.strings = udp_tunnel_type_names,
},
[ETH_SS_STATS_STD] = {
.per_dev = false,
.count = __ETHTOOL_STATS_CNT,
.strings = stats_std_names,
},
[ETH_SS_STATS_ETH_PHY] = {
.per_dev = false,
.count = __ETHTOOL_A_STATS_ETH_PHY_CNT,
.strings = stats_eth_phy_names,
},
[ETH_SS_STATS_ETH_MAC] = {
.per_dev = false,
.count = __ETHTOOL_A_STATS_ETH_MAC_CNT,
.strings = stats_eth_mac_names,
},
[ETH_SS_STATS_ETH_CTRL] = {
.per_dev = false,
.count = __ETHTOOL_A_STATS_ETH_CTRL_CNT,
.strings = stats_eth_ctrl_names,
},
[ETH_SS_STATS_RMON] = {
.per_dev = false,
.count = __ETHTOOL_A_STATS_RMON_CNT,
.strings = stats_rmon_names,
},
};
struct strset_req_info {
struct ethnl_req_info base;
u32 req_ids;
bool counts_only;
};
#define STRSET_REQINFO(__req_base) \
container_of(__req_base, struct strset_req_info, base)
struct strset_reply_data {
struct ethnl_reply_data base;
struct strset_info sets[ETH_SS_COUNT];
};
#define STRSET_REPDATA(__reply_base) \
container_of(__reply_base, struct strset_reply_data, base)
const struct nla_policy ethnl_strset_get_policy[] = {
[ETHTOOL_A_STRSET_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_STRSET_STRINGSETS] = { .type = NLA_NESTED },
[ETHTOOL_A_STRSET_COUNTS_ONLY] = { .type = NLA_FLAG },
};
static const struct nla_policy get_stringset_policy[] = {
[ETHTOOL_A_STRINGSET_ID] = { .type = NLA_U32 },
};
/**
* strset_include() - test if a string set should be included in reply
* @info: parsed client request
* @data: pointer to request data structure
* @id: id of string set to check (ETH_SS_* constants)
*/
static bool strset_include(const struct strset_req_info *info,
const struct strset_reply_data *data, u32 id)
{
bool per_dev;
BUILD_BUG_ON(ETH_SS_COUNT >= BITS_PER_BYTE * sizeof(info->req_ids));
if (info->req_ids)
return info->req_ids & (1U << id);
per_dev = data->sets[id].per_dev;
if (!per_dev && !data->sets[id].strings)
return false;
return data->base.dev ? per_dev : !per_dev;
}
static int strset_get_id(const struct nlattr *nest, u32 *val,
struct netlink_ext_ack *extack)
{
struct nlattr *tb[ARRAY_SIZE(get_stringset_policy)];
int ret;
ret = nla_parse_nested(tb, ARRAY_SIZE(get_stringset_policy) - 1, nest,
get_stringset_policy, extack);
if (ret < 0)
return ret;
if (NL_REQ_ATTR_CHECK(extack, nest, tb, ETHTOOL_A_STRINGSET_ID))
return -EINVAL;
*val = nla_get_u32(tb[ETHTOOL_A_STRINGSET_ID]);
return 0;
}
static const struct nla_policy strset_stringsets_policy[] = {
[ETHTOOL_A_STRINGSETS_STRINGSET] = { .type = NLA_NESTED },
};
static int strset_parse_request(struct ethnl_req_info *req_base,
struct nlattr **tb,
struct netlink_ext_ack *extack)
{
struct strset_req_info *req_info = STRSET_REQINFO(req_base);
struct nlattr *nest = tb[ETHTOOL_A_STRSET_STRINGSETS];
struct nlattr *attr;
int rem, ret;
if (!nest)
return 0;
ret = nla_validate_nested(nest,
ARRAY_SIZE(strset_stringsets_policy) - 1,
strset_stringsets_policy, extack);
if (ret < 0)
return ret;
req_info->counts_only = tb[ETHTOOL_A_STRSET_COUNTS_ONLY];
nla_for_each_nested(attr, nest, rem) {
u32 id;
if (WARN_ONCE(nla_type(attr) != ETHTOOL_A_STRINGSETS_STRINGSET,
"unexpected attrtype %u in ETHTOOL_A_STRSET_STRINGSETS\n",
nla_type(attr)))
return -EINVAL;
ret = strset_get_id(attr, &id, extack);
if (ret < 0)
return ret;
if (id >= ETH_SS_COUNT) {
NL_SET_ERR_MSG_ATTR(extack, attr,
"unknown string set id");
return -EOPNOTSUPP;
}
req_info->req_ids |= (1U << id);
}
return 0;
}
static void strset_cleanup_data(struct ethnl_reply_data *reply_base)
{
struct strset_reply_data *data = STRSET_REPDATA(reply_base);
unsigned int i;
for (i = 0; i < ETH_SS_COUNT; i++)
if (data->sets[i].free_strings) {
kfree(data->sets[i].strings);
data->sets[i].strings = NULL;
data->sets[i].free_strings = false;
}
}
static int strset_prepare_set(struct strset_info *info, struct net_device *dev,
unsigned int id, bool counts_only)
{
const struct ethtool_phy_ops *phy_ops = ethtool_phy_ops;
const struct ethtool_ops *ops = dev->ethtool_ops;
void *strings;
int count, ret;
if (id == ETH_SS_PHY_STATS && dev->phydev &&
!ops->get_ethtool_phy_stats && phy_ops &&
phy_ops->get_sset_count)
ret = phy_ops->get_sset_count(dev->phydev);
else if (ops->get_sset_count && ops->get_strings)
ret = ops->get_sset_count(dev, id);
else
ret = -EOPNOTSUPP;
if (ret <= 0) {
info->count = 0;
return 0;
}
count = ret;
if (!counts_only) {
strings = kcalloc(count, ETH_GSTRING_LEN, GFP_KERNEL);
if (!strings)
return -ENOMEM;
if (id == ETH_SS_PHY_STATS && dev->phydev &&
!ops->get_ethtool_phy_stats && phy_ops &&
phy_ops->get_strings)
phy_ops->get_strings(dev->phydev, strings);
else
ops->get_strings(dev, id, strings);
info->strings = strings;
info->free_strings = true;
}
info->count = count;
return 0;
}
static int strset_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
const struct strset_req_info *req_info = STRSET_REQINFO(req_base);
struct strset_reply_data *data = STRSET_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
unsigned int i;
int ret;
BUILD_BUG_ON(ARRAY_SIZE(info_template) != ETH_SS_COUNT);
memcpy(&data->sets, &info_template, sizeof(data->sets));
if (!dev) {
for (i = 0; i < ETH_SS_COUNT; i++) {
if ((req_info->req_ids & (1U << i)) &&
data->sets[i].per_dev) {
if (info)
GENL_SET_ERR_MSG(info, "requested per device strings without dev");
return -EINVAL;
}
}
return 0;
}
ret = ethnl_ops_begin(dev);
if (ret < 0)
goto err_strset;
for (i = 0; i < ETH_SS_COUNT; i++) {
if (!strset_include(req_info, data, i) ||
!data->sets[i].per_dev)
continue;
ret = strset_prepare_set(&data->sets[i], dev, i,
req_info->counts_only);
if (ret < 0)
goto err_ops;
}
ethnl_ops_complete(dev);
return 0;
err_ops:
ethnl_ops_complete(dev);
err_strset:
strset_cleanup_data(reply_base);
return ret;
}
/* calculate size of ETHTOOL_A_STRSET_STRINGSET nest for one string set */
static int strset_set_size(const struct strset_info *info, bool counts_only)
{
unsigned int len = 0;
unsigned int i;
if (info->count == 0)
return 0;
if (counts_only)
return nla_total_size(2 * nla_total_size(sizeof(u32)));
for (i = 0; i < info->count; i++) {
const char *str = info->strings[i];
/* ETHTOOL_A_STRING_INDEX, ETHTOOL_A_STRING_VALUE, nest */
len += nla_total_size(nla_total_size(sizeof(u32)) +
ethnl_strz_size(str));
}
/* ETHTOOL_A_STRINGSET_ID, ETHTOOL_A_STRINGSET_COUNT */
len = 2 * nla_total_size(sizeof(u32)) + nla_total_size(len);
return nla_total_size(len);
}
static int strset_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct strset_req_info *req_info = STRSET_REQINFO(req_base);
const struct strset_reply_data *data = STRSET_REPDATA(reply_base);
unsigned int i;
int len = 0;
int ret;
len += nla_total_size(0); /* ETHTOOL_A_STRSET_STRINGSETS */
for (i = 0; i < ETH_SS_COUNT; i++) {
const struct strset_info *set_info = &data->sets[i];
if (!strset_include(req_info, data, i))
continue;
ret = strset_set_size(set_info, req_info->counts_only);
if (ret < 0)
return ret;
len += ret;
}
return len;
}
/* fill one string into reply */
static int strset_fill_string(struct sk_buff *skb,
const struct strset_info *set_info, u32 idx)
{
struct nlattr *string_attr;
const char *value;
value = set_info->strings[idx];
string_attr = nla_nest_start(skb, ETHTOOL_A_STRINGS_STRING);
if (!string_attr)
return -EMSGSIZE;
if (nla_put_u32(skb, ETHTOOL_A_STRING_INDEX, idx) ||
ethnl_put_strz(skb, ETHTOOL_A_STRING_VALUE, value))
goto nla_put_failure;
nla_nest_end(skb, string_attr);
return 0;
nla_put_failure:
nla_nest_cancel(skb, string_attr);
return -EMSGSIZE;
}
/* fill one string set into reply */
static int strset_fill_set(struct sk_buff *skb,
const struct strset_info *set_info, u32 id,
bool counts_only)
{
struct nlattr *stringset_attr;
struct nlattr *strings_attr;
unsigned int i;
if (!set_info->per_dev && !set_info->strings)
return -EOPNOTSUPP;
if (set_info->count == 0)
return 0;
stringset_attr = nla_nest_start(skb, ETHTOOL_A_STRINGSETS_STRINGSET);
if (!stringset_attr)
return -EMSGSIZE;
if (nla_put_u32(skb, ETHTOOL_A_STRINGSET_ID, id) ||
nla_put_u32(skb, ETHTOOL_A_STRINGSET_COUNT, set_info->count))
goto nla_put_failure;
if (!counts_only) {
strings_attr = nla_nest_start(skb, ETHTOOL_A_STRINGSET_STRINGS);
if (!strings_attr)
goto nla_put_failure;
for (i = 0; i < set_info->count; i++) {
if (strset_fill_string(skb, set_info, i) < 0)
goto nla_put_failure;
}
nla_nest_end(skb, strings_attr);
}
nla_nest_end(skb, stringset_attr);
return 0;
nla_put_failure:
nla_nest_cancel(skb, stringset_attr);
return -EMSGSIZE;
}
static int strset_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct strset_req_info *req_info = STRSET_REQINFO(req_base);
const struct strset_reply_data *data = STRSET_REPDATA(reply_base);
struct nlattr *nest;
unsigned int i;
int ret;
nest = nla_nest_start(skb, ETHTOOL_A_STRSET_STRINGSETS);
if (!nest)
return -EMSGSIZE;
for (i = 0; i < ETH_SS_COUNT; i++) {
if (strset_include(req_info, data, i)) {
ret = strset_fill_set(skb, &data->sets[i], i,
req_info->counts_only);
if (ret < 0)
goto nla_put_failure;
}
}
nla_nest_end(skb, nest);
return 0;
nla_put_failure:
nla_nest_cancel(skb, nest);
return ret;
}
const struct ethnl_request_ops ethnl_strset_request_ops = {
.request_cmd = ETHTOOL_MSG_STRSET_GET,
.reply_cmd = ETHTOOL_MSG_STRSET_GET_REPLY,
.hdr_attr = ETHTOOL_A_STRSET_HEADER,
.req_info_size = sizeof(struct strset_req_info),
.reply_data_size = sizeof(struct strset_reply_data),
.allow_nodev_do = true,
.parse_request = strset_parse_request,
.prepare_data = strset_prepare_data,
.reply_size = strset_reply_size,
.fill_reply = strset_fill_reply,
.cleanup_data = strset_cleanup_data,
};
| linux-master | net/ethtool/strset.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
#include "bitset.h"
#define EEE_MODES_COUNT \
(sizeof_field(struct ethtool_eee, supported) * BITS_PER_BYTE)
struct eee_req_info {
struct ethnl_req_info base;
};
struct eee_reply_data {
struct ethnl_reply_data base;
struct ethtool_eee eee;
};
#define EEE_REPDATA(__reply_base) \
container_of(__reply_base, struct eee_reply_data, base)
const struct nla_policy ethnl_eee_get_policy[] = {
[ETHTOOL_A_EEE_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int eee_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct eee_reply_data *data = EEE_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
if (!dev->ethtool_ops->get_eee)
return -EOPNOTSUPP;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
ret = dev->ethtool_ops->get_eee(dev, &data->eee);
ethnl_ops_complete(dev);
return ret;
}
static int eee_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const struct eee_reply_data *data = EEE_REPDATA(reply_base);
const struct ethtool_eee *eee = &data->eee;
int len = 0;
int ret;
BUILD_BUG_ON(sizeof(eee->advertised) * BITS_PER_BYTE !=
EEE_MODES_COUNT);
BUILD_BUG_ON(sizeof(eee->lp_advertised) * BITS_PER_BYTE !=
EEE_MODES_COUNT);
/* MODES_OURS */
ret = ethnl_bitset32_size(&eee->advertised, &eee->supported,
EEE_MODES_COUNT, link_mode_names, compact);
if (ret < 0)
return ret;
len += ret;
/* MODES_PEERS */
ret = ethnl_bitset32_size(&eee->lp_advertised, NULL,
EEE_MODES_COUNT, link_mode_names, compact);
if (ret < 0)
return ret;
len += ret;
len += nla_total_size(sizeof(u8)) + /* _EEE_ACTIVE */
nla_total_size(sizeof(u8)) + /* _EEE_ENABLED */
nla_total_size(sizeof(u8)) + /* _EEE_TX_LPI_ENABLED */
nla_total_size(sizeof(u32)); /* _EEE_TX_LPI_TIMER */
return len;
}
static int eee_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const struct eee_reply_data *data = EEE_REPDATA(reply_base);
const struct ethtool_eee *eee = &data->eee;
int ret;
ret = ethnl_put_bitset32(skb, ETHTOOL_A_EEE_MODES_OURS,
&eee->advertised, &eee->supported,
EEE_MODES_COUNT, link_mode_names, compact);
if (ret < 0)
return ret;
ret = ethnl_put_bitset32(skb, ETHTOOL_A_EEE_MODES_PEER,
&eee->lp_advertised, NULL, EEE_MODES_COUNT,
link_mode_names, compact);
if (ret < 0)
return ret;
if (nla_put_u8(skb, ETHTOOL_A_EEE_ACTIVE, !!eee->eee_active) ||
nla_put_u8(skb, ETHTOOL_A_EEE_ENABLED, !!eee->eee_enabled) ||
nla_put_u8(skb, ETHTOOL_A_EEE_TX_LPI_ENABLED,
!!eee->tx_lpi_enabled) ||
nla_put_u32(skb, ETHTOOL_A_EEE_TX_LPI_TIMER, eee->tx_lpi_timer))
return -EMSGSIZE;
return 0;
}
/* EEE_SET */
const struct nla_policy ethnl_eee_set_policy[] = {
[ETHTOOL_A_EEE_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_EEE_MODES_OURS] = { .type = NLA_NESTED },
[ETHTOOL_A_EEE_ENABLED] = { .type = NLA_U8 },
[ETHTOOL_A_EEE_TX_LPI_ENABLED] = { .type = NLA_U8 },
[ETHTOOL_A_EEE_TX_LPI_TIMER] = { .type = NLA_U32 },
};
static int
ethnl_set_eee_validate(struct ethnl_req_info *req_info, struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
return ops->get_eee && ops->set_eee ? 1 : -EOPNOTSUPP;
}
static int
ethnl_set_eee(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct net_device *dev = req_info->dev;
struct nlattr **tb = info->attrs;
struct ethtool_eee eee = {};
bool mod = false;
int ret;
ret = dev->ethtool_ops->get_eee(dev, &eee);
if (ret < 0)
return ret;
ret = ethnl_update_bitset32(&eee.advertised, EEE_MODES_COUNT,
tb[ETHTOOL_A_EEE_MODES_OURS],
link_mode_names, info->extack, &mod);
if (ret < 0)
return ret;
ethnl_update_bool32(&eee.eee_enabled, tb[ETHTOOL_A_EEE_ENABLED], &mod);
ethnl_update_bool32(&eee.tx_lpi_enabled,
tb[ETHTOOL_A_EEE_TX_LPI_ENABLED], &mod);
ethnl_update_u32(&eee.tx_lpi_timer, tb[ETHTOOL_A_EEE_TX_LPI_TIMER],
&mod);
if (!mod)
return 0;
ret = dev->ethtool_ops->set_eee(dev, &eee);
return ret < 0 ? ret : 1;
}
const struct ethnl_request_ops ethnl_eee_request_ops = {
.request_cmd = ETHTOOL_MSG_EEE_GET,
.reply_cmd = ETHTOOL_MSG_EEE_GET_REPLY,
.hdr_attr = ETHTOOL_A_EEE_HEADER,
.req_info_size = sizeof(struct eee_req_info),
.reply_data_size = sizeof(struct eee_reply_data),
.prepare_data = eee_prepare_data,
.reply_size = eee_reply_size,
.fill_reply = eee_fill_reply,
.set_validate = ethnl_set_eee_validate,
.set = ethnl_set_eee,
.set_ntf_cmd = ETHTOOL_MSG_EEE_NTF,
};
| linux-master | net/ethtool/eee.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/ethtool_netlink.h>
#include <linux/net_tstamp.h>
#include <linux/phy.h>
#include <linux/rtnetlink.h>
#include <linux/ptp_clock_kernel.h>
#include "common.h"
const char netdev_features_strings[NETDEV_FEATURE_COUNT][ETH_GSTRING_LEN] = {
[NETIF_F_SG_BIT] = "tx-scatter-gather",
[NETIF_F_IP_CSUM_BIT] = "tx-checksum-ipv4",
[NETIF_F_HW_CSUM_BIT] = "tx-checksum-ip-generic",
[NETIF_F_IPV6_CSUM_BIT] = "tx-checksum-ipv6",
[NETIF_F_HIGHDMA_BIT] = "highdma",
[NETIF_F_FRAGLIST_BIT] = "tx-scatter-gather-fraglist",
[NETIF_F_HW_VLAN_CTAG_TX_BIT] = "tx-vlan-hw-insert",
[NETIF_F_HW_VLAN_CTAG_RX_BIT] = "rx-vlan-hw-parse",
[NETIF_F_HW_VLAN_CTAG_FILTER_BIT] = "rx-vlan-filter",
[NETIF_F_HW_VLAN_STAG_TX_BIT] = "tx-vlan-stag-hw-insert",
[NETIF_F_HW_VLAN_STAG_RX_BIT] = "rx-vlan-stag-hw-parse",
[NETIF_F_HW_VLAN_STAG_FILTER_BIT] = "rx-vlan-stag-filter",
[NETIF_F_VLAN_CHALLENGED_BIT] = "vlan-challenged",
[NETIF_F_GSO_BIT] = "tx-generic-segmentation",
[NETIF_F_LLTX_BIT] = "tx-lockless",
[NETIF_F_NETNS_LOCAL_BIT] = "netns-local",
[NETIF_F_GRO_BIT] = "rx-gro",
[NETIF_F_GRO_HW_BIT] = "rx-gro-hw",
[NETIF_F_LRO_BIT] = "rx-lro",
[NETIF_F_TSO_BIT] = "tx-tcp-segmentation",
[NETIF_F_GSO_ROBUST_BIT] = "tx-gso-robust",
[NETIF_F_TSO_ECN_BIT] = "tx-tcp-ecn-segmentation",
[NETIF_F_TSO_MANGLEID_BIT] = "tx-tcp-mangleid-segmentation",
[NETIF_F_TSO6_BIT] = "tx-tcp6-segmentation",
[NETIF_F_FSO_BIT] = "tx-fcoe-segmentation",
[NETIF_F_GSO_GRE_BIT] = "tx-gre-segmentation",
[NETIF_F_GSO_GRE_CSUM_BIT] = "tx-gre-csum-segmentation",
[NETIF_F_GSO_IPXIP4_BIT] = "tx-ipxip4-segmentation",
[NETIF_F_GSO_IPXIP6_BIT] = "tx-ipxip6-segmentation",
[NETIF_F_GSO_UDP_TUNNEL_BIT] = "tx-udp_tnl-segmentation",
[NETIF_F_GSO_UDP_TUNNEL_CSUM_BIT] = "tx-udp_tnl-csum-segmentation",
[NETIF_F_GSO_PARTIAL_BIT] = "tx-gso-partial",
[NETIF_F_GSO_TUNNEL_REMCSUM_BIT] = "tx-tunnel-remcsum-segmentation",
[NETIF_F_GSO_SCTP_BIT] = "tx-sctp-segmentation",
[NETIF_F_GSO_ESP_BIT] = "tx-esp-segmentation",
[NETIF_F_GSO_UDP_L4_BIT] = "tx-udp-segmentation",
[NETIF_F_GSO_FRAGLIST_BIT] = "tx-gso-list",
[NETIF_F_FCOE_CRC_BIT] = "tx-checksum-fcoe-crc",
[NETIF_F_SCTP_CRC_BIT] = "tx-checksum-sctp",
[NETIF_F_FCOE_MTU_BIT] = "fcoe-mtu",
[NETIF_F_NTUPLE_BIT] = "rx-ntuple-filter",
[NETIF_F_RXHASH_BIT] = "rx-hashing",
[NETIF_F_RXCSUM_BIT] = "rx-checksum",
[NETIF_F_NOCACHE_COPY_BIT] = "tx-nocache-copy",
[NETIF_F_LOOPBACK_BIT] = "loopback",
[NETIF_F_RXFCS_BIT] = "rx-fcs",
[NETIF_F_RXALL_BIT] = "rx-all",
[NETIF_F_HW_L2FW_DOFFLOAD_BIT] = "l2-fwd-offload",
[NETIF_F_HW_TC_BIT] = "hw-tc-offload",
[NETIF_F_HW_ESP_BIT] = "esp-hw-offload",
[NETIF_F_HW_ESP_TX_CSUM_BIT] = "esp-tx-csum-hw-offload",
[NETIF_F_RX_UDP_TUNNEL_PORT_BIT] = "rx-udp_tunnel-port-offload",
[NETIF_F_HW_TLS_RECORD_BIT] = "tls-hw-record",
[NETIF_F_HW_TLS_TX_BIT] = "tls-hw-tx-offload",
[NETIF_F_HW_TLS_RX_BIT] = "tls-hw-rx-offload",
[NETIF_F_GRO_FRAGLIST_BIT] = "rx-gro-list",
[NETIF_F_HW_MACSEC_BIT] = "macsec-hw-offload",
[NETIF_F_GRO_UDP_FWD_BIT] = "rx-udp-gro-forwarding",
[NETIF_F_HW_HSR_TAG_INS_BIT] = "hsr-tag-ins-offload",
[NETIF_F_HW_HSR_TAG_RM_BIT] = "hsr-tag-rm-offload",
[NETIF_F_HW_HSR_FWD_BIT] = "hsr-fwd-offload",
[NETIF_F_HW_HSR_DUP_BIT] = "hsr-dup-offload",
};
const char
rss_hash_func_strings[ETH_RSS_HASH_FUNCS_COUNT][ETH_GSTRING_LEN] = {
[ETH_RSS_HASH_TOP_BIT] = "toeplitz",
[ETH_RSS_HASH_XOR_BIT] = "xor",
[ETH_RSS_HASH_CRC32_BIT] = "crc32",
};
const char
tunable_strings[__ETHTOOL_TUNABLE_COUNT][ETH_GSTRING_LEN] = {
[ETHTOOL_ID_UNSPEC] = "Unspec",
[ETHTOOL_RX_COPYBREAK] = "rx-copybreak",
[ETHTOOL_TX_COPYBREAK] = "tx-copybreak",
[ETHTOOL_PFC_PREVENTION_TOUT] = "pfc-prevention-tout",
[ETHTOOL_TX_COPYBREAK_BUF_SIZE] = "tx-copybreak-buf-size",
};
const char
phy_tunable_strings[__ETHTOOL_PHY_TUNABLE_COUNT][ETH_GSTRING_LEN] = {
[ETHTOOL_ID_UNSPEC] = "Unspec",
[ETHTOOL_PHY_DOWNSHIFT] = "phy-downshift",
[ETHTOOL_PHY_FAST_LINK_DOWN] = "phy-fast-link-down",
[ETHTOOL_PHY_EDPD] = "phy-energy-detect-power-down",
};
#define __LINK_MODE_NAME(speed, type, duplex) \
#speed "base" #type "/" #duplex
#define __DEFINE_LINK_MODE_NAME(speed, type, duplex) \
[ETHTOOL_LINK_MODE(speed, type, duplex)] = \
__LINK_MODE_NAME(speed, type, duplex)
#define __DEFINE_SPECIAL_MODE_NAME(_mode, _name) \
[ETHTOOL_LINK_MODE_ ## _mode ## _BIT] = _name
const char link_mode_names[][ETH_GSTRING_LEN] = {
__DEFINE_LINK_MODE_NAME(10, T, Half),
__DEFINE_LINK_MODE_NAME(10, T, Full),
__DEFINE_LINK_MODE_NAME(100, T, Half),
__DEFINE_LINK_MODE_NAME(100, T, Full),
__DEFINE_LINK_MODE_NAME(1000, T, Half),
__DEFINE_LINK_MODE_NAME(1000, T, Full),
__DEFINE_SPECIAL_MODE_NAME(Autoneg, "Autoneg"),
__DEFINE_SPECIAL_MODE_NAME(TP, "TP"),
__DEFINE_SPECIAL_MODE_NAME(AUI, "AUI"),
__DEFINE_SPECIAL_MODE_NAME(MII, "MII"),
__DEFINE_SPECIAL_MODE_NAME(FIBRE, "FIBRE"),
__DEFINE_SPECIAL_MODE_NAME(BNC, "BNC"),
__DEFINE_LINK_MODE_NAME(10000, T, Full),
__DEFINE_SPECIAL_MODE_NAME(Pause, "Pause"),
__DEFINE_SPECIAL_MODE_NAME(Asym_Pause, "Asym_Pause"),
__DEFINE_LINK_MODE_NAME(2500, X, Full),
__DEFINE_SPECIAL_MODE_NAME(Backplane, "Backplane"),
__DEFINE_LINK_MODE_NAME(1000, KX, Full),
__DEFINE_LINK_MODE_NAME(10000, KX4, Full),
__DEFINE_LINK_MODE_NAME(10000, KR, Full),
__DEFINE_SPECIAL_MODE_NAME(10000baseR_FEC, "10000baseR_FEC"),
__DEFINE_LINK_MODE_NAME(20000, MLD2, Full),
__DEFINE_LINK_MODE_NAME(20000, KR2, Full),
__DEFINE_LINK_MODE_NAME(40000, KR4, Full),
__DEFINE_LINK_MODE_NAME(40000, CR4, Full),
__DEFINE_LINK_MODE_NAME(40000, SR4, Full),
__DEFINE_LINK_MODE_NAME(40000, LR4, Full),
__DEFINE_LINK_MODE_NAME(56000, KR4, Full),
__DEFINE_LINK_MODE_NAME(56000, CR4, Full),
__DEFINE_LINK_MODE_NAME(56000, SR4, Full),
__DEFINE_LINK_MODE_NAME(56000, LR4, Full),
__DEFINE_LINK_MODE_NAME(25000, CR, Full),
__DEFINE_LINK_MODE_NAME(25000, KR, Full),
__DEFINE_LINK_MODE_NAME(25000, SR, Full),
__DEFINE_LINK_MODE_NAME(50000, CR2, Full),
__DEFINE_LINK_MODE_NAME(50000, KR2, Full),
__DEFINE_LINK_MODE_NAME(100000, KR4, Full),
__DEFINE_LINK_MODE_NAME(100000, SR4, Full),
__DEFINE_LINK_MODE_NAME(100000, CR4, Full),
__DEFINE_LINK_MODE_NAME(100000, LR4_ER4, Full),
__DEFINE_LINK_MODE_NAME(50000, SR2, Full),
__DEFINE_LINK_MODE_NAME(1000, X, Full),
__DEFINE_LINK_MODE_NAME(10000, CR, Full),
__DEFINE_LINK_MODE_NAME(10000, SR, Full),
__DEFINE_LINK_MODE_NAME(10000, LR, Full),
__DEFINE_LINK_MODE_NAME(10000, LRM, Full),
__DEFINE_LINK_MODE_NAME(10000, ER, Full),
__DEFINE_LINK_MODE_NAME(2500, T, Full),
__DEFINE_LINK_MODE_NAME(5000, T, Full),
__DEFINE_SPECIAL_MODE_NAME(FEC_NONE, "None"),
__DEFINE_SPECIAL_MODE_NAME(FEC_RS, "RS"),
__DEFINE_SPECIAL_MODE_NAME(FEC_BASER, "BASER"),
__DEFINE_LINK_MODE_NAME(50000, KR, Full),
__DEFINE_LINK_MODE_NAME(50000, SR, Full),
__DEFINE_LINK_MODE_NAME(50000, CR, Full),
__DEFINE_LINK_MODE_NAME(50000, LR_ER_FR, Full),
__DEFINE_LINK_MODE_NAME(50000, DR, Full),
__DEFINE_LINK_MODE_NAME(100000, KR2, Full),
__DEFINE_LINK_MODE_NAME(100000, SR2, Full),
__DEFINE_LINK_MODE_NAME(100000, CR2, Full),
__DEFINE_LINK_MODE_NAME(100000, LR2_ER2_FR2, Full),
__DEFINE_LINK_MODE_NAME(100000, DR2, Full),
__DEFINE_LINK_MODE_NAME(200000, KR4, Full),
__DEFINE_LINK_MODE_NAME(200000, SR4, Full),
__DEFINE_LINK_MODE_NAME(200000, LR4_ER4_FR4, Full),
__DEFINE_LINK_MODE_NAME(200000, DR4, Full),
__DEFINE_LINK_MODE_NAME(200000, CR4, Full),
__DEFINE_LINK_MODE_NAME(100, T1, Full),
__DEFINE_LINK_MODE_NAME(1000, T1, Full),
__DEFINE_LINK_MODE_NAME(400000, KR8, Full),
__DEFINE_LINK_MODE_NAME(400000, SR8, Full),
__DEFINE_LINK_MODE_NAME(400000, LR8_ER8_FR8, Full),
__DEFINE_LINK_MODE_NAME(400000, DR8, Full),
__DEFINE_LINK_MODE_NAME(400000, CR8, Full),
__DEFINE_SPECIAL_MODE_NAME(FEC_LLRS, "LLRS"),
__DEFINE_LINK_MODE_NAME(100000, KR, Full),
__DEFINE_LINK_MODE_NAME(100000, SR, Full),
__DEFINE_LINK_MODE_NAME(100000, LR_ER_FR, Full),
__DEFINE_LINK_MODE_NAME(100000, DR, Full),
__DEFINE_LINK_MODE_NAME(100000, CR, Full),
__DEFINE_LINK_MODE_NAME(200000, KR2, Full),
__DEFINE_LINK_MODE_NAME(200000, SR2, Full),
__DEFINE_LINK_MODE_NAME(200000, LR2_ER2_FR2, Full),
__DEFINE_LINK_MODE_NAME(200000, DR2, Full),
__DEFINE_LINK_MODE_NAME(200000, CR2, Full),
__DEFINE_LINK_MODE_NAME(400000, KR4, Full),
__DEFINE_LINK_MODE_NAME(400000, SR4, Full),
__DEFINE_LINK_MODE_NAME(400000, LR4_ER4_FR4, Full),
__DEFINE_LINK_MODE_NAME(400000, DR4, Full),
__DEFINE_LINK_MODE_NAME(400000, CR4, Full),
__DEFINE_LINK_MODE_NAME(100, FX, Half),
__DEFINE_LINK_MODE_NAME(100, FX, Full),
__DEFINE_LINK_MODE_NAME(10, T1L, Full),
__DEFINE_LINK_MODE_NAME(800000, CR8, Full),
__DEFINE_LINK_MODE_NAME(800000, KR8, Full),
__DEFINE_LINK_MODE_NAME(800000, DR8, Full),
__DEFINE_LINK_MODE_NAME(800000, DR8_2, Full),
__DEFINE_LINK_MODE_NAME(800000, SR8, Full),
__DEFINE_LINK_MODE_NAME(800000, VR8, Full),
__DEFINE_LINK_MODE_NAME(10, T1S, Full),
__DEFINE_LINK_MODE_NAME(10, T1S, Half),
__DEFINE_LINK_MODE_NAME(10, T1S_P2MP, Half),
};
static_assert(ARRAY_SIZE(link_mode_names) == __ETHTOOL_LINK_MODE_MASK_NBITS);
#define __LINK_MODE_LANES_CR 1
#define __LINK_MODE_LANES_CR2 2
#define __LINK_MODE_LANES_CR4 4
#define __LINK_MODE_LANES_CR8 8
#define __LINK_MODE_LANES_DR 1
#define __LINK_MODE_LANES_DR2 2
#define __LINK_MODE_LANES_DR4 4
#define __LINK_MODE_LANES_DR8 8
#define __LINK_MODE_LANES_KR 1
#define __LINK_MODE_LANES_KR2 2
#define __LINK_MODE_LANES_KR4 4
#define __LINK_MODE_LANES_KR8 8
#define __LINK_MODE_LANES_SR 1
#define __LINK_MODE_LANES_SR2 2
#define __LINK_MODE_LANES_SR4 4
#define __LINK_MODE_LANES_SR8 8
#define __LINK_MODE_LANES_ER 1
#define __LINK_MODE_LANES_KX 1
#define __LINK_MODE_LANES_KX4 4
#define __LINK_MODE_LANES_LR 1
#define __LINK_MODE_LANES_LR4 4
#define __LINK_MODE_LANES_LR4_ER4 4
#define __LINK_MODE_LANES_LR_ER_FR 1
#define __LINK_MODE_LANES_LR2_ER2_FR2 2
#define __LINK_MODE_LANES_LR4_ER4_FR4 4
#define __LINK_MODE_LANES_LR8_ER8_FR8 8
#define __LINK_MODE_LANES_LRM 1
#define __LINK_MODE_LANES_MLD2 2
#define __LINK_MODE_LANES_T 1
#define __LINK_MODE_LANES_T1 1
#define __LINK_MODE_LANES_X 1
#define __LINK_MODE_LANES_FX 1
#define __LINK_MODE_LANES_T1L 1
#define __LINK_MODE_LANES_T1S 1
#define __LINK_MODE_LANES_T1S_P2MP 1
#define __LINK_MODE_LANES_VR8 8
#define __LINK_MODE_LANES_DR8_2 8
#define __DEFINE_LINK_MODE_PARAMS(_speed, _type, _duplex) \
[ETHTOOL_LINK_MODE(_speed, _type, _duplex)] = { \
.speed = SPEED_ ## _speed, \
.lanes = __LINK_MODE_LANES_ ## _type, \
.duplex = __DUPLEX_ ## _duplex \
}
#define __DUPLEX_Half DUPLEX_HALF
#define __DUPLEX_Full DUPLEX_FULL
#define __DEFINE_SPECIAL_MODE_PARAMS(_mode) \
[ETHTOOL_LINK_MODE_ ## _mode ## _BIT] = { \
.speed = SPEED_UNKNOWN, \
.lanes = 0, \
.duplex = DUPLEX_UNKNOWN, \
}
const struct link_mode_info link_mode_params[] = {
__DEFINE_LINK_MODE_PARAMS(10, T, Half),
__DEFINE_LINK_MODE_PARAMS(10, T, Full),
__DEFINE_LINK_MODE_PARAMS(100, T, Half),
__DEFINE_LINK_MODE_PARAMS(100, T, Full),
__DEFINE_LINK_MODE_PARAMS(1000, T, Half),
__DEFINE_LINK_MODE_PARAMS(1000, T, Full),
__DEFINE_SPECIAL_MODE_PARAMS(Autoneg),
__DEFINE_SPECIAL_MODE_PARAMS(TP),
__DEFINE_SPECIAL_MODE_PARAMS(AUI),
__DEFINE_SPECIAL_MODE_PARAMS(MII),
__DEFINE_SPECIAL_MODE_PARAMS(FIBRE),
__DEFINE_SPECIAL_MODE_PARAMS(BNC),
__DEFINE_LINK_MODE_PARAMS(10000, T, Full),
__DEFINE_SPECIAL_MODE_PARAMS(Pause),
__DEFINE_SPECIAL_MODE_PARAMS(Asym_Pause),
__DEFINE_LINK_MODE_PARAMS(2500, X, Full),
__DEFINE_SPECIAL_MODE_PARAMS(Backplane),
__DEFINE_LINK_MODE_PARAMS(1000, KX, Full),
__DEFINE_LINK_MODE_PARAMS(10000, KX4, Full),
__DEFINE_LINK_MODE_PARAMS(10000, KR, Full),
[ETHTOOL_LINK_MODE_10000baseR_FEC_BIT] = {
.speed = SPEED_10000,
.lanes = 1,
.duplex = DUPLEX_FULL,
},
__DEFINE_LINK_MODE_PARAMS(20000, MLD2, Full),
__DEFINE_LINK_MODE_PARAMS(20000, KR2, Full),
__DEFINE_LINK_MODE_PARAMS(40000, KR4, Full),
__DEFINE_LINK_MODE_PARAMS(40000, CR4, Full),
__DEFINE_LINK_MODE_PARAMS(40000, SR4, Full),
__DEFINE_LINK_MODE_PARAMS(40000, LR4, Full),
__DEFINE_LINK_MODE_PARAMS(56000, KR4, Full),
__DEFINE_LINK_MODE_PARAMS(56000, CR4, Full),
__DEFINE_LINK_MODE_PARAMS(56000, SR4, Full),
__DEFINE_LINK_MODE_PARAMS(56000, LR4, Full),
__DEFINE_LINK_MODE_PARAMS(25000, CR, Full),
__DEFINE_LINK_MODE_PARAMS(25000, KR, Full),
__DEFINE_LINK_MODE_PARAMS(25000, SR, Full),
__DEFINE_LINK_MODE_PARAMS(50000, CR2, Full),
__DEFINE_LINK_MODE_PARAMS(50000, KR2, Full),
__DEFINE_LINK_MODE_PARAMS(100000, KR4, Full),
__DEFINE_LINK_MODE_PARAMS(100000, SR4, Full),
__DEFINE_LINK_MODE_PARAMS(100000, CR4, Full),
__DEFINE_LINK_MODE_PARAMS(100000, LR4_ER4, Full),
__DEFINE_LINK_MODE_PARAMS(50000, SR2, Full),
__DEFINE_LINK_MODE_PARAMS(1000, X, Full),
__DEFINE_LINK_MODE_PARAMS(10000, CR, Full),
__DEFINE_LINK_MODE_PARAMS(10000, SR, Full),
__DEFINE_LINK_MODE_PARAMS(10000, LR, Full),
__DEFINE_LINK_MODE_PARAMS(10000, LRM, Full),
__DEFINE_LINK_MODE_PARAMS(10000, ER, Full),
__DEFINE_LINK_MODE_PARAMS(2500, T, Full),
__DEFINE_LINK_MODE_PARAMS(5000, T, Full),
__DEFINE_SPECIAL_MODE_PARAMS(FEC_NONE),
__DEFINE_SPECIAL_MODE_PARAMS(FEC_RS),
__DEFINE_SPECIAL_MODE_PARAMS(FEC_BASER),
__DEFINE_LINK_MODE_PARAMS(50000, KR, Full),
__DEFINE_LINK_MODE_PARAMS(50000, SR, Full),
__DEFINE_LINK_MODE_PARAMS(50000, CR, Full),
__DEFINE_LINK_MODE_PARAMS(50000, LR_ER_FR, Full),
__DEFINE_LINK_MODE_PARAMS(50000, DR, Full),
__DEFINE_LINK_MODE_PARAMS(100000, KR2, Full),
__DEFINE_LINK_MODE_PARAMS(100000, SR2, Full),
__DEFINE_LINK_MODE_PARAMS(100000, CR2, Full),
__DEFINE_LINK_MODE_PARAMS(100000, LR2_ER2_FR2, Full),
__DEFINE_LINK_MODE_PARAMS(100000, DR2, Full),
__DEFINE_LINK_MODE_PARAMS(200000, KR4, Full),
__DEFINE_LINK_MODE_PARAMS(200000, SR4, Full),
__DEFINE_LINK_MODE_PARAMS(200000, LR4_ER4_FR4, Full),
__DEFINE_LINK_MODE_PARAMS(200000, DR4, Full),
__DEFINE_LINK_MODE_PARAMS(200000, CR4, Full),
__DEFINE_LINK_MODE_PARAMS(100, T1, Full),
__DEFINE_LINK_MODE_PARAMS(1000, T1, Full),
__DEFINE_LINK_MODE_PARAMS(400000, KR8, Full),
__DEFINE_LINK_MODE_PARAMS(400000, SR8, Full),
__DEFINE_LINK_MODE_PARAMS(400000, LR8_ER8_FR8, Full),
__DEFINE_LINK_MODE_PARAMS(400000, DR8, Full),
__DEFINE_LINK_MODE_PARAMS(400000, CR8, Full),
__DEFINE_SPECIAL_MODE_PARAMS(FEC_LLRS),
__DEFINE_LINK_MODE_PARAMS(100000, KR, Full),
__DEFINE_LINK_MODE_PARAMS(100000, SR, Full),
__DEFINE_LINK_MODE_PARAMS(100000, LR_ER_FR, Full),
__DEFINE_LINK_MODE_PARAMS(100000, DR, Full),
__DEFINE_LINK_MODE_PARAMS(100000, CR, Full),
__DEFINE_LINK_MODE_PARAMS(200000, KR2, Full),
__DEFINE_LINK_MODE_PARAMS(200000, SR2, Full),
__DEFINE_LINK_MODE_PARAMS(200000, LR2_ER2_FR2, Full),
__DEFINE_LINK_MODE_PARAMS(200000, DR2, Full),
__DEFINE_LINK_MODE_PARAMS(200000, CR2, Full),
__DEFINE_LINK_MODE_PARAMS(400000, KR4, Full),
__DEFINE_LINK_MODE_PARAMS(400000, SR4, Full),
__DEFINE_LINK_MODE_PARAMS(400000, LR4_ER4_FR4, Full),
__DEFINE_LINK_MODE_PARAMS(400000, DR4, Full),
__DEFINE_LINK_MODE_PARAMS(400000, CR4, Full),
__DEFINE_LINK_MODE_PARAMS(100, FX, Half),
__DEFINE_LINK_MODE_PARAMS(100, FX, Full),
__DEFINE_LINK_MODE_PARAMS(10, T1L, Full),
__DEFINE_LINK_MODE_PARAMS(800000, CR8, Full),
__DEFINE_LINK_MODE_PARAMS(800000, KR8, Full),
__DEFINE_LINK_MODE_PARAMS(800000, DR8, Full),
__DEFINE_LINK_MODE_PARAMS(800000, DR8_2, Full),
__DEFINE_LINK_MODE_PARAMS(800000, SR8, Full),
__DEFINE_LINK_MODE_PARAMS(800000, VR8, Full),
__DEFINE_LINK_MODE_PARAMS(10, T1S, Full),
__DEFINE_LINK_MODE_PARAMS(10, T1S, Half),
__DEFINE_LINK_MODE_PARAMS(10, T1S_P2MP, Half),
};
static_assert(ARRAY_SIZE(link_mode_params) == __ETHTOOL_LINK_MODE_MASK_NBITS);
const char netif_msg_class_names[][ETH_GSTRING_LEN] = {
[NETIF_MSG_DRV_BIT] = "drv",
[NETIF_MSG_PROBE_BIT] = "probe",
[NETIF_MSG_LINK_BIT] = "link",
[NETIF_MSG_TIMER_BIT] = "timer",
[NETIF_MSG_IFDOWN_BIT] = "ifdown",
[NETIF_MSG_IFUP_BIT] = "ifup",
[NETIF_MSG_RX_ERR_BIT] = "rx_err",
[NETIF_MSG_TX_ERR_BIT] = "tx_err",
[NETIF_MSG_TX_QUEUED_BIT] = "tx_queued",
[NETIF_MSG_INTR_BIT] = "intr",
[NETIF_MSG_TX_DONE_BIT] = "tx_done",
[NETIF_MSG_RX_STATUS_BIT] = "rx_status",
[NETIF_MSG_PKTDATA_BIT] = "pktdata",
[NETIF_MSG_HW_BIT] = "hw",
[NETIF_MSG_WOL_BIT] = "wol",
};
static_assert(ARRAY_SIZE(netif_msg_class_names) == NETIF_MSG_CLASS_COUNT);
const char wol_mode_names[][ETH_GSTRING_LEN] = {
[const_ilog2(WAKE_PHY)] = "phy",
[const_ilog2(WAKE_UCAST)] = "ucast",
[const_ilog2(WAKE_MCAST)] = "mcast",
[const_ilog2(WAKE_BCAST)] = "bcast",
[const_ilog2(WAKE_ARP)] = "arp",
[const_ilog2(WAKE_MAGIC)] = "magic",
[const_ilog2(WAKE_MAGICSECURE)] = "magicsecure",
[const_ilog2(WAKE_FILTER)] = "filter",
};
static_assert(ARRAY_SIZE(wol_mode_names) == WOL_MODE_COUNT);
const char sof_timestamping_names[][ETH_GSTRING_LEN] = {
[const_ilog2(SOF_TIMESTAMPING_TX_HARDWARE)] = "hardware-transmit",
[const_ilog2(SOF_TIMESTAMPING_TX_SOFTWARE)] = "software-transmit",
[const_ilog2(SOF_TIMESTAMPING_RX_HARDWARE)] = "hardware-receive",
[const_ilog2(SOF_TIMESTAMPING_RX_SOFTWARE)] = "software-receive",
[const_ilog2(SOF_TIMESTAMPING_SOFTWARE)] = "software-system-clock",
[const_ilog2(SOF_TIMESTAMPING_SYS_HARDWARE)] = "hardware-legacy-clock",
[const_ilog2(SOF_TIMESTAMPING_RAW_HARDWARE)] = "hardware-raw-clock",
[const_ilog2(SOF_TIMESTAMPING_OPT_ID)] = "option-id",
[const_ilog2(SOF_TIMESTAMPING_TX_SCHED)] = "sched-transmit",
[const_ilog2(SOF_TIMESTAMPING_TX_ACK)] = "ack-transmit",
[const_ilog2(SOF_TIMESTAMPING_OPT_CMSG)] = "option-cmsg",
[const_ilog2(SOF_TIMESTAMPING_OPT_TSONLY)] = "option-tsonly",
[const_ilog2(SOF_TIMESTAMPING_OPT_STATS)] = "option-stats",
[const_ilog2(SOF_TIMESTAMPING_OPT_PKTINFO)] = "option-pktinfo",
[const_ilog2(SOF_TIMESTAMPING_OPT_TX_SWHW)] = "option-tx-swhw",
[const_ilog2(SOF_TIMESTAMPING_BIND_PHC)] = "bind-phc",
[const_ilog2(SOF_TIMESTAMPING_OPT_ID_TCP)] = "option-id-tcp",
};
static_assert(ARRAY_SIZE(sof_timestamping_names) == __SOF_TIMESTAMPING_CNT);
const char ts_tx_type_names[][ETH_GSTRING_LEN] = {
[HWTSTAMP_TX_OFF] = "off",
[HWTSTAMP_TX_ON] = "on",
[HWTSTAMP_TX_ONESTEP_SYNC] = "onestep-sync",
[HWTSTAMP_TX_ONESTEP_P2P] = "onestep-p2p",
};
static_assert(ARRAY_SIZE(ts_tx_type_names) == __HWTSTAMP_TX_CNT);
const char ts_rx_filter_names[][ETH_GSTRING_LEN] = {
[HWTSTAMP_FILTER_NONE] = "none",
[HWTSTAMP_FILTER_ALL] = "all",
[HWTSTAMP_FILTER_SOME] = "some",
[HWTSTAMP_FILTER_PTP_V1_L4_EVENT] = "ptpv1-l4-event",
[HWTSTAMP_FILTER_PTP_V1_L4_SYNC] = "ptpv1-l4-sync",
[HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ] = "ptpv1-l4-delay-req",
[HWTSTAMP_FILTER_PTP_V2_L4_EVENT] = "ptpv2-l4-event",
[HWTSTAMP_FILTER_PTP_V2_L4_SYNC] = "ptpv2-l4-sync",
[HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ] = "ptpv2-l4-delay-req",
[HWTSTAMP_FILTER_PTP_V2_L2_EVENT] = "ptpv2-l2-event",
[HWTSTAMP_FILTER_PTP_V2_L2_SYNC] = "ptpv2-l2-sync",
[HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ] = "ptpv2-l2-delay-req",
[HWTSTAMP_FILTER_PTP_V2_EVENT] = "ptpv2-event",
[HWTSTAMP_FILTER_PTP_V2_SYNC] = "ptpv2-sync",
[HWTSTAMP_FILTER_PTP_V2_DELAY_REQ] = "ptpv2-delay-req",
[HWTSTAMP_FILTER_NTP_ALL] = "ntp-all",
};
static_assert(ARRAY_SIZE(ts_rx_filter_names) == __HWTSTAMP_FILTER_CNT);
const char udp_tunnel_type_names[][ETH_GSTRING_LEN] = {
[ETHTOOL_UDP_TUNNEL_TYPE_VXLAN] = "vxlan",
[ETHTOOL_UDP_TUNNEL_TYPE_GENEVE] = "geneve",
[ETHTOOL_UDP_TUNNEL_TYPE_VXLAN_GPE] = "vxlan-gpe",
};
static_assert(ARRAY_SIZE(udp_tunnel_type_names) ==
__ETHTOOL_UDP_TUNNEL_TYPE_CNT);
/* return false if legacy contained non-0 deprecated fields
* maxtxpkt/maxrxpkt. rest of ksettings always updated
*/
bool
convert_legacy_settings_to_link_ksettings(
struct ethtool_link_ksettings *link_ksettings,
const struct ethtool_cmd *legacy_settings)
{
bool retval = true;
memset(link_ksettings, 0, sizeof(*link_ksettings));
/* This is used to tell users that driver is still using these
* deprecated legacy fields, and they should not use
* %ETHTOOL_GLINKSETTINGS/%ETHTOOL_SLINKSETTINGS
*/
if (legacy_settings->maxtxpkt ||
legacy_settings->maxrxpkt)
retval = false;
ethtool_convert_legacy_u32_to_link_mode(
link_ksettings->link_modes.supported,
legacy_settings->supported);
ethtool_convert_legacy_u32_to_link_mode(
link_ksettings->link_modes.advertising,
legacy_settings->advertising);
ethtool_convert_legacy_u32_to_link_mode(
link_ksettings->link_modes.lp_advertising,
legacy_settings->lp_advertising);
link_ksettings->base.speed
= ethtool_cmd_speed(legacy_settings);
link_ksettings->base.duplex
= legacy_settings->duplex;
link_ksettings->base.port
= legacy_settings->port;
link_ksettings->base.phy_address
= legacy_settings->phy_address;
link_ksettings->base.autoneg
= legacy_settings->autoneg;
link_ksettings->base.mdio_support
= legacy_settings->mdio_support;
link_ksettings->base.eth_tp_mdix
= legacy_settings->eth_tp_mdix;
link_ksettings->base.eth_tp_mdix_ctrl
= legacy_settings->eth_tp_mdix_ctrl;
return retval;
}
int __ethtool_get_link(struct net_device *dev)
{
if (!dev->ethtool_ops->get_link)
return -EOPNOTSUPP;
return netif_running(dev) && dev->ethtool_ops->get_link(dev);
}
static int ethtool_get_rxnfc_rule_count(struct net_device *dev)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct ethtool_rxnfc info = {
.cmd = ETHTOOL_GRXCLSRLCNT,
};
int err;
err = ops->get_rxnfc(dev, &info, NULL);
if (err)
return err;
return info.rule_cnt;
}
int ethtool_get_max_rxnfc_channel(struct net_device *dev, u64 *max)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct ethtool_rxnfc *info;
int err, i, rule_cnt;
u64 max_ring = 0;
if (!ops->get_rxnfc)
return -EOPNOTSUPP;
rule_cnt = ethtool_get_rxnfc_rule_count(dev);
if (rule_cnt <= 0)
return -EINVAL;
info = kvzalloc(struct_size(info, rule_locs, rule_cnt), GFP_KERNEL);
if (!info)
return -ENOMEM;
info->cmd = ETHTOOL_GRXCLSRLALL;
info->rule_cnt = rule_cnt;
err = ops->get_rxnfc(dev, info, info->rule_locs);
if (err)
goto err_free_info;
for (i = 0; i < rule_cnt; i++) {
struct ethtool_rxnfc rule_info = {
.cmd = ETHTOOL_GRXCLSRULE,
.fs.location = info->rule_locs[i],
};
err = ops->get_rxnfc(dev, &rule_info, NULL);
if (err)
goto err_free_info;
if (rule_info.fs.ring_cookie != RX_CLS_FLOW_DISC &&
rule_info.fs.ring_cookie != RX_CLS_FLOW_WAKE &&
!(rule_info.flow_type & FLOW_RSS) &&
!ethtool_get_flow_spec_ring_vf(rule_info.fs.ring_cookie))
max_ring =
max_t(u64, max_ring, rule_info.fs.ring_cookie);
}
kvfree(info);
*max = max_ring;
return 0;
err_free_info:
kvfree(info);
return err;
}
int ethtool_get_max_rxfh_channel(struct net_device *dev, u32 *max)
{
u32 dev_size, current_max = 0;
u32 *indir;
int ret;
if (!dev->ethtool_ops->get_rxfh_indir_size ||
!dev->ethtool_ops->get_rxfh)
return -EOPNOTSUPP;
dev_size = dev->ethtool_ops->get_rxfh_indir_size(dev);
if (dev_size == 0)
return -EOPNOTSUPP;
indir = kcalloc(dev_size, sizeof(indir[0]), GFP_USER);
if (!indir)
return -ENOMEM;
ret = dev->ethtool_ops->get_rxfh(dev, indir, NULL, NULL);
if (ret)
goto out;
while (dev_size--)
current_max = max(current_max, indir[dev_size]);
*max = current_max;
out:
kfree(indir);
return ret;
}
int ethtool_check_ops(const struct ethtool_ops *ops)
{
if (WARN_ON(ops->set_coalesce && !ops->supported_coalesce_params))
return -EINVAL;
/* NOTE: sufficiently insane drivers may swap ethtool_ops at runtime,
* the fact that ops are checked at registration time does not
* mean the ops attached to a netdev later on are sane.
*/
return 0;
}
int __ethtool_get_ts_info(struct net_device *dev, struct ethtool_ts_info *info)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct phy_device *phydev = dev->phydev;
memset(info, 0, sizeof(*info));
info->cmd = ETHTOOL_GET_TS_INFO;
if (phy_has_tsinfo(phydev))
return phy_ts_info(phydev, info);
if (ops->get_ts_info)
return ops->get_ts_info(dev, info);
info->so_timestamping = SOF_TIMESTAMPING_RX_SOFTWARE |
SOF_TIMESTAMPING_SOFTWARE;
info->phc_index = -1;
return 0;
}
int ethtool_get_phc_vclocks(struct net_device *dev, int **vclock_index)
{
struct ethtool_ts_info info = { };
int num = 0;
if (!__ethtool_get_ts_info(dev, &info))
num = ptp_get_vclocks_index(info.phc_index, vclock_index);
return num;
}
EXPORT_SYMBOL(ethtool_get_phc_vclocks);
const struct ethtool_phy_ops *ethtool_phy_ops;
void ethtool_set_ethtool_phy_ops(const struct ethtool_phy_ops *ops)
{
ASSERT_RTNL();
ethtool_phy_ops = ops;
}
EXPORT_SYMBOL_GPL(ethtool_set_ethtool_phy_ops);
void
ethtool_params_from_link_mode(struct ethtool_link_ksettings *link_ksettings,
enum ethtool_link_mode_bit_indices link_mode)
{
const struct link_mode_info *link_info;
if (WARN_ON_ONCE(link_mode >= __ETHTOOL_LINK_MODE_MASK_NBITS))
return;
link_info = &link_mode_params[link_mode];
link_ksettings->base.speed = link_info->speed;
link_ksettings->lanes = link_info->lanes;
link_ksettings->base.duplex = link_info->duplex;
}
EXPORT_SYMBOL_GPL(ethtool_params_from_link_mode);
| linux-master | net/ethtool/common.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
struct coalesce_req_info {
struct ethnl_req_info base;
};
struct coalesce_reply_data {
struct ethnl_reply_data base;
struct ethtool_coalesce coalesce;
struct kernel_ethtool_coalesce kernel_coalesce;
u32 supported_params;
};
#define COALESCE_REPDATA(__reply_base) \
container_of(__reply_base, struct coalesce_reply_data, base)
#define __SUPPORTED_OFFSET ETHTOOL_A_COALESCE_RX_USECS
static u32 attr_to_mask(unsigned int attr_type)
{
return BIT(attr_type - __SUPPORTED_OFFSET);
}
/* build time check that indices in ethtool_ops::supported_coalesce_params
* match corresponding attribute types with an offset
*/
#define __CHECK_SUPPORTED_OFFSET(x) \
static_assert((ETHTOOL_ ## x) == \
BIT((ETHTOOL_A_ ## x) - __SUPPORTED_OFFSET))
__CHECK_SUPPORTED_OFFSET(COALESCE_RX_USECS);
__CHECK_SUPPORTED_OFFSET(COALESCE_RX_MAX_FRAMES);
__CHECK_SUPPORTED_OFFSET(COALESCE_RX_USECS_IRQ);
__CHECK_SUPPORTED_OFFSET(COALESCE_RX_MAX_FRAMES_IRQ);
__CHECK_SUPPORTED_OFFSET(COALESCE_TX_USECS);
__CHECK_SUPPORTED_OFFSET(COALESCE_TX_MAX_FRAMES);
__CHECK_SUPPORTED_OFFSET(COALESCE_TX_USECS_IRQ);
__CHECK_SUPPORTED_OFFSET(COALESCE_TX_MAX_FRAMES_IRQ);
__CHECK_SUPPORTED_OFFSET(COALESCE_STATS_BLOCK_USECS);
__CHECK_SUPPORTED_OFFSET(COALESCE_USE_ADAPTIVE_RX);
__CHECK_SUPPORTED_OFFSET(COALESCE_USE_ADAPTIVE_TX);
__CHECK_SUPPORTED_OFFSET(COALESCE_PKT_RATE_LOW);
__CHECK_SUPPORTED_OFFSET(COALESCE_RX_USECS_LOW);
__CHECK_SUPPORTED_OFFSET(COALESCE_RX_MAX_FRAMES_LOW);
__CHECK_SUPPORTED_OFFSET(COALESCE_TX_USECS_LOW);
__CHECK_SUPPORTED_OFFSET(COALESCE_TX_MAX_FRAMES_LOW);
__CHECK_SUPPORTED_OFFSET(COALESCE_PKT_RATE_HIGH);
__CHECK_SUPPORTED_OFFSET(COALESCE_RX_USECS_HIGH);
__CHECK_SUPPORTED_OFFSET(COALESCE_RX_MAX_FRAMES_HIGH);
__CHECK_SUPPORTED_OFFSET(COALESCE_TX_USECS_HIGH);
__CHECK_SUPPORTED_OFFSET(COALESCE_TX_MAX_FRAMES_HIGH);
__CHECK_SUPPORTED_OFFSET(COALESCE_RATE_SAMPLE_INTERVAL);
const struct nla_policy ethnl_coalesce_get_policy[] = {
[ETHTOOL_A_COALESCE_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int coalesce_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct coalesce_reply_data *data = COALESCE_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
if (!dev->ethtool_ops->get_coalesce)
return -EOPNOTSUPP;
data->supported_params = dev->ethtool_ops->supported_coalesce_params;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
ret = dev->ethtool_ops->get_coalesce(dev, &data->coalesce,
&data->kernel_coalesce,
info->extack);
ethnl_ops_complete(dev);
return ret;
}
static int coalesce_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
return nla_total_size(sizeof(u32)) + /* _RX_USECS */
nla_total_size(sizeof(u32)) + /* _RX_MAX_FRAMES */
nla_total_size(sizeof(u32)) + /* _RX_USECS_IRQ */
nla_total_size(sizeof(u32)) + /* _RX_MAX_FRAMES_IRQ */
nla_total_size(sizeof(u32)) + /* _TX_USECS */
nla_total_size(sizeof(u32)) + /* _TX_MAX_FRAMES */
nla_total_size(sizeof(u32)) + /* _TX_USECS_IRQ */
nla_total_size(sizeof(u32)) + /* _TX_MAX_FRAMES_IRQ */
nla_total_size(sizeof(u32)) + /* _STATS_BLOCK_USECS */
nla_total_size(sizeof(u8)) + /* _USE_ADAPTIVE_RX */
nla_total_size(sizeof(u8)) + /* _USE_ADAPTIVE_TX */
nla_total_size(sizeof(u32)) + /* _PKT_RATE_LOW */
nla_total_size(sizeof(u32)) + /* _RX_USECS_LOW */
nla_total_size(sizeof(u32)) + /* _RX_MAX_FRAMES_LOW */
nla_total_size(sizeof(u32)) + /* _TX_USECS_LOW */
nla_total_size(sizeof(u32)) + /* _TX_MAX_FRAMES_LOW */
nla_total_size(sizeof(u32)) + /* _PKT_RATE_HIGH */
nla_total_size(sizeof(u32)) + /* _RX_USECS_HIGH */
nla_total_size(sizeof(u32)) + /* _RX_MAX_FRAMES_HIGH */
nla_total_size(sizeof(u32)) + /* _TX_USECS_HIGH */
nla_total_size(sizeof(u32)) + /* _TX_MAX_FRAMES_HIGH */
nla_total_size(sizeof(u32)) + /* _RATE_SAMPLE_INTERVAL */
nla_total_size(sizeof(u8)) + /* _USE_CQE_MODE_TX */
nla_total_size(sizeof(u8)) + /* _USE_CQE_MODE_RX */
nla_total_size(sizeof(u32)) + /* _TX_AGGR_MAX_BYTES */
nla_total_size(sizeof(u32)) + /* _TX_AGGR_MAX_FRAMES */
nla_total_size(sizeof(u32)); /* _TX_AGGR_TIME_USECS */
}
static bool coalesce_put_u32(struct sk_buff *skb, u16 attr_type, u32 val,
u32 supported_params)
{
if (!val && !(supported_params & attr_to_mask(attr_type)))
return false;
return nla_put_u32(skb, attr_type, val);
}
static bool coalesce_put_bool(struct sk_buff *skb, u16 attr_type, u32 val,
u32 supported_params)
{
if (!val && !(supported_params & attr_to_mask(attr_type)))
return false;
return nla_put_u8(skb, attr_type, !!val);
}
static int coalesce_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct coalesce_reply_data *data = COALESCE_REPDATA(reply_base);
const struct kernel_ethtool_coalesce *kcoal = &data->kernel_coalesce;
const struct ethtool_coalesce *coal = &data->coalesce;
u32 supported = data->supported_params;
if (coalesce_put_u32(skb, ETHTOOL_A_COALESCE_RX_USECS,
coal->rx_coalesce_usecs, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_RX_MAX_FRAMES,
coal->rx_max_coalesced_frames, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_RX_USECS_IRQ,
coal->rx_coalesce_usecs_irq, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_RX_MAX_FRAMES_IRQ,
coal->rx_max_coalesced_frames_irq, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_USECS,
coal->tx_coalesce_usecs, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_MAX_FRAMES,
coal->tx_max_coalesced_frames, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_USECS_IRQ,
coal->tx_coalesce_usecs_irq, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_MAX_FRAMES_IRQ,
coal->tx_max_coalesced_frames_irq, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_STATS_BLOCK_USECS,
coal->stats_block_coalesce_usecs, supported) ||
coalesce_put_bool(skb, ETHTOOL_A_COALESCE_USE_ADAPTIVE_RX,
coal->use_adaptive_rx_coalesce, supported) ||
coalesce_put_bool(skb, ETHTOOL_A_COALESCE_USE_ADAPTIVE_TX,
coal->use_adaptive_tx_coalesce, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_PKT_RATE_LOW,
coal->pkt_rate_low, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_RX_USECS_LOW,
coal->rx_coalesce_usecs_low, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_RX_MAX_FRAMES_LOW,
coal->rx_max_coalesced_frames_low, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_USECS_LOW,
coal->tx_coalesce_usecs_low, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_MAX_FRAMES_LOW,
coal->tx_max_coalesced_frames_low, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_PKT_RATE_HIGH,
coal->pkt_rate_high, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_RX_USECS_HIGH,
coal->rx_coalesce_usecs_high, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_RX_MAX_FRAMES_HIGH,
coal->rx_max_coalesced_frames_high, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_USECS_HIGH,
coal->tx_coalesce_usecs_high, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_MAX_FRAMES_HIGH,
coal->tx_max_coalesced_frames_high, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_RATE_SAMPLE_INTERVAL,
coal->rate_sample_interval, supported) ||
coalesce_put_bool(skb, ETHTOOL_A_COALESCE_USE_CQE_MODE_TX,
kcoal->use_cqe_mode_tx, supported) ||
coalesce_put_bool(skb, ETHTOOL_A_COALESCE_USE_CQE_MODE_RX,
kcoal->use_cqe_mode_rx, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_AGGR_MAX_BYTES,
kcoal->tx_aggr_max_bytes, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_AGGR_MAX_FRAMES,
kcoal->tx_aggr_max_frames, supported) ||
coalesce_put_u32(skb, ETHTOOL_A_COALESCE_TX_AGGR_TIME_USECS,
kcoal->tx_aggr_time_usecs, supported))
return -EMSGSIZE;
return 0;
}
/* COALESCE_SET */
const struct nla_policy ethnl_coalesce_set_policy[] = {
[ETHTOOL_A_COALESCE_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_COALESCE_RX_USECS] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_RX_MAX_FRAMES] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_RX_USECS_IRQ] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_RX_MAX_FRAMES_IRQ] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_TX_USECS] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_TX_MAX_FRAMES] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_TX_USECS_IRQ] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_TX_MAX_FRAMES_IRQ] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_STATS_BLOCK_USECS] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_USE_ADAPTIVE_RX] = { .type = NLA_U8 },
[ETHTOOL_A_COALESCE_USE_ADAPTIVE_TX] = { .type = NLA_U8 },
[ETHTOOL_A_COALESCE_PKT_RATE_LOW] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_RX_USECS_LOW] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_RX_MAX_FRAMES_LOW] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_TX_USECS_LOW] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_TX_MAX_FRAMES_LOW] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_PKT_RATE_HIGH] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_RX_USECS_HIGH] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_RX_MAX_FRAMES_HIGH] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_TX_USECS_HIGH] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_TX_MAX_FRAMES_HIGH] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_RATE_SAMPLE_INTERVAL] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_USE_CQE_MODE_TX] = NLA_POLICY_MAX(NLA_U8, 1),
[ETHTOOL_A_COALESCE_USE_CQE_MODE_RX] = NLA_POLICY_MAX(NLA_U8, 1),
[ETHTOOL_A_COALESCE_TX_AGGR_MAX_BYTES] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_TX_AGGR_MAX_FRAMES] = { .type = NLA_U32 },
[ETHTOOL_A_COALESCE_TX_AGGR_TIME_USECS] = { .type = NLA_U32 },
};
static int
ethnl_set_coalesce_validate(struct ethnl_req_info *req_info,
struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
struct nlattr **tb = info->attrs;
u32 supported_params;
u16 a;
if (!ops->get_coalesce || !ops->set_coalesce)
return -EOPNOTSUPP;
/* make sure that only supported parameters are present */
supported_params = ops->supported_coalesce_params;
for (a = ETHTOOL_A_COALESCE_RX_USECS; a < __ETHTOOL_A_COALESCE_CNT; a++)
if (tb[a] && !(supported_params & attr_to_mask(a))) {
NL_SET_ERR_MSG_ATTR(info->extack, tb[a],
"cannot modify an unsupported parameter");
return -EINVAL;
}
return 1;
}
static int
__ethnl_set_coalesce(struct ethnl_req_info *req_info, struct genl_info *info,
bool *dual_change)
{
struct kernel_ethtool_coalesce kernel_coalesce = {};
struct net_device *dev = req_info->dev;
struct ethtool_coalesce coalesce = {};
bool mod_mode = false, mod = false;
struct nlattr **tb = info->attrs;
int ret;
ret = dev->ethtool_ops->get_coalesce(dev, &coalesce, &kernel_coalesce,
info->extack);
if (ret < 0)
return ret;
/* Update values */
ethnl_update_u32(&coalesce.rx_coalesce_usecs,
tb[ETHTOOL_A_COALESCE_RX_USECS], &mod);
ethnl_update_u32(&coalesce.rx_max_coalesced_frames,
tb[ETHTOOL_A_COALESCE_RX_MAX_FRAMES], &mod);
ethnl_update_u32(&coalesce.rx_coalesce_usecs_irq,
tb[ETHTOOL_A_COALESCE_RX_USECS_IRQ], &mod);
ethnl_update_u32(&coalesce.rx_max_coalesced_frames_irq,
tb[ETHTOOL_A_COALESCE_RX_MAX_FRAMES_IRQ], &mod);
ethnl_update_u32(&coalesce.tx_coalesce_usecs,
tb[ETHTOOL_A_COALESCE_TX_USECS], &mod);
ethnl_update_u32(&coalesce.tx_max_coalesced_frames,
tb[ETHTOOL_A_COALESCE_TX_MAX_FRAMES], &mod);
ethnl_update_u32(&coalesce.tx_coalesce_usecs_irq,
tb[ETHTOOL_A_COALESCE_TX_USECS_IRQ], &mod);
ethnl_update_u32(&coalesce.tx_max_coalesced_frames_irq,
tb[ETHTOOL_A_COALESCE_TX_MAX_FRAMES_IRQ], &mod);
ethnl_update_u32(&coalesce.stats_block_coalesce_usecs,
tb[ETHTOOL_A_COALESCE_STATS_BLOCK_USECS], &mod);
ethnl_update_u32(&coalesce.pkt_rate_low,
tb[ETHTOOL_A_COALESCE_PKT_RATE_LOW], &mod);
ethnl_update_u32(&coalesce.rx_coalesce_usecs_low,
tb[ETHTOOL_A_COALESCE_RX_USECS_LOW], &mod);
ethnl_update_u32(&coalesce.rx_max_coalesced_frames_low,
tb[ETHTOOL_A_COALESCE_RX_MAX_FRAMES_LOW], &mod);
ethnl_update_u32(&coalesce.tx_coalesce_usecs_low,
tb[ETHTOOL_A_COALESCE_TX_USECS_LOW], &mod);
ethnl_update_u32(&coalesce.tx_max_coalesced_frames_low,
tb[ETHTOOL_A_COALESCE_TX_MAX_FRAMES_LOW], &mod);
ethnl_update_u32(&coalesce.pkt_rate_high,
tb[ETHTOOL_A_COALESCE_PKT_RATE_HIGH], &mod);
ethnl_update_u32(&coalesce.rx_coalesce_usecs_high,
tb[ETHTOOL_A_COALESCE_RX_USECS_HIGH], &mod);
ethnl_update_u32(&coalesce.rx_max_coalesced_frames_high,
tb[ETHTOOL_A_COALESCE_RX_MAX_FRAMES_HIGH], &mod);
ethnl_update_u32(&coalesce.tx_coalesce_usecs_high,
tb[ETHTOOL_A_COALESCE_TX_USECS_HIGH], &mod);
ethnl_update_u32(&coalesce.tx_max_coalesced_frames_high,
tb[ETHTOOL_A_COALESCE_TX_MAX_FRAMES_HIGH], &mod);
ethnl_update_u32(&coalesce.rate_sample_interval,
tb[ETHTOOL_A_COALESCE_RATE_SAMPLE_INTERVAL], &mod);
ethnl_update_u32(&kernel_coalesce.tx_aggr_max_bytes,
tb[ETHTOOL_A_COALESCE_TX_AGGR_MAX_BYTES], &mod);
ethnl_update_u32(&kernel_coalesce.tx_aggr_max_frames,
tb[ETHTOOL_A_COALESCE_TX_AGGR_MAX_FRAMES], &mod);
ethnl_update_u32(&kernel_coalesce.tx_aggr_time_usecs,
tb[ETHTOOL_A_COALESCE_TX_AGGR_TIME_USECS], &mod);
/* Update operation modes */
ethnl_update_bool32(&coalesce.use_adaptive_rx_coalesce,
tb[ETHTOOL_A_COALESCE_USE_ADAPTIVE_RX], &mod_mode);
ethnl_update_bool32(&coalesce.use_adaptive_tx_coalesce,
tb[ETHTOOL_A_COALESCE_USE_ADAPTIVE_TX], &mod_mode);
ethnl_update_u8(&kernel_coalesce.use_cqe_mode_tx,
tb[ETHTOOL_A_COALESCE_USE_CQE_MODE_TX], &mod_mode);
ethnl_update_u8(&kernel_coalesce.use_cqe_mode_rx,
tb[ETHTOOL_A_COALESCE_USE_CQE_MODE_RX], &mod_mode);
*dual_change = mod && mod_mode;
if (!mod && !mod_mode)
return 0;
ret = dev->ethtool_ops->set_coalesce(dev, &coalesce, &kernel_coalesce,
info->extack);
return ret < 0 ? ret : 1;
}
static int
ethnl_set_coalesce(struct ethnl_req_info *req_info, struct genl_info *info)
{
bool dual_change;
int err, ret;
/* SET_COALESCE may change operation mode and parameters in one call.
* Changing operation mode may cause the driver to reset the parameter
* values, and therefore ignore user input (driver does not know which
* parameters come from user and which are echoed back from ->get).
* To not complicate the drivers if user tries to change both the mode
* and parameters at once - call the driver twice.
*/
err = __ethnl_set_coalesce(req_info, info, &dual_change);
if (err < 0)
return err;
ret = err;
if (ret && dual_change) {
err = __ethnl_set_coalesce(req_info, info, &dual_change);
if (err < 0)
return err;
}
return ret;
}
const struct ethnl_request_ops ethnl_coalesce_request_ops = {
.request_cmd = ETHTOOL_MSG_COALESCE_GET,
.reply_cmd = ETHTOOL_MSG_COALESCE_GET_REPLY,
.hdr_attr = ETHTOOL_A_COALESCE_HEADER,
.req_info_size = sizeof(struct coalesce_req_info),
.reply_data_size = sizeof(struct coalesce_reply_data),
.prepare_data = coalesce_prepare_data,
.reply_size = coalesce_reply_size,
.fill_reply = coalesce_fill_reply,
.set_validate = ethnl_set_coalesce_validate,
.set = ethnl_set_coalesce,
.set_ntf_cmd = ETHTOOL_MSG_COALESCE_NTF,
};
| linux-master | net/ethtool/coalesce.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/net_tstamp.h>
#include "netlink.h"
#include "common.h"
#include "bitset.h"
struct tsinfo_req_info {
struct ethnl_req_info base;
};
struct tsinfo_reply_data {
struct ethnl_reply_data base;
struct ethtool_ts_info ts_info;
};
#define TSINFO_REPDATA(__reply_base) \
container_of(__reply_base, struct tsinfo_reply_data, base)
const struct nla_policy ethnl_tsinfo_get_policy[] = {
[ETHTOOL_A_TSINFO_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int tsinfo_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct tsinfo_reply_data *data = TSINFO_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
ret = __ethtool_get_ts_info(dev, &data->ts_info);
ethnl_ops_complete(dev);
return ret;
}
static int tsinfo_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct tsinfo_reply_data *data = TSINFO_REPDATA(reply_base);
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const struct ethtool_ts_info *ts_info = &data->ts_info;
int len = 0;
int ret;
BUILD_BUG_ON(__SOF_TIMESTAMPING_CNT > 32);
BUILD_BUG_ON(__HWTSTAMP_TX_CNT > 32);
BUILD_BUG_ON(__HWTSTAMP_FILTER_CNT > 32);
if (ts_info->so_timestamping) {
ret = ethnl_bitset32_size(&ts_info->so_timestamping, NULL,
__SOF_TIMESTAMPING_CNT,
sof_timestamping_names, compact);
if (ret < 0)
return ret;
len += ret; /* _TSINFO_TIMESTAMPING */
}
if (ts_info->tx_types) {
ret = ethnl_bitset32_size(&ts_info->tx_types, NULL,
__HWTSTAMP_TX_CNT,
ts_tx_type_names, compact);
if (ret < 0)
return ret;
len += ret; /* _TSINFO_TX_TYPES */
}
if (ts_info->rx_filters) {
ret = ethnl_bitset32_size(&ts_info->rx_filters, NULL,
__HWTSTAMP_FILTER_CNT,
ts_rx_filter_names, compact);
if (ret < 0)
return ret;
len += ret; /* _TSINFO_RX_FILTERS */
}
if (ts_info->phc_index >= 0)
len += nla_total_size(sizeof(u32)); /* _TSINFO_PHC_INDEX */
return len;
}
static int tsinfo_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct tsinfo_reply_data *data = TSINFO_REPDATA(reply_base);
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const struct ethtool_ts_info *ts_info = &data->ts_info;
int ret;
if (ts_info->so_timestamping) {
ret = ethnl_put_bitset32(skb, ETHTOOL_A_TSINFO_TIMESTAMPING,
&ts_info->so_timestamping, NULL,
__SOF_TIMESTAMPING_CNT,
sof_timestamping_names, compact);
if (ret < 0)
return ret;
}
if (ts_info->tx_types) {
ret = ethnl_put_bitset32(skb, ETHTOOL_A_TSINFO_TX_TYPES,
&ts_info->tx_types, NULL,
__HWTSTAMP_TX_CNT,
ts_tx_type_names, compact);
if (ret < 0)
return ret;
}
if (ts_info->rx_filters) {
ret = ethnl_put_bitset32(skb, ETHTOOL_A_TSINFO_RX_FILTERS,
&ts_info->rx_filters, NULL,
__HWTSTAMP_FILTER_CNT,
ts_rx_filter_names, compact);
if (ret < 0)
return ret;
}
if (ts_info->phc_index >= 0 &&
nla_put_u32(skb, ETHTOOL_A_TSINFO_PHC_INDEX, ts_info->phc_index))
return -EMSGSIZE;
return 0;
}
const struct ethnl_request_ops ethnl_tsinfo_request_ops = {
.request_cmd = ETHTOOL_MSG_TSINFO_GET,
.reply_cmd = ETHTOOL_MSG_TSINFO_GET_REPLY,
.hdr_attr = ETHTOOL_A_TSINFO_HEADER,
.req_info_size = sizeof(struct tsinfo_req_info),
.reply_data_size = sizeof(struct tsinfo_reply_data),
.prepare_data = tsinfo_prepare_data,
.reply_size = tsinfo_reply_size,
.fill_reply = tsinfo_fill_reply,
};
| linux-master | net/ethtool/tsinfo.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
#include "bitset.h"
struct wol_req_info {
struct ethnl_req_info base;
};
struct wol_reply_data {
struct ethnl_reply_data base;
struct ethtool_wolinfo wol;
bool show_sopass;
};
#define WOL_REPDATA(__reply_base) \
container_of(__reply_base, struct wol_reply_data, base)
const struct nla_policy ethnl_wol_get_policy[] = {
[ETHTOOL_A_WOL_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int wol_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct wol_reply_data *data = WOL_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
if (!dev->ethtool_ops->get_wol)
return -EOPNOTSUPP;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
dev->ethtool_ops->get_wol(dev, &data->wol);
ethnl_ops_complete(dev);
/* do not include password in notifications */
data->show_sopass = !genl_info_is_ntf(info) &&
(data->wol.supported & WAKE_MAGICSECURE);
return 0;
}
static int wol_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const struct wol_reply_data *data = WOL_REPDATA(reply_base);
int len;
len = ethnl_bitset32_size(&data->wol.wolopts, &data->wol.supported,
WOL_MODE_COUNT, wol_mode_names, compact);
if (len < 0)
return len;
if (data->show_sopass)
len += nla_total_size(sizeof(data->wol.sopass));
return len;
}
static int wol_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const struct wol_reply_data *data = WOL_REPDATA(reply_base);
int ret;
ret = ethnl_put_bitset32(skb, ETHTOOL_A_WOL_MODES, &data->wol.wolopts,
&data->wol.supported, WOL_MODE_COUNT,
wol_mode_names, compact);
if (ret < 0)
return ret;
if (data->show_sopass &&
nla_put(skb, ETHTOOL_A_WOL_SOPASS, sizeof(data->wol.sopass),
data->wol.sopass))
return -EMSGSIZE;
return 0;
}
/* WOL_SET */
const struct nla_policy ethnl_wol_set_policy[] = {
[ETHTOOL_A_WOL_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_WOL_MODES] = { .type = NLA_NESTED },
[ETHTOOL_A_WOL_SOPASS] = { .type = NLA_BINARY,
.len = SOPASS_MAX },
};
static int
ethnl_set_wol_validate(struct ethnl_req_info *req_info, struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
return ops->get_wol && ops->set_wol ? 1 : -EOPNOTSUPP;
}
static int
ethnl_set_wol(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct ethtool_wolinfo wol = { .cmd = ETHTOOL_GWOL };
struct net_device *dev = req_info->dev;
struct nlattr **tb = info->attrs;
bool mod = false;
int ret;
dev->ethtool_ops->get_wol(dev, &wol);
ret = ethnl_update_bitset32(&wol.wolopts, WOL_MODE_COUNT,
tb[ETHTOOL_A_WOL_MODES], wol_mode_names,
info->extack, &mod);
if (ret < 0)
return ret;
if (wol.wolopts & ~wol.supported) {
NL_SET_ERR_MSG_ATTR(info->extack, tb[ETHTOOL_A_WOL_MODES],
"cannot enable unsupported WoL mode");
return -EINVAL;
}
if (tb[ETHTOOL_A_WOL_SOPASS]) {
if (!(wol.supported & WAKE_MAGICSECURE)) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_WOL_SOPASS],
"magicsecure not supported, cannot set password");
return -EINVAL;
}
ethnl_update_binary(wol.sopass, sizeof(wol.sopass),
tb[ETHTOOL_A_WOL_SOPASS], &mod);
}
if (!mod)
return 0;
ret = dev->ethtool_ops->set_wol(dev, &wol);
if (ret)
return ret;
dev->wol_enabled = !!wol.wolopts;
return 1;
}
const struct ethnl_request_ops ethnl_wol_request_ops = {
.request_cmd = ETHTOOL_MSG_WOL_GET,
.reply_cmd = ETHTOOL_MSG_WOL_GET_REPLY,
.hdr_attr = ETHTOOL_A_WOL_HEADER,
.req_info_size = sizeof(struct wol_req_info),
.reply_data_size = sizeof(struct wol_reply_data),
.prepare_data = wol_prepare_data,
.reply_size = wol_reply_size,
.fill_reply = wol_fill_reply,
.set_validate = ethnl_set_wol_validate,
.set = ethnl_set_wol,
.set_ntf_cmd = ETHTOOL_MSG_WOL_NTF,
};
| linux-master | net/ethtool/wol.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
struct rings_req_info {
struct ethnl_req_info base;
};
struct rings_reply_data {
struct ethnl_reply_data base;
struct ethtool_ringparam ringparam;
struct kernel_ethtool_ringparam kernel_ringparam;
u32 supported_ring_params;
};
#define RINGS_REPDATA(__reply_base) \
container_of(__reply_base, struct rings_reply_data, base)
const struct nla_policy ethnl_rings_get_policy[] = {
[ETHTOOL_A_RINGS_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int rings_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct rings_reply_data *data = RINGS_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
if (!dev->ethtool_ops->get_ringparam)
return -EOPNOTSUPP;
data->supported_ring_params = dev->ethtool_ops->supported_ring_params;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
dev->ethtool_ops->get_ringparam(dev, &data->ringparam,
&data->kernel_ringparam, info->extack);
ethnl_ops_complete(dev);
return 0;
}
static int rings_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
return nla_total_size(sizeof(u32)) + /* _RINGS_RX_MAX */
nla_total_size(sizeof(u32)) + /* _RINGS_RX_MINI_MAX */
nla_total_size(sizeof(u32)) + /* _RINGS_RX_JUMBO_MAX */
nla_total_size(sizeof(u32)) + /* _RINGS_TX_MAX */
nla_total_size(sizeof(u32)) + /* _RINGS_RX */
nla_total_size(sizeof(u32)) + /* _RINGS_RX_MINI */
nla_total_size(sizeof(u32)) + /* _RINGS_RX_JUMBO */
nla_total_size(sizeof(u32)) + /* _RINGS_TX */
nla_total_size(sizeof(u32)) + /* _RINGS_RX_BUF_LEN */
nla_total_size(sizeof(u8)) + /* _RINGS_TCP_DATA_SPLIT */
nla_total_size(sizeof(u32) + /* _RINGS_CQE_SIZE */
nla_total_size(sizeof(u8)) + /* _RINGS_TX_PUSH */
nla_total_size(sizeof(u8))) + /* _RINGS_RX_PUSH */
nla_total_size(sizeof(u32)) + /* _RINGS_TX_PUSH_BUF_LEN */
nla_total_size(sizeof(u32)); /* _RINGS_TX_PUSH_BUF_LEN_MAX */
}
static int rings_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct rings_reply_data *data = RINGS_REPDATA(reply_base);
const struct kernel_ethtool_ringparam *kr = &data->kernel_ringparam;
const struct ethtool_ringparam *ringparam = &data->ringparam;
u32 supported_ring_params = data->supported_ring_params;
WARN_ON(kr->tcp_data_split > ETHTOOL_TCP_DATA_SPLIT_ENABLED);
if ((ringparam->rx_max_pending &&
(nla_put_u32(skb, ETHTOOL_A_RINGS_RX_MAX,
ringparam->rx_max_pending) ||
nla_put_u32(skb, ETHTOOL_A_RINGS_RX,
ringparam->rx_pending))) ||
(ringparam->rx_mini_max_pending &&
(nla_put_u32(skb, ETHTOOL_A_RINGS_RX_MINI_MAX,
ringparam->rx_mini_max_pending) ||
nla_put_u32(skb, ETHTOOL_A_RINGS_RX_MINI,
ringparam->rx_mini_pending))) ||
(ringparam->rx_jumbo_max_pending &&
(nla_put_u32(skb, ETHTOOL_A_RINGS_RX_JUMBO_MAX,
ringparam->rx_jumbo_max_pending) ||
nla_put_u32(skb, ETHTOOL_A_RINGS_RX_JUMBO,
ringparam->rx_jumbo_pending))) ||
(ringparam->tx_max_pending &&
(nla_put_u32(skb, ETHTOOL_A_RINGS_TX_MAX,
ringparam->tx_max_pending) ||
nla_put_u32(skb, ETHTOOL_A_RINGS_TX,
ringparam->tx_pending))) ||
(kr->rx_buf_len &&
(nla_put_u32(skb, ETHTOOL_A_RINGS_RX_BUF_LEN, kr->rx_buf_len))) ||
(kr->tcp_data_split &&
(nla_put_u8(skb, ETHTOOL_A_RINGS_TCP_DATA_SPLIT,
kr->tcp_data_split))) ||
(kr->cqe_size &&
(nla_put_u32(skb, ETHTOOL_A_RINGS_CQE_SIZE, kr->cqe_size))) ||
nla_put_u8(skb, ETHTOOL_A_RINGS_TX_PUSH, !!kr->tx_push) ||
nla_put_u8(skb, ETHTOOL_A_RINGS_RX_PUSH, !!kr->rx_push) ||
((supported_ring_params & ETHTOOL_RING_USE_TX_PUSH_BUF_LEN) &&
(nla_put_u32(skb, ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN_MAX,
kr->tx_push_buf_max_len) ||
nla_put_u32(skb, ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN,
kr->tx_push_buf_len))))
return -EMSGSIZE;
return 0;
}
/* RINGS_SET */
const struct nla_policy ethnl_rings_set_policy[] = {
[ETHTOOL_A_RINGS_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_RINGS_RX] = { .type = NLA_U32 },
[ETHTOOL_A_RINGS_RX_MINI] = { .type = NLA_U32 },
[ETHTOOL_A_RINGS_RX_JUMBO] = { .type = NLA_U32 },
[ETHTOOL_A_RINGS_TX] = { .type = NLA_U32 },
[ETHTOOL_A_RINGS_RX_BUF_LEN] = NLA_POLICY_MIN(NLA_U32, 1),
[ETHTOOL_A_RINGS_CQE_SIZE] = NLA_POLICY_MIN(NLA_U32, 1),
[ETHTOOL_A_RINGS_TX_PUSH] = NLA_POLICY_MAX(NLA_U8, 1),
[ETHTOOL_A_RINGS_RX_PUSH] = NLA_POLICY_MAX(NLA_U8, 1),
[ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN] = { .type = NLA_U32 },
};
static int
ethnl_set_rings_validate(struct ethnl_req_info *req_info,
struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
struct nlattr **tb = info->attrs;
if (tb[ETHTOOL_A_RINGS_RX_BUF_LEN] &&
!(ops->supported_ring_params & ETHTOOL_RING_USE_RX_BUF_LEN)) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_RINGS_RX_BUF_LEN],
"setting rx buf len not supported");
return -EOPNOTSUPP;
}
if (tb[ETHTOOL_A_RINGS_CQE_SIZE] &&
!(ops->supported_ring_params & ETHTOOL_RING_USE_CQE_SIZE)) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_RINGS_CQE_SIZE],
"setting cqe size not supported");
return -EOPNOTSUPP;
}
if (tb[ETHTOOL_A_RINGS_TX_PUSH] &&
!(ops->supported_ring_params & ETHTOOL_RING_USE_TX_PUSH)) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_RINGS_TX_PUSH],
"setting tx push not supported");
return -EOPNOTSUPP;
}
if (tb[ETHTOOL_A_RINGS_RX_PUSH] &&
!(ops->supported_ring_params & ETHTOOL_RING_USE_RX_PUSH)) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_RINGS_RX_PUSH],
"setting rx push not supported");
return -EOPNOTSUPP;
}
if (tb[ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN] &&
!(ops->supported_ring_params & ETHTOOL_RING_USE_TX_PUSH_BUF_LEN)) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN],
"setting tx push buf len is not supported");
return -EOPNOTSUPP;
}
return ops->get_ringparam && ops->set_ringparam ? 1 : -EOPNOTSUPP;
}
static int
ethnl_set_rings(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct kernel_ethtool_ringparam kernel_ringparam = {};
struct ethtool_ringparam ringparam = {};
struct net_device *dev = req_info->dev;
struct nlattr **tb = info->attrs;
const struct nlattr *err_attr;
bool mod = false;
int ret;
dev->ethtool_ops->get_ringparam(dev, &ringparam,
&kernel_ringparam, info->extack);
ethnl_update_u32(&ringparam.rx_pending, tb[ETHTOOL_A_RINGS_RX], &mod);
ethnl_update_u32(&ringparam.rx_mini_pending,
tb[ETHTOOL_A_RINGS_RX_MINI], &mod);
ethnl_update_u32(&ringparam.rx_jumbo_pending,
tb[ETHTOOL_A_RINGS_RX_JUMBO], &mod);
ethnl_update_u32(&ringparam.tx_pending, tb[ETHTOOL_A_RINGS_TX], &mod);
ethnl_update_u32(&kernel_ringparam.rx_buf_len,
tb[ETHTOOL_A_RINGS_RX_BUF_LEN], &mod);
ethnl_update_u32(&kernel_ringparam.cqe_size,
tb[ETHTOOL_A_RINGS_CQE_SIZE], &mod);
ethnl_update_u8(&kernel_ringparam.tx_push,
tb[ETHTOOL_A_RINGS_TX_PUSH], &mod);
ethnl_update_u8(&kernel_ringparam.rx_push,
tb[ETHTOOL_A_RINGS_RX_PUSH], &mod);
ethnl_update_u32(&kernel_ringparam.tx_push_buf_len,
tb[ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN], &mod);
if (!mod)
return 0;
/* ensure new ring parameters are within limits */
if (ringparam.rx_pending > ringparam.rx_max_pending)
err_attr = tb[ETHTOOL_A_RINGS_RX];
else if (ringparam.rx_mini_pending > ringparam.rx_mini_max_pending)
err_attr = tb[ETHTOOL_A_RINGS_RX_MINI];
else if (ringparam.rx_jumbo_pending > ringparam.rx_jumbo_max_pending)
err_attr = tb[ETHTOOL_A_RINGS_RX_JUMBO];
else if (ringparam.tx_pending > ringparam.tx_max_pending)
err_attr = tb[ETHTOOL_A_RINGS_TX];
else
err_attr = NULL;
if (err_attr) {
NL_SET_ERR_MSG_ATTR(info->extack, err_attr,
"requested ring size exceeds maximum");
return -EINVAL;
}
if (kernel_ringparam.tx_push_buf_len > kernel_ringparam.tx_push_buf_max_len) {
NL_SET_ERR_MSG_ATTR_FMT(info->extack, tb[ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN],
"Requested TX push buffer exceeds the maximum of %u",
kernel_ringparam.tx_push_buf_max_len);
return -EINVAL;
}
ret = dev->ethtool_ops->set_ringparam(dev, &ringparam,
&kernel_ringparam, info->extack);
return ret < 0 ? ret : 1;
}
const struct ethnl_request_ops ethnl_rings_request_ops = {
.request_cmd = ETHTOOL_MSG_RINGS_GET,
.reply_cmd = ETHTOOL_MSG_RINGS_GET_REPLY,
.hdr_attr = ETHTOOL_A_RINGS_HEADER,
.req_info_size = sizeof(struct rings_req_info),
.reply_data_size = sizeof(struct rings_reply_data),
.prepare_data = rings_prepare_data,
.reply_size = rings_reply_size,
.fill_reply = rings_fill_reply,
.set_validate = ethnl_set_rings_validate,
.set = ethnl_set_rings,
.set_ntf_cmd = ETHTOOL_MSG_RINGS_NTF,
};
| linux-master | net/ethtool/rings.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
#include <linux/phy.h>
struct linkstate_req_info {
struct ethnl_req_info base;
};
struct linkstate_reply_data {
struct ethnl_reply_data base;
int link;
int sqi;
int sqi_max;
struct ethtool_link_ext_stats link_stats;
bool link_ext_state_provided;
struct ethtool_link_ext_state_info ethtool_link_ext_state_info;
};
#define LINKSTATE_REPDATA(__reply_base) \
container_of(__reply_base, struct linkstate_reply_data, base)
const struct nla_policy ethnl_linkstate_get_policy[] = {
[ETHTOOL_A_LINKSTATE_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy_stats),
};
static int linkstate_get_sqi(struct net_device *dev)
{
struct phy_device *phydev = dev->phydev;
int ret;
if (!phydev)
return -EOPNOTSUPP;
mutex_lock(&phydev->lock);
if (!phydev->drv || !phydev->drv->get_sqi)
ret = -EOPNOTSUPP;
else
ret = phydev->drv->get_sqi(phydev);
mutex_unlock(&phydev->lock);
return ret;
}
static int linkstate_get_sqi_max(struct net_device *dev)
{
struct phy_device *phydev = dev->phydev;
int ret;
if (!phydev)
return -EOPNOTSUPP;
mutex_lock(&phydev->lock);
if (!phydev->drv || !phydev->drv->get_sqi_max)
ret = -EOPNOTSUPP;
else
ret = phydev->drv->get_sqi_max(phydev);
mutex_unlock(&phydev->lock);
return ret;
};
static int linkstate_get_link_ext_state(struct net_device *dev,
struct linkstate_reply_data *data)
{
int err;
if (!dev->ethtool_ops->get_link_ext_state)
return -EOPNOTSUPP;
err = dev->ethtool_ops->get_link_ext_state(dev, &data->ethtool_link_ext_state_info);
if (err)
return err;
data->link_ext_state_provided = true;
return 0;
}
static int linkstate_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct linkstate_reply_data *data = LINKSTATE_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
data->link = __ethtool_get_link(dev);
ret = linkstate_get_sqi(dev);
if (ret < 0 && ret != -EOPNOTSUPP)
goto out;
data->sqi = ret;
ret = linkstate_get_sqi_max(dev);
if (ret < 0 && ret != -EOPNOTSUPP)
goto out;
data->sqi_max = ret;
if (dev->flags & IFF_UP) {
ret = linkstate_get_link_ext_state(dev, data);
if (ret < 0 && ret != -EOPNOTSUPP && ret != -ENODATA)
goto out;
}
ethtool_stats_init((u64 *)&data->link_stats,
sizeof(data->link_stats) / 8);
if (req_base->flags & ETHTOOL_FLAG_STATS) {
if (dev->phydev)
data->link_stats.link_down_events =
READ_ONCE(dev->phydev->link_down_events);
if (dev->ethtool_ops->get_link_ext_stats)
dev->ethtool_ops->get_link_ext_stats(dev,
&data->link_stats);
}
ret = 0;
out:
ethnl_ops_complete(dev);
return ret;
}
static int linkstate_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
struct linkstate_reply_data *data = LINKSTATE_REPDATA(reply_base);
int len;
len = nla_total_size(sizeof(u8)) /* LINKSTATE_LINK */
+ 0;
if (data->sqi != -EOPNOTSUPP)
len += nla_total_size(sizeof(u32));
if (data->sqi_max != -EOPNOTSUPP)
len += nla_total_size(sizeof(u32));
if (data->link_ext_state_provided)
len += nla_total_size(sizeof(u8)); /* LINKSTATE_EXT_STATE */
if (data->ethtool_link_ext_state_info.__link_ext_substate)
len += nla_total_size(sizeof(u8)); /* LINKSTATE_EXT_SUBSTATE */
if (data->link_stats.link_down_events != ETHTOOL_STAT_NOT_SET)
len += nla_total_size(sizeof(u32));
return len;
}
static int linkstate_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
struct linkstate_reply_data *data = LINKSTATE_REPDATA(reply_base);
if (data->link >= 0 &&
nla_put_u8(skb, ETHTOOL_A_LINKSTATE_LINK, !!data->link))
return -EMSGSIZE;
if (data->sqi != -EOPNOTSUPP &&
nla_put_u32(skb, ETHTOOL_A_LINKSTATE_SQI, data->sqi))
return -EMSGSIZE;
if (data->sqi_max != -EOPNOTSUPP &&
nla_put_u32(skb, ETHTOOL_A_LINKSTATE_SQI_MAX, data->sqi_max))
return -EMSGSIZE;
if (data->link_ext_state_provided) {
if (nla_put_u8(skb, ETHTOOL_A_LINKSTATE_EXT_STATE,
data->ethtool_link_ext_state_info.link_ext_state))
return -EMSGSIZE;
if (data->ethtool_link_ext_state_info.__link_ext_substate &&
nla_put_u8(skb, ETHTOOL_A_LINKSTATE_EXT_SUBSTATE,
data->ethtool_link_ext_state_info.__link_ext_substate))
return -EMSGSIZE;
}
if (data->link_stats.link_down_events != ETHTOOL_STAT_NOT_SET)
if (nla_put_u32(skb, ETHTOOL_A_LINKSTATE_EXT_DOWN_CNT,
data->link_stats.link_down_events))
return -EMSGSIZE;
return 0;
}
const struct ethnl_request_ops ethnl_linkstate_request_ops = {
.request_cmd = ETHTOOL_MSG_LINKSTATE_GET,
.reply_cmd = ETHTOOL_MSG_LINKSTATE_GET_REPLY,
.hdr_attr = ETHTOOL_A_LINKSTATE_HEADER,
.req_info_size = sizeof(struct linkstate_req_info),
.reply_data_size = sizeof(struct linkstate_reply_data),
.prepare_data = linkstate_prepare_data,
.reply_size = linkstate_reply_size,
.fill_reply = linkstate_fill_reply,
};
| linux-master | net/ethtool/linkstate.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/ethtool.h>
#include "netlink.h"
#include "common.h"
#include "bitset.h"
struct module_req_info {
struct ethnl_req_info base;
};
struct module_reply_data {
struct ethnl_reply_data base;
struct ethtool_module_power_mode_params power;
};
#define MODULE_REPDATA(__reply_base) \
container_of(__reply_base, struct module_reply_data, base)
/* MODULE_GET */
const struct nla_policy ethnl_module_get_policy[ETHTOOL_A_MODULE_HEADER + 1] = {
[ETHTOOL_A_MODULE_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy),
};
static int module_get_power_mode(struct net_device *dev,
struct module_reply_data *data,
struct netlink_ext_ack *extack)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
if (!ops->get_module_power_mode)
return 0;
return ops->get_module_power_mode(dev, &data->power, extack);
}
static int module_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct module_reply_data *data = MODULE_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
ret = module_get_power_mode(dev, data, info->extack);
if (ret < 0)
goto out_complete;
out_complete:
ethnl_ops_complete(dev);
return ret;
}
static int module_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
struct module_reply_data *data = MODULE_REPDATA(reply_base);
int len = 0;
if (data->power.policy)
len += nla_total_size(sizeof(u8)); /* _MODULE_POWER_MODE_POLICY */
if (data->power.mode)
len += nla_total_size(sizeof(u8)); /* _MODULE_POWER_MODE */
return len;
}
static int module_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct module_reply_data *data = MODULE_REPDATA(reply_base);
if (data->power.policy &&
nla_put_u8(skb, ETHTOOL_A_MODULE_POWER_MODE_POLICY,
data->power.policy))
return -EMSGSIZE;
if (data->power.mode &&
nla_put_u8(skb, ETHTOOL_A_MODULE_POWER_MODE, data->power.mode))
return -EMSGSIZE;
return 0;
}
/* MODULE_SET */
const struct nla_policy ethnl_module_set_policy[ETHTOOL_A_MODULE_POWER_MODE_POLICY + 1] = {
[ETHTOOL_A_MODULE_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_MODULE_POWER_MODE_POLICY] =
NLA_POLICY_RANGE(NLA_U8, ETHTOOL_MODULE_POWER_MODE_POLICY_HIGH,
ETHTOOL_MODULE_POWER_MODE_POLICY_AUTO),
};
static int
ethnl_set_module_validate(struct ethnl_req_info *req_info,
struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
struct nlattr **tb = info->attrs;
if (!tb[ETHTOOL_A_MODULE_POWER_MODE_POLICY])
return 0;
if (!ops->get_module_power_mode || !ops->set_module_power_mode) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_MODULE_POWER_MODE_POLICY],
"Setting power mode policy is not supported by this device");
return -EOPNOTSUPP;
}
return 1;
}
static int
ethnl_set_module(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct ethtool_module_power_mode_params power = {};
struct ethtool_module_power_mode_params power_new;
const struct ethtool_ops *ops;
struct net_device *dev = req_info->dev;
struct nlattr **tb = info->attrs;
int ret;
ops = dev->ethtool_ops;
power_new.policy = nla_get_u8(tb[ETHTOOL_A_MODULE_POWER_MODE_POLICY]);
ret = ops->get_module_power_mode(dev, &power, info->extack);
if (ret < 0)
return ret;
if (power_new.policy == power.policy)
return 0;
ret = ops->set_module_power_mode(dev, &power_new, info->extack);
return ret < 0 ? ret : 1;
}
const struct ethnl_request_ops ethnl_module_request_ops = {
.request_cmd = ETHTOOL_MSG_MODULE_GET,
.reply_cmd = ETHTOOL_MSG_MODULE_GET_REPLY,
.hdr_attr = ETHTOOL_A_MODULE_HEADER,
.req_info_size = sizeof(struct module_req_info),
.reply_data_size = sizeof(struct module_reply_data),
.prepare_data = module_prepare_data,
.reply_size = module_reply_size,
.fill_reply = module_fill_reply,
.set_validate = ethnl_set_module_validate,
.set = ethnl_set_module,
.set_ntf_cmd = ETHTOOL_MSG_MODULE_NTF,
};
| linux-master | net/ethtool/module.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/phy.h>
#include <linux/ethtool_netlink.h>
#include "netlink.h"
#include "common.h"
/* 802.3 standard allows 100 meters for BaseT cables. However longer
* cables might work, depending on the quality of the cables and the
* PHY. So allow testing for up to 150 meters.
*/
#define MAX_CABLE_LENGTH_CM (150 * 100)
const struct nla_policy ethnl_cable_test_act_policy[] = {
[ETHTOOL_A_CABLE_TEST_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int ethnl_cable_test_started(struct phy_device *phydev, u8 cmd)
{
struct sk_buff *skb;
int err = -ENOMEM;
void *ehdr;
skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb)
goto out;
ehdr = ethnl_bcastmsg_put(skb, cmd);
if (!ehdr) {
err = -EMSGSIZE;
goto out;
}
err = ethnl_fill_reply_header(skb, phydev->attached_dev,
ETHTOOL_A_CABLE_TEST_NTF_HEADER);
if (err)
goto out;
err = nla_put_u8(skb, ETHTOOL_A_CABLE_TEST_NTF_STATUS,
ETHTOOL_A_CABLE_TEST_NTF_STATUS_STARTED);
if (err)
goto out;
genlmsg_end(skb, ehdr);
return ethnl_multicast(skb, phydev->attached_dev);
out:
nlmsg_free(skb);
phydev_err(phydev, "%s: Error %pe\n", __func__, ERR_PTR(err));
return err;
}
int ethnl_act_cable_test(struct sk_buff *skb, struct genl_info *info)
{
struct ethnl_req_info req_info = {};
const struct ethtool_phy_ops *ops;
struct nlattr **tb = info->attrs;
struct net_device *dev;
int ret;
ret = ethnl_parse_header_dev_get(&req_info,
tb[ETHTOOL_A_CABLE_TEST_HEADER],
genl_info_net(info), info->extack,
true);
if (ret < 0)
return ret;
dev = req_info.dev;
if (!dev->phydev) {
ret = -EOPNOTSUPP;
goto out_dev_put;
}
rtnl_lock();
ops = ethtool_phy_ops;
if (!ops || !ops->start_cable_test) {
ret = -EOPNOTSUPP;
goto out_rtnl;
}
ret = ethnl_ops_begin(dev);
if (ret < 0)
goto out_rtnl;
ret = ops->start_cable_test(dev->phydev, info->extack);
ethnl_ops_complete(dev);
if (!ret)
ethnl_cable_test_started(dev->phydev,
ETHTOOL_MSG_CABLE_TEST_NTF);
out_rtnl:
rtnl_unlock();
out_dev_put:
ethnl_parse_header_dev_put(&req_info);
return ret;
}
int ethnl_cable_test_alloc(struct phy_device *phydev, u8 cmd)
{
int err = -ENOMEM;
/* One TDR sample occupies 20 bytes. For a 150 meter cable,
* with four pairs, around 12K is needed.
*/
phydev->skb = genlmsg_new(SZ_16K, GFP_KERNEL);
if (!phydev->skb)
goto out;
phydev->ehdr = ethnl_bcastmsg_put(phydev->skb, cmd);
if (!phydev->ehdr) {
err = -EMSGSIZE;
goto out;
}
err = ethnl_fill_reply_header(phydev->skb, phydev->attached_dev,
ETHTOOL_A_CABLE_TEST_NTF_HEADER);
if (err)
goto out;
err = nla_put_u8(phydev->skb, ETHTOOL_A_CABLE_TEST_NTF_STATUS,
ETHTOOL_A_CABLE_TEST_NTF_STATUS_COMPLETED);
if (err)
goto out;
phydev->nest = nla_nest_start(phydev->skb,
ETHTOOL_A_CABLE_TEST_NTF_NEST);
if (!phydev->nest) {
err = -EMSGSIZE;
goto out;
}
return 0;
out:
nlmsg_free(phydev->skb);
phydev->skb = NULL;
return err;
}
EXPORT_SYMBOL_GPL(ethnl_cable_test_alloc);
void ethnl_cable_test_free(struct phy_device *phydev)
{
nlmsg_free(phydev->skb);
phydev->skb = NULL;
}
EXPORT_SYMBOL_GPL(ethnl_cable_test_free);
void ethnl_cable_test_finished(struct phy_device *phydev)
{
nla_nest_end(phydev->skb, phydev->nest);
genlmsg_end(phydev->skb, phydev->ehdr);
ethnl_multicast(phydev->skb, phydev->attached_dev);
}
EXPORT_SYMBOL_GPL(ethnl_cable_test_finished);
int ethnl_cable_test_result(struct phy_device *phydev, u8 pair, u8 result)
{
struct nlattr *nest;
int ret = -EMSGSIZE;
nest = nla_nest_start(phydev->skb, ETHTOOL_A_CABLE_NEST_RESULT);
if (!nest)
return -EMSGSIZE;
if (nla_put_u8(phydev->skb, ETHTOOL_A_CABLE_RESULT_PAIR, pair))
goto err;
if (nla_put_u8(phydev->skb, ETHTOOL_A_CABLE_RESULT_CODE, result))
goto err;
nla_nest_end(phydev->skb, nest);
return 0;
err:
nla_nest_cancel(phydev->skb, nest);
return ret;
}
EXPORT_SYMBOL_GPL(ethnl_cable_test_result);
int ethnl_cable_test_fault_length(struct phy_device *phydev, u8 pair, u32 cm)
{
struct nlattr *nest;
int ret = -EMSGSIZE;
nest = nla_nest_start(phydev->skb,
ETHTOOL_A_CABLE_NEST_FAULT_LENGTH);
if (!nest)
return -EMSGSIZE;
if (nla_put_u8(phydev->skb, ETHTOOL_A_CABLE_FAULT_LENGTH_PAIR, pair))
goto err;
if (nla_put_u32(phydev->skb, ETHTOOL_A_CABLE_FAULT_LENGTH_CM, cm))
goto err;
nla_nest_end(phydev->skb, nest);
return 0;
err:
nla_nest_cancel(phydev->skb, nest);
return ret;
}
EXPORT_SYMBOL_GPL(ethnl_cable_test_fault_length);
struct cable_test_tdr_req_info {
struct ethnl_req_info base;
};
static const struct nla_policy cable_test_tdr_act_cfg_policy[] = {
[ETHTOOL_A_CABLE_TEST_TDR_CFG_FIRST] = { .type = NLA_U32 },
[ETHTOOL_A_CABLE_TEST_TDR_CFG_LAST] = { .type = NLA_U32 },
[ETHTOOL_A_CABLE_TEST_TDR_CFG_STEP] = { .type = NLA_U32 },
[ETHTOOL_A_CABLE_TEST_TDR_CFG_PAIR] = { .type = NLA_U8 },
};
const struct nla_policy ethnl_cable_test_tdr_act_policy[] = {
[ETHTOOL_A_CABLE_TEST_TDR_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_CABLE_TEST_TDR_CFG] = { .type = NLA_NESTED },
};
/* CABLE_TEST_TDR_ACT */
static int ethnl_act_cable_test_tdr_cfg(const struct nlattr *nest,
struct genl_info *info,
struct phy_tdr_config *cfg)
{
struct nlattr *tb[ARRAY_SIZE(cable_test_tdr_act_cfg_policy)];
int ret;
cfg->first = 100;
cfg->step = 100;
cfg->last = MAX_CABLE_LENGTH_CM;
cfg->pair = PHY_PAIR_ALL;
if (!nest)
return 0;
ret = nla_parse_nested(tb,
ARRAY_SIZE(cable_test_tdr_act_cfg_policy) - 1,
nest, cable_test_tdr_act_cfg_policy,
info->extack);
if (ret < 0)
return ret;
if (tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_FIRST])
cfg->first = nla_get_u32(
tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_FIRST]);
if (tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_LAST])
cfg->last = nla_get_u32(tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_LAST]);
if (tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_STEP])
cfg->step = nla_get_u32(tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_STEP]);
if (tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_PAIR]) {
cfg->pair = nla_get_u8(tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_PAIR]);
if (cfg->pair > ETHTOOL_A_CABLE_PAIR_D) {
NL_SET_ERR_MSG_ATTR(
info->extack,
tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_PAIR],
"invalid pair parameter");
return -EINVAL;
}
}
if (cfg->first > MAX_CABLE_LENGTH_CM) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_FIRST],
"invalid first parameter");
return -EINVAL;
}
if (cfg->last > MAX_CABLE_LENGTH_CM) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_LAST],
"invalid last parameter");
return -EINVAL;
}
if (cfg->first > cfg->last) {
NL_SET_ERR_MSG(info->extack, "invalid first/last parameter");
return -EINVAL;
}
if (!cfg->step) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_STEP],
"invalid step parameter");
return -EINVAL;
}
if (cfg->step > (cfg->last - cfg->first)) {
NL_SET_ERR_MSG_ATTR(info->extack,
tb[ETHTOOL_A_CABLE_TEST_TDR_CFG_STEP],
"step parameter too big");
return -EINVAL;
}
return 0;
}
int ethnl_act_cable_test_tdr(struct sk_buff *skb, struct genl_info *info)
{
struct ethnl_req_info req_info = {};
const struct ethtool_phy_ops *ops;
struct nlattr **tb = info->attrs;
struct phy_tdr_config cfg;
struct net_device *dev;
int ret;
ret = ethnl_parse_header_dev_get(&req_info,
tb[ETHTOOL_A_CABLE_TEST_TDR_HEADER],
genl_info_net(info), info->extack,
true);
if (ret < 0)
return ret;
dev = req_info.dev;
if (!dev->phydev) {
ret = -EOPNOTSUPP;
goto out_dev_put;
}
ret = ethnl_act_cable_test_tdr_cfg(tb[ETHTOOL_A_CABLE_TEST_TDR_CFG],
info, &cfg);
if (ret)
goto out_dev_put;
rtnl_lock();
ops = ethtool_phy_ops;
if (!ops || !ops->start_cable_test_tdr) {
ret = -EOPNOTSUPP;
goto out_rtnl;
}
ret = ethnl_ops_begin(dev);
if (ret < 0)
goto out_rtnl;
ret = ops->start_cable_test_tdr(dev->phydev, info->extack, &cfg);
ethnl_ops_complete(dev);
if (!ret)
ethnl_cable_test_started(dev->phydev,
ETHTOOL_MSG_CABLE_TEST_TDR_NTF);
out_rtnl:
rtnl_unlock();
out_dev_put:
ethnl_parse_header_dev_put(&req_info);
return ret;
}
int ethnl_cable_test_amplitude(struct phy_device *phydev,
u8 pair, s16 mV)
{
struct nlattr *nest;
int ret = -EMSGSIZE;
nest = nla_nest_start(phydev->skb,
ETHTOOL_A_CABLE_TDR_NEST_AMPLITUDE);
if (!nest)
return -EMSGSIZE;
if (nla_put_u8(phydev->skb, ETHTOOL_A_CABLE_AMPLITUDE_PAIR, pair))
goto err;
if (nla_put_u16(phydev->skb, ETHTOOL_A_CABLE_AMPLITUDE_mV, mV))
goto err;
nla_nest_end(phydev->skb, nest);
return 0;
err:
nla_nest_cancel(phydev->skb, nest);
return ret;
}
EXPORT_SYMBOL_GPL(ethnl_cable_test_amplitude);
int ethnl_cable_test_pulse(struct phy_device *phydev, u16 mV)
{
struct nlattr *nest;
int ret = -EMSGSIZE;
nest = nla_nest_start(phydev->skb, ETHTOOL_A_CABLE_TDR_NEST_PULSE);
if (!nest)
return -EMSGSIZE;
if (nla_put_u16(phydev->skb, ETHTOOL_A_CABLE_PULSE_mV, mV))
goto err;
nla_nest_end(phydev->skb, nest);
return 0;
err:
nla_nest_cancel(phydev->skb, nest);
return ret;
}
EXPORT_SYMBOL_GPL(ethnl_cable_test_pulse);
int ethnl_cable_test_step(struct phy_device *phydev, u32 first, u32 last,
u32 step)
{
struct nlattr *nest;
int ret = -EMSGSIZE;
nest = nla_nest_start(phydev->skb, ETHTOOL_A_CABLE_TDR_NEST_STEP);
if (!nest)
return -EMSGSIZE;
if (nla_put_u32(phydev->skb, ETHTOOL_A_CABLE_STEP_FIRST_DISTANCE,
first))
goto err;
if (nla_put_u32(phydev->skb, ETHTOOL_A_CABLE_STEP_LAST_DISTANCE, last))
goto err;
if (nla_put_u32(phydev->skb, ETHTOOL_A_CABLE_STEP_STEP_DISTANCE, step))
goto err;
nla_nest_end(phydev->skb, nest);
return 0;
err:
nla_nest_cancel(phydev->skb, nest);
return ret;
}
EXPORT_SYMBOL_GPL(ethnl_cable_test_step);
| linux-master | net/ethtool/cabletest.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
#include "bitset.h"
/* LINKMODES_GET */
struct linkmodes_req_info {
struct ethnl_req_info base;
};
struct linkmodes_reply_data {
struct ethnl_reply_data base;
struct ethtool_link_ksettings ksettings;
struct ethtool_link_settings *lsettings;
bool peer_empty;
};
#define LINKMODES_REPDATA(__reply_base) \
container_of(__reply_base, struct linkmodes_reply_data, base)
const struct nla_policy ethnl_linkmodes_get_policy[] = {
[ETHTOOL_A_LINKMODES_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int linkmodes_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct linkmodes_reply_data *data = LINKMODES_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
data->lsettings = &data->ksettings.base;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
ret = __ethtool_get_link_ksettings(dev, &data->ksettings);
if (ret < 0 && info) {
GENL_SET_ERR_MSG(info, "failed to retrieve link settings");
goto out;
}
if (!dev->ethtool_ops->cap_link_lanes_supported)
data->ksettings.lanes = 0;
data->peer_empty =
bitmap_empty(data->ksettings.link_modes.lp_advertising,
__ETHTOOL_LINK_MODE_MASK_NBITS);
out:
ethnl_ops_complete(dev);
return ret;
}
static int linkmodes_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct linkmodes_reply_data *data = LINKMODES_REPDATA(reply_base);
const struct ethtool_link_ksettings *ksettings = &data->ksettings;
const struct ethtool_link_settings *lsettings = &ksettings->base;
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
int len, ret;
len = nla_total_size(sizeof(u8)) /* LINKMODES_AUTONEG */
+ nla_total_size(sizeof(u32)) /* LINKMODES_SPEED */
+ nla_total_size(sizeof(u32)) /* LINKMODES_LANES */
+ nla_total_size(sizeof(u8)) /* LINKMODES_DUPLEX */
+ nla_total_size(sizeof(u8)) /* LINKMODES_RATE_MATCHING */
+ 0;
ret = ethnl_bitset_size(ksettings->link_modes.advertising,
ksettings->link_modes.supported,
__ETHTOOL_LINK_MODE_MASK_NBITS,
link_mode_names, compact);
if (ret < 0)
return ret;
len += ret;
if (!data->peer_empty) {
ret = ethnl_bitset_size(ksettings->link_modes.lp_advertising,
NULL, __ETHTOOL_LINK_MODE_MASK_NBITS,
link_mode_names, compact);
if (ret < 0)
return ret;
len += ret;
}
if (lsettings->master_slave_cfg != MASTER_SLAVE_CFG_UNSUPPORTED)
len += nla_total_size(sizeof(u8));
if (lsettings->master_slave_state != MASTER_SLAVE_STATE_UNSUPPORTED)
len += nla_total_size(sizeof(u8));
return len;
}
static int linkmodes_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct linkmodes_reply_data *data = LINKMODES_REPDATA(reply_base);
const struct ethtool_link_ksettings *ksettings = &data->ksettings;
const struct ethtool_link_settings *lsettings = &ksettings->base;
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
int ret;
if (nla_put_u8(skb, ETHTOOL_A_LINKMODES_AUTONEG, lsettings->autoneg))
return -EMSGSIZE;
ret = ethnl_put_bitset(skb, ETHTOOL_A_LINKMODES_OURS,
ksettings->link_modes.advertising,
ksettings->link_modes.supported,
__ETHTOOL_LINK_MODE_MASK_NBITS, link_mode_names,
compact);
if (ret < 0)
return -EMSGSIZE;
if (!data->peer_empty) {
ret = ethnl_put_bitset(skb, ETHTOOL_A_LINKMODES_PEER,
ksettings->link_modes.lp_advertising,
NULL, __ETHTOOL_LINK_MODE_MASK_NBITS,
link_mode_names, compact);
if (ret < 0)
return -EMSGSIZE;
}
if (nla_put_u32(skb, ETHTOOL_A_LINKMODES_SPEED, lsettings->speed) ||
nla_put_u8(skb, ETHTOOL_A_LINKMODES_DUPLEX, lsettings->duplex))
return -EMSGSIZE;
if (ksettings->lanes &&
nla_put_u32(skb, ETHTOOL_A_LINKMODES_LANES, ksettings->lanes))
return -EMSGSIZE;
if (lsettings->master_slave_cfg != MASTER_SLAVE_CFG_UNSUPPORTED &&
nla_put_u8(skb, ETHTOOL_A_LINKMODES_MASTER_SLAVE_CFG,
lsettings->master_slave_cfg))
return -EMSGSIZE;
if (lsettings->master_slave_state != MASTER_SLAVE_STATE_UNSUPPORTED &&
nla_put_u8(skb, ETHTOOL_A_LINKMODES_MASTER_SLAVE_STATE,
lsettings->master_slave_state))
return -EMSGSIZE;
if (nla_put_u8(skb, ETHTOOL_A_LINKMODES_RATE_MATCHING,
lsettings->rate_matching))
return -EMSGSIZE;
return 0;
}
/* LINKMODES_SET */
const struct nla_policy ethnl_linkmodes_set_policy[] = {
[ETHTOOL_A_LINKMODES_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_LINKMODES_AUTONEG] = { .type = NLA_U8 },
[ETHTOOL_A_LINKMODES_OURS] = { .type = NLA_NESTED },
[ETHTOOL_A_LINKMODES_SPEED] = { .type = NLA_U32 },
[ETHTOOL_A_LINKMODES_DUPLEX] = { .type = NLA_U8 },
[ETHTOOL_A_LINKMODES_MASTER_SLAVE_CFG] = { .type = NLA_U8 },
[ETHTOOL_A_LINKMODES_LANES] = NLA_POLICY_RANGE(NLA_U32, 1, 8),
};
/* Set advertised link modes to all supported modes matching requested speed,
* lanes and duplex values. Called when autonegotiation is on, speed, lanes or
* duplex is requested but no link mode change. This is done in userspace with
* ioctl() interface, move it into kernel for netlink.
* Returns true if advertised modes bitmap was modified.
*/
static bool ethnl_auto_linkmodes(struct ethtool_link_ksettings *ksettings,
bool req_speed, bool req_lanes, bool req_duplex)
{
unsigned long *advertising = ksettings->link_modes.advertising;
unsigned long *supported = ksettings->link_modes.supported;
DECLARE_BITMAP(old_adv, __ETHTOOL_LINK_MODE_MASK_NBITS);
unsigned int i;
bitmap_copy(old_adv, advertising, __ETHTOOL_LINK_MODE_MASK_NBITS);
for (i = 0; i < __ETHTOOL_LINK_MODE_MASK_NBITS; i++) {
const struct link_mode_info *info = &link_mode_params[i];
if (info->speed == SPEED_UNKNOWN)
continue;
if (test_bit(i, supported) &&
(!req_speed || info->speed == ksettings->base.speed) &&
(!req_lanes || info->lanes == ksettings->lanes) &&
(!req_duplex || info->duplex == ksettings->base.duplex))
set_bit(i, advertising);
else
clear_bit(i, advertising);
}
return !bitmap_equal(old_adv, advertising,
__ETHTOOL_LINK_MODE_MASK_NBITS);
}
static bool ethnl_validate_master_slave_cfg(u8 cfg)
{
switch (cfg) {
case MASTER_SLAVE_CFG_MASTER_PREFERRED:
case MASTER_SLAVE_CFG_SLAVE_PREFERRED:
case MASTER_SLAVE_CFG_MASTER_FORCE:
case MASTER_SLAVE_CFG_SLAVE_FORCE:
return true;
}
return false;
}
static int ethnl_check_linkmodes(struct genl_info *info, struct nlattr **tb)
{
const struct nlattr *master_slave_cfg, *lanes_cfg;
master_slave_cfg = tb[ETHTOOL_A_LINKMODES_MASTER_SLAVE_CFG];
if (master_slave_cfg &&
!ethnl_validate_master_slave_cfg(nla_get_u8(master_slave_cfg))) {
NL_SET_ERR_MSG_ATTR(info->extack, master_slave_cfg,
"master/slave value is invalid");
return -EOPNOTSUPP;
}
lanes_cfg = tb[ETHTOOL_A_LINKMODES_LANES];
if (lanes_cfg && !is_power_of_2(nla_get_u32(lanes_cfg))) {
NL_SET_ERR_MSG_ATTR(info->extack, lanes_cfg,
"lanes value is invalid");
return -EINVAL;
}
return 0;
}
static int ethnl_update_linkmodes(struct genl_info *info, struct nlattr **tb,
struct ethtool_link_ksettings *ksettings,
bool *mod, const struct net_device *dev)
{
struct ethtool_link_settings *lsettings = &ksettings->base;
bool req_speed, req_lanes, req_duplex;
const struct nlattr *master_slave_cfg, *lanes_cfg;
int ret;
master_slave_cfg = tb[ETHTOOL_A_LINKMODES_MASTER_SLAVE_CFG];
if (master_slave_cfg) {
if (lsettings->master_slave_cfg == MASTER_SLAVE_CFG_UNSUPPORTED) {
NL_SET_ERR_MSG_ATTR(info->extack, master_slave_cfg,
"master/slave configuration not supported by device");
return -EOPNOTSUPP;
}
}
*mod = false;
req_speed = tb[ETHTOOL_A_LINKMODES_SPEED];
req_lanes = tb[ETHTOOL_A_LINKMODES_LANES];
req_duplex = tb[ETHTOOL_A_LINKMODES_DUPLEX];
ethnl_update_u8(&lsettings->autoneg, tb[ETHTOOL_A_LINKMODES_AUTONEG],
mod);
lanes_cfg = tb[ETHTOOL_A_LINKMODES_LANES];
if (lanes_cfg) {
/* If autoneg is off and lanes parameter is not supported by the
* driver, return an error.
*/
if (!lsettings->autoneg &&
!dev->ethtool_ops->cap_link_lanes_supported) {
NL_SET_ERR_MSG_ATTR(info->extack, lanes_cfg,
"lanes configuration not supported by device");
return -EOPNOTSUPP;
}
} else if (!lsettings->autoneg && ksettings->lanes) {
/* If autoneg is off and lanes parameter is not passed from user but
* it was defined previously then set the lanes parameter to 0.
*/
ksettings->lanes = 0;
*mod = true;
}
ret = ethnl_update_bitset(ksettings->link_modes.advertising,
__ETHTOOL_LINK_MODE_MASK_NBITS,
tb[ETHTOOL_A_LINKMODES_OURS], link_mode_names,
info->extack, mod);
if (ret < 0)
return ret;
ethnl_update_u32(&lsettings->speed, tb[ETHTOOL_A_LINKMODES_SPEED],
mod);
ethnl_update_u32(&ksettings->lanes, lanes_cfg, mod);
ethnl_update_u8(&lsettings->duplex, tb[ETHTOOL_A_LINKMODES_DUPLEX],
mod);
ethnl_update_u8(&lsettings->master_slave_cfg, master_slave_cfg, mod);
if (!tb[ETHTOOL_A_LINKMODES_OURS] && lsettings->autoneg &&
(req_speed || req_lanes || req_duplex) &&
ethnl_auto_linkmodes(ksettings, req_speed, req_lanes, req_duplex))
*mod = true;
return 0;
}
static int
ethnl_set_linkmodes_validate(struct ethnl_req_info *req_info,
struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
int ret;
ret = ethnl_check_linkmodes(info, info->attrs);
if (ret < 0)
return ret;
if (!ops->get_link_ksettings || !ops->set_link_ksettings)
return -EOPNOTSUPP;
return 1;
}
static int
ethnl_set_linkmodes(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct ethtool_link_ksettings ksettings = {};
struct net_device *dev = req_info->dev;
struct nlattr **tb = info->attrs;
bool mod = false;
int ret;
ret = __ethtool_get_link_ksettings(dev, &ksettings);
if (ret < 0) {
GENL_SET_ERR_MSG(info, "failed to retrieve link settings");
return ret;
}
ret = ethnl_update_linkmodes(info, tb, &ksettings, &mod, dev);
if (ret < 0)
return ret;
if (!mod)
return 0;
ret = dev->ethtool_ops->set_link_ksettings(dev, &ksettings);
if (ret < 0) {
GENL_SET_ERR_MSG(info, "link settings update failed");
return ret;
}
return 1;
}
const struct ethnl_request_ops ethnl_linkmodes_request_ops = {
.request_cmd = ETHTOOL_MSG_LINKMODES_GET,
.reply_cmd = ETHTOOL_MSG_LINKMODES_GET_REPLY,
.hdr_attr = ETHTOOL_A_LINKMODES_HEADER,
.req_info_size = sizeof(struct linkmodes_req_info),
.reply_data_size = sizeof(struct linkmodes_reply_data),
.prepare_data = linkmodes_prepare_data,
.reply_size = linkmodes_reply_size,
.fill_reply = linkmodes_fill_reply,
.set_validate = ethnl_set_linkmodes_validate,
.set = ethnl_set_linkmodes,
.set_ntf_cmd = ETHTOOL_MSG_LINKMODES_NTF,
};
| linux-master | net/ethtool/linkmodes.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
struct rss_req_info {
struct ethnl_req_info base;
u32 rss_context;
};
struct rss_reply_data {
struct ethnl_reply_data base;
u32 indir_size;
u32 hkey_size;
u32 hfunc;
u32 *indir_table;
u8 *hkey;
};
#define RSS_REQINFO(__req_base) \
container_of(__req_base, struct rss_req_info, base)
#define RSS_REPDATA(__reply_base) \
container_of(__reply_base, struct rss_reply_data, base)
const struct nla_policy ethnl_rss_get_policy[] = {
[ETHTOOL_A_RSS_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_RSS_CONTEXT] = { .type = NLA_U32 },
};
static int
rss_parse_request(struct ethnl_req_info *req_info, struct nlattr **tb,
struct netlink_ext_ack *extack)
{
struct rss_req_info *request = RSS_REQINFO(req_info);
if (tb[ETHTOOL_A_RSS_CONTEXT])
request->rss_context = nla_get_u32(tb[ETHTOOL_A_RSS_CONTEXT]);
return 0;
}
static int
rss_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct rss_reply_data *data = RSS_REPDATA(reply_base);
struct rss_req_info *request = RSS_REQINFO(req_base);
struct net_device *dev = reply_base->dev;
const struct ethtool_ops *ops;
u32 total_size, indir_bytes;
u8 dev_hfunc = 0;
u8 *rss_config;
int ret;
ops = dev->ethtool_ops;
if (!ops->get_rxfh)
return -EOPNOTSUPP;
/* Some drivers don't handle rss_context */
if (request->rss_context && !ops->get_rxfh_context)
return -EOPNOTSUPP;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
data->indir_size = 0;
data->hkey_size = 0;
if (ops->get_rxfh_indir_size)
data->indir_size = ops->get_rxfh_indir_size(dev);
if (ops->get_rxfh_key_size)
data->hkey_size = ops->get_rxfh_key_size(dev);
indir_bytes = data->indir_size * sizeof(u32);
total_size = indir_bytes + data->hkey_size;
rss_config = kzalloc(total_size, GFP_KERNEL);
if (!rss_config) {
ret = -ENOMEM;
goto out_ops;
}
if (data->indir_size)
data->indir_table = (u32 *)rss_config;
if (data->hkey_size)
data->hkey = rss_config + indir_bytes;
if (request->rss_context)
ret = ops->get_rxfh_context(dev, data->indir_table, data->hkey,
&dev_hfunc, request->rss_context);
else
ret = ops->get_rxfh(dev, data->indir_table, data->hkey,
&dev_hfunc);
if (ret)
goto out_ops;
data->hfunc = dev_hfunc;
out_ops:
ethnl_ops_complete(dev);
return ret;
}
static int
rss_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct rss_reply_data *data = RSS_REPDATA(reply_base);
int len;
len = nla_total_size(sizeof(u32)) + /* _RSS_HFUNC */
nla_total_size(sizeof(u32) * data->indir_size) + /* _RSS_INDIR */
nla_total_size(data->hkey_size); /* _RSS_HKEY */
return len;
}
static int
rss_fill_reply(struct sk_buff *skb, const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct rss_reply_data *data = RSS_REPDATA(reply_base);
if ((data->hfunc &&
nla_put_u32(skb, ETHTOOL_A_RSS_HFUNC, data->hfunc)) ||
(data->indir_size &&
nla_put(skb, ETHTOOL_A_RSS_INDIR,
sizeof(u32) * data->indir_size, data->indir_table)) ||
(data->hkey_size &&
nla_put(skb, ETHTOOL_A_RSS_HKEY, data->hkey_size, data->hkey)))
return -EMSGSIZE;
return 0;
}
static void rss_cleanup_data(struct ethnl_reply_data *reply_base)
{
const struct rss_reply_data *data = RSS_REPDATA(reply_base);
kfree(data->indir_table);
}
const struct ethnl_request_ops ethnl_rss_request_ops = {
.request_cmd = ETHTOOL_MSG_RSS_GET,
.reply_cmd = ETHTOOL_MSG_RSS_GET_REPLY,
.hdr_attr = ETHTOOL_A_RSS_HEADER,
.req_info_size = sizeof(struct rss_req_info),
.reply_data_size = sizeof(struct rss_reply_data),
.parse_request = rss_parse_request,
.prepare_data = rss_prepare_data,
.reply_size = rss_reply_size,
.fill_reply = rss_fill_reply,
.cleanup_data = rss_cleanup_data,
};
| linux-master | net/ethtool/rss.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
#include "bitset.h"
struct stats_req_info {
struct ethnl_req_info base;
DECLARE_BITMAP(stat_mask, __ETHTOOL_STATS_CNT);
enum ethtool_mac_stats_src src;
};
#define STATS_REQINFO(__req_base) \
container_of(__req_base, struct stats_req_info, base)
struct stats_reply_data {
struct ethnl_reply_data base;
struct_group(stats,
struct ethtool_eth_phy_stats phy_stats;
struct ethtool_eth_mac_stats mac_stats;
struct ethtool_eth_ctrl_stats ctrl_stats;
struct ethtool_rmon_stats rmon_stats;
);
const struct ethtool_rmon_hist_range *rmon_ranges;
};
#define STATS_REPDATA(__reply_base) \
container_of(__reply_base, struct stats_reply_data, base)
const char stats_std_names[__ETHTOOL_STATS_CNT][ETH_GSTRING_LEN] = {
[ETHTOOL_STATS_ETH_PHY] = "eth-phy",
[ETHTOOL_STATS_ETH_MAC] = "eth-mac",
[ETHTOOL_STATS_ETH_CTRL] = "eth-ctrl",
[ETHTOOL_STATS_RMON] = "rmon",
};
const char stats_eth_phy_names[__ETHTOOL_A_STATS_ETH_PHY_CNT][ETH_GSTRING_LEN] = {
[ETHTOOL_A_STATS_ETH_PHY_5_SYM_ERR] = "SymbolErrorDuringCarrier",
};
const char stats_eth_mac_names[__ETHTOOL_A_STATS_ETH_MAC_CNT][ETH_GSTRING_LEN] = {
[ETHTOOL_A_STATS_ETH_MAC_2_TX_PKT] = "FramesTransmittedOK",
[ETHTOOL_A_STATS_ETH_MAC_3_SINGLE_COL] = "SingleCollisionFrames",
[ETHTOOL_A_STATS_ETH_MAC_4_MULTI_COL] = "MultipleCollisionFrames",
[ETHTOOL_A_STATS_ETH_MAC_5_RX_PKT] = "FramesReceivedOK",
[ETHTOOL_A_STATS_ETH_MAC_6_FCS_ERR] = "FrameCheckSequenceErrors",
[ETHTOOL_A_STATS_ETH_MAC_7_ALIGN_ERR] = "AlignmentErrors",
[ETHTOOL_A_STATS_ETH_MAC_8_TX_BYTES] = "OctetsTransmittedOK",
[ETHTOOL_A_STATS_ETH_MAC_9_TX_DEFER] = "FramesWithDeferredXmissions",
[ETHTOOL_A_STATS_ETH_MAC_10_LATE_COL] = "LateCollisions",
[ETHTOOL_A_STATS_ETH_MAC_11_XS_COL] = "FramesAbortedDueToXSColls",
[ETHTOOL_A_STATS_ETH_MAC_12_TX_INT_ERR] = "FramesLostDueToIntMACXmitError",
[ETHTOOL_A_STATS_ETH_MAC_13_CS_ERR] = "CarrierSenseErrors",
[ETHTOOL_A_STATS_ETH_MAC_14_RX_BYTES] = "OctetsReceivedOK",
[ETHTOOL_A_STATS_ETH_MAC_15_RX_INT_ERR] = "FramesLostDueToIntMACRcvError",
[ETHTOOL_A_STATS_ETH_MAC_18_TX_MCAST] = "MulticastFramesXmittedOK",
[ETHTOOL_A_STATS_ETH_MAC_19_TX_BCAST] = "BroadcastFramesXmittedOK",
[ETHTOOL_A_STATS_ETH_MAC_20_XS_DEFER] = "FramesWithExcessiveDeferral",
[ETHTOOL_A_STATS_ETH_MAC_21_RX_MCAST] = "MulticastFramesReceivedOK",
[ETHTOOL_A_STATS_ETH_MAC_22_RX_BCAST] = "BroadcastFramesReceivedOK",
[ETHTOOL_A_STATS_ETH_MAC_23_IR_LEN_ERR] = "InRangeLengthErrors",
[ETHTOOL_A_STATS_ETH_MAC_24_OOR_LEN] = "OutOfRangeLengthField",
[ETHTOOL_A_STATS_ETH_MAC_25_TOO_LONG_ERR] = "FrameTooLongErrors",
};
const char stats_eth_ctrl_names[__ETHTOOL_A_STATS_ETH_CTRL_CNT][ETH_GSTRING_LEN] = {
[ETHTOOL_A_STATS_ETH_CTRL_3_TX] = "MACControlFramesTransmitted",
[ETHTOOL_A_STATS_ETH_CTRL_4_RX] = "MACControlFramesReceived",
[ETHTOOL_A_STATS_ETH_CTRL_5_RX_UNSUP] = "UnsupportedOpcodesReceived",
};
const char stats_rmon_names[__ETHTOOL_A_STATS_RMON_CNT][ETH_GSTRING_LEN] = {
[ETHTOOL_A_STATS_RMON_UNDERSIZE] = "etherStatsUndersizePkts",
[ETHTOOL_A_STATS_RMON_OVERSIZE] = "etherStatsOversizePkts",
[ETHTOOL_A_STATS_RMON_FRAG] = "etherStatsFragments",
[ETHTOOL_A_STATS_RMON_JABBER] = "etherStatsJabbers",
};
const struct nla_policy ethnl_stats_get_policy[ETHTOOL_A_STATS_SRC + 1] = {
[ETHTOOL_A_STATS_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_STATS_GROUPS] = { .type = NLA_NESTED },
[ETHTOOL_A_STATS_SRC] =
NLA_POLICY_MAX(NLA_U32, ETHTOOL_MAC_STATS_SRC_PMAC),
};
static int stats_parse_request(struct ethnl_req_info *req_base,
struct nlattr **tb,
struct netlink_ext_ack *extack)
{
enum ethtool_mac_stats_src src = ETHTOOL_MAC_STATS_SRC_AGGREGATE;
struct stats_req_info *req_info = STATS_REQINFO(req_base);
bool mod = false;
int err;
err = ethnl_update_bitset(req_info->stat_mask, __ETHTOOL_STATS_CNT,
tb[ETHTOOL_A_STATS_GROUPS], stats_std_names,
extack, &mod);
if (err)
return err;
if (!mod) {
NL_SET_ERR_MSG(extack, "no stats requested");
return -EINVAL;
}
if (tb[ETHTOOL_A_STATS_SRC])
src = nla_get_u32(tb[ETHTOOL_A_STATS_SRC]);
req_info->src = src;
return 0;
}
static int stats_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
const struct stats_req_info *req_info = STATS_REQINFO(req_base);
struct stats_reply_data *data = STATS_REPDATA(reply_base);
enum ethtool_mac_stats_src src = req_info->src;
struct net_device *dev = reply_base->dev;
int ret;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
if ((src == ETHTOOL_MAC_STATS_SRC_EMAC ||
src == ETHTOOL_MAC_STATS_SRC_PMAC) &&
!__ethtool_dev_mm_supported(dev)) {
NL_SET_ERR_MSG_MOD(info->extack,
"Device does not support MAC merge layer");
ethnl_ops_complete(dev);
return -EOPNOTSUPP;
}
/* Mark all stats as unset (see ETHTOOL_STAT_NOT_SET) to prevent them
* from being reported to user space in case driver did not set them.
*/
memset(&data->stats, 0xff, sizeof(data->stats));
data->phy_stats.src = src;
data->mac_stats.src = src;
data->ctrl_stats.src = src;
data->rmon_stats.src = src;
if (test_bit(ETHTOOL_STATS_ETH_PHY, req_info->stat_mask) &&
dev->ethtool_ops->get_eth_phy_stats)
dev->ethtool_ops->get_eth_phy_stats(dev, &data->phy_stats);
if (test_bit(ETHTOOL_STATS_ETH_MAC, req_info->stat_mask) &&
dev->ethtool_ops->get_eth_mac_stats)
dev->ethtool_ops->get_eth_mac_stats(dev, &data->mac_stats);
if (test_bit(ETHTOOL_STATS_ETH_CTRL, req_info->stat_mask) &&
dev->ethtool_ops->get_eth_ctrl_stats)
dev->ethtool_ops->get_eth_ctrl_stats(dev, &data->ctrl_stats);
if (test_bit(ETHTOOL_STATS_RMON, req_info->stat_mask) &&
dev->ethtool_ops->get_rmon_stats)
dev->ethtool_ops->get_rmon_stats(dev, &data->rmon_stats,
&data->rmon_ranges);
ethnl_ops_complete(dev);
return 0;
}
static int stats_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct stats_req_info *req_info = STATS_REQINFO(req_base);
unsigned int n_grps = 0, n_stats = 0;
int len = 0;
len += nla_total_size(sizeof(u32)); /* _STATS_SRC */
if (test_bit(ETHTOOL_STATS_ETH_PHY, req_info->stat_mask)) {
n_stats += sizeof(struct ethtool_eth_phy_stats) / sizeof(u64);
n_grps++;
}
if (test_bit(ETHTOOL_STATS_ETH_MAC, req_info->stat_mask)) {
n_stats += sizeof(struct ethtool_eth_mac_stats) / sizeof(u64);
n_grps++;
}
if (test_bit(ETHTOOL_STATS_ETH_CTRL, req_info->stat_mask)) {
n_stats += sizeof(struct ethtool_eth_ctrl_stats) / sizeof(u64);
n_grps++;
}
if (test_bit(ETHTOOL_STATS_RMON, req_info->stat_mask)) {
n_stats += sizeof(struct ethtool_rmon_stats) / sizeof(u64);
n_grps++;
/* Above includes the space for _A_STATS_GRP_HIST_VALs */
len += (nla_total_size(0) + /* _A_STATS_GRP_HIST */
nla_total_size(4) + /* _A_STATS_GRP_HIST_BKT_LOW */
nla_total_size(4)) * /* _A_STATS_GRP_HIST_BKT_HI */
ETHTOOL_RMON_HIST_MAX * 2;
}
len += n_grps * (nla_total_size(0) + /* _A_STATS_GRP */
nla_total_size(4) + /* _A_STATS_GRP_ID */
nla_total_size(4)); /* _A_STATS_GRP_SS_ID */
len += n_stats * (nla_total_size(0) + /* _A_STATS_GRP_STAT */
nla_total_size_64bit(sizeof(u64)));
return len;
}
static int stat_put(struct sk_buff *skb, u16 attrtype, u64 val)
{
struct nlattr *nest;
int ret;
if (val == ETHTOOL_STAT_NOT_SET)
return 0;
/* We want to start stats attr types from 0, so we don't have a type
* for pad inside ETHTOOL_A_STATS_GRP_STAT. Pad things on the outside
* of ETHTOOL_A_STATS_GRP_STAT. Since we're one nest away from the
* actual attr we're 4B off - nla_need_padding_for_64bit() & co.
* can't be used.
*/
#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
if (!IS_ALIGNED((unsigned long)skb_tail_pointer(skb), 8))
if (!nla_reserve(skb, ETHTOOL_A_STATS_GRP_PAD, 0))
return -EMSGSIZE;
#endif
nest = nla_nest_start(skb, ETHTOOL_A_STATS_GRP_STAT);
if (!nest)
return -EMSGSIZE;
ret = nla_put_u64_64bit(skb, attrtype, val, -1 /* not used */);
if (ret) {
nla_nest_cancel(skb, nest);
return ret;
}
nla_nest_end(skb, nest);
return 0;
}
static int stats_put_phy_stats(struct sk_buff *skb,
const struct stats_reply_data *data)
{
if (stat_put(skb, ETHTOOL_A_STATS_ETH_PHY_5_SYM_ERR,
data->phy_stats.SymbolErrorDuringCarrier))
return -EMSGSIZE;
return 0;
}
static int stats_put_mac_stats(struct sk_buff *skb,
const struct stats_reply_data *data)
{
if (stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_2_TX_PKT,
data->mac_stats.FramesTransmittedOK) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_3_SINGLE_COL,
data->mac_stats.SingleCollisionFrames) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_4_MULTI_COL,
data->mac_stats.MultipleCollisionFrames) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_5_RX_PKT,
data->mac_stats.FramesReceivedOK) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_6_FCS_ERR,
data->mac_stats.FrameCheckSequenceErrors) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_7_ALIGN_ERR,
data->mac_stats.AlignmentErrors) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_8_TX_BYTES,
data->mac_stats.OctetsTransmittedOK) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_9_TX_DEFER,
data->mac_stats.FramesWithDeferredXmissions) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_10_LATE_COL,
data->mac_stats.LateCollisions) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_11_XS_COL,
data->mac_stats.FramesAbortedDueToXSColls) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_12_TX_INT_ERR,
data->mac_stats.FramesLostDueToIntMACXmitError) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_13_CS_ERR,
data->mac_stats.CarrierSenseErrors) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_14_RX_BYTES,
data->mac_stats.OctetsReceivedOK) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_15_RX_INT_ERR,
data->mac_stats.FramesLostDueToIntMACRcvError) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_18_TX_MCAST,
data->mac_stats.MulticastFramesXmittedOK) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_19_TX_BCAST,
data->mac_stats.BroadcastFramesXmittedOK) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_20_XS_DEFER,
data->mac_stats.FramesWithExcessiveDeferral) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_21_RX_MCAST,
data->mac_stats.MulticastFramesReceivedOK) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_22_RX_BCAST,
data->mac_stats.BroadcastFramesReceivedOK) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_23_IR_LEN_ERR,
data->mac_stats.InRangeLengthErrors) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_24_OOR_LEN,
data->mac_stats.OutOfRangeLengthField) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_MAC_25_TOO_LONG_ERR,
data->mac_stats.FrameTooLongErrors))
return -EMSGSIZE;
return 0;
}
static int stats_put_ctrl_stats(struct sk_buff *skb,
const struct stats_reply_data *data)
{
if (stat_put(skb, ETHTOOL_A_STATS_ETH_CTRL_3_TX,
data->ctrl_stats.MACControlFramesTransmitted) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_CTRL_4_RX,
data->ctrl_stats.MACControlFramesReceived) ||
stat_put(skb, ETHTOOL_A_STATS_ETH_CTRL_5_RX_UNSUP,
data->ctrl_stats.UnsupportedOpcodesReceived))
return -EMSGSIZE;
return 0;
}
static int stats_put_rmon_hist(struct sk_buff *skb, u32 attr, const u64 *hist,
const struct ethtool_rmon_hist_range *ranges)
{
struct nlattr *nest;
int i;
if (!ranges)
return 0;
for (i = 0; i < ETHTOOL_RMON_HIST_MAX; i++) {
if (!ranges[i].low && !ranges[i].high)
break;
if (hist[i] == ETHTOOL_STAT_NOT_SET)
continue;
nest = nla_nest_start(skb, attr);
if (!nest)
return -EMSGSIZE;
if (nla_put_u32(skb, ETHTOOL_A_STATS_GRP_HIST_BKT_LOW,
ranges[i].low) ||
nla_put_u32(skb, ETHTOOL_A_STATS_GRP_HIST_BKT_HI,
ranges[i].high) ||
nla_put_u64_64bit(skb, ETHTOOL_A_STATS_GRP_HIST_VAL,
hist[i], ETHTOOL_A_STATS_GRP_PAD))
goto err_cancel_hist;
nla_nest_end(skb, nest);
}
return 0;
err_cancel_hist:
nla_nest_cancel(skb, nest);
return -EMSGSIZE;
}
static int stats_put_rmon_stats(struct sk_buff *skb,
const struct stats_reply_data *data)
{
if (stats_put_rmon_hist(skb, ETHTOOL_A_STATS_GRP_HIST_RX,
data->rmon_stats.hist, data->rmon_ranges) ||
stats_put_rmon_hist(skb, ETHTOOL_A_STATS_GRP_HIST_TX,
data->rmon_stats.hist_tx, data->rmon_ranges))
return -EMSGSIZE;
if (stat_put(skb, ETHTOOL_A_STATS_RMON_UNDERSIZE,
data->rmon_stats.undersize_pkts) ||
stat_put(skb, ETHTOOL_A_STATS_RMON_OVERSIZE,
data->rmon_stats.oversize_pkts) ||
stat_put(skb, ETHTOOL_A_STATS_RMON_FRAG,
data->rmon_stats.fragments) ||
stat_put(skb, ETHTOOL_A_STATS_RMON_JABBER,
data->rmon_stats.jabbers))
return -EMSGSIZE;
return 0;
}
static int stats_put_stats(struct sk_buff *skb,
const struct stats_reply_data *data,
u32 id, u32 ss_id,
int (*cb)(struct sk_buff *skb,
const struct stats_reply_data *data))
{
struct nlattr *nest;
nest = nla_nest_start(skb, ETHTOOL_A_STATS_GRP);
if (!nest)
return -EMSGSIZE;
if (nla_put_u32(skb, ETHTOOL_A_STATS_GRP_ID, id) ||
nla_put_u32(skb, ETHTOOL_A_STATS_GRP_SS_ID, ss_id))
goto err_cancel;
if (cb(skb, data))
goto err_cancel;
nla_nest_end(skb, nest);
return 0;
err_cancel:
nla_nest_cancel(skb, nest);
return -EMSGSIZE;
}
static int stats_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct stats_req_info *req_info = STATS_REQINFO(req_base);
const struct stats_reply_data *data = STATS_REPDATA(reply_base);
int ret = 0;
if (nla_put_u32(skb, ETHTOOL_A_STATS_SRC, req_info->src))
return -EMSGSIZE;
if (!ret && test_bit(ETHTOOL_STATS_ETH_PHY, req_info->stat_mask))
ret = stats_put_stats(skb, data, ETHTOOL_STATS_ETH_PHY,
ETH_SS_STATS_ETH_PHY,
stats_put_phy_stats);
if (!ret && test_bit(ETHTOOL_STATS_ETH_MAC, req_info->stat_mask))
ret = stats_put_stats(skb, data, ETHTOOL_STATS_ETH_MAC,
ETH_SS_STATS_ETH_MAC,
stats_put_mac_stats);
if (!ret && test_bit(ETHTOOL_STATS_ETH_CTRL, req_info->stat_mask))
ret = stats_put_stats(skb, data, ETHTOOL_STATS_ETH_CTRL,
ETH_SS_STATS_ETH_CTRL,
stats_put_ctrl_stats);
if (!ret && test_bit(ETHTOOL_STATS_RMON, req_info->stat_mask))
ret = stats_put_stats(skb, data, ETHTOOL_STATS_RMON,
ETH_SS_STATS_RMON, stats_put_rmon_stats);
return ret;
}
const struct ethnl_request_ops ethnl_stats_request_ops = {
.request_cmd = ETHTOOL_MSG_STATS_GET,
.reply_cmd = ETHTOOL_MSG_STATS_GET_REPLY,
.hdr_attr = ETHTOOL_A_STATS_HEADER,
.req_info_size = sizeof(struct stats_req_info),
.reply_data_size = sizeof(struct stats_reply_data),
.parse_request = stats_parse_request,
.prepare_data = stats_prepare_data,
.reply_size = stats_reply_size,
.fill_reply = stats_fill_reply,
};
static u64 ethtool_stats_sum(u64 a, u64 b)
{
if (a == ETHTOOL_STAT_NOT_SET)
return b;
if (b == ETHTOOL_STAT_NOT_SET)
return a;
return a + b;
}
/* Avoid modifying the aggregation procedure every time a new counter is added
* by treating the structures as an array of u64 statistics.
*/
static void ethtool_aggregate_stats(void *aggr_stats, const void *emac_stats,
const void *pmac_stats, size_t stats_size,
size_t stats_offset)
{
size_t num_stats = stats_size / sizeof(u64);
const u64 *s1 = emac_stats + stats_offset;
const u64 *s2 = pmac_stats + stats_offset;
u64 *s = aggr_stats + stats_offset;
int i;
for (i = 0; i < num_stats; i++)
s[i] = ethtool_stats_sum(s1[i], s2[i]);
}
void ethtool_aggregate_mac_stats(struct net_device *dev,
struct ethtool_eth_mac_stats *mac_stats)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct ethtool_eth_mac_stats pmac, emac;
memset(&emac, 0xff, sizeof(emac));
memset(&pmac, 0xff, sizeof(pmac));
emac.src = ETHTOOL_MAC_STATS_SRC_EMAC;
pmac.src = ETHTOOL_MAC_STATS_SRC_PMAC;
ops->get_eth_mac_stats(dev, &emac);
ops->get_eth_mac_stats(dev, &pmac);
ethtool_aggregate_stats(mac_stats, &emac, &pmac,
sizeof(mac_stats->stats),
offsetof(struct ethtool_eth_mac_stats, stats));
}
EXPORT_SYMBOL(ethtool_aggregate_mac_stats);
void ethtool_aggregate_phy_stats(struct net_device *dev,
struct ethtool_eth_phy_stats *phy_stats)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct ethtool_eth_phy_stats pmac, emac;
memset(&emac, 0xff, sizeof(emac));
memset(&pmac, 0xff, sizeof(pmac));
emac.src = ETHTOOL_MAC_STATS_SRC_EMAC;
pmac.src = ETHTOOL_MAC_STATS_SRC_PMAC;
ops->get_eth_phy_stats(dev, &emac);
ops->get_eth_phy_stats(dev, &pmac);
ethtool_aggregate_stats(phy_stats, &emac, &pmac,
sizeof(phy_stats->stats),
offsetof(struct ethtool_eth_phy_stats, stats));
}
EXPORT_SYMBOL(ethtool_aggregate_phy_stats);
void ethtool_aggregate_ctrl_stats(struct net_device *dev,
struct ethtool_eth_ctrl_stats *ctrl_stats)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct ethtool_eth_ctrl_stats pmac, emac;
memset(&emac, 0xff, sizeof(emac));
memset(&pmac, 0xff, sizeof(pmac));
emac.src = ETHTOOL_MAC_STATS_SRC_EMAC;
pmac.src = ETHTOOL_MAC_STATS_SRC_PMAC;
ops->get_eth_ctrl_stats(dev, &emac);
ops->get_eth_ctrl_stats(dev, &pmac);
ethtool_aggregate_stats(ctrl_stats, &emac, &pmac,
sizeof(ctrl_stats->stats),
offsetof(struct ethtool_eth_ctrl_stats, stats));
}
EXPORT_SYMBOL(ethtool_aggregate_ctrl_stats);
void ethtool_aggregate_pause_stats(struct net_device *dev,
struct ethtool_pause_stats *pause_stats)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct ethtool_pause_stats pmac, emac;
memset(&emac, 0xff, sizeof(emac));
memset(&pmac, 0xff, sizeof(pmac));
emac.src = ETHTOOL_MAC_STATS_SRC_EMAC;
pmac.src = ETHTOOL_MAC_STATS_SRC_PMAC;
ops->get_pause_stats(dev, &emac);
ops->get_pause_stats(dev, &pmac);
ethtool_aggregate_stats(pause_stats, &emac, &pmac,
sizeof(pause_stats->stats),
offsetof(struct ethtool_pause_stats, stats));
}
EXPORT_SYMBOL(ethtool_aggregate_pause_stats);
void ethtool_aggregate_rmon_stats(struct net_device *dev,
struct ethtool_rmon_stats *rmon_stats)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
const struct ethtool_rmon_hist_range *dummy;
struct ethtool_rmon_stats pmac, emac;
memset(&emac, 0xff, sizeof(emac));
memset(&pmac, 0xff, sizeof(pmac));
emac.src = ETHTOOL_MAC_STATS_SRC_EMAC;
pmac.src = ETHTOOL_MAC_STATS_SRC_PMAC;
ops->get_rmon_stats(dev, &emac, &dummy);
ops->get_rmon_stats(dev, &pmac, &dummy);
ethtool_aggregate_stats(rmon_stats, &emac, &pmac,
sizeof(rmon_stats->stats),
offsetof(struct ethtool_rmon_stats, stats));
}
EXPORT_SYMBOL(ethtool_aggregate_rmon_stats);
| linux-master | net/ethtool/stats.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
struct linkinfo_req_info {
struct ethnl_req_info base;
};
struct linkinfo_reply_data {
struct ethnl_reply_data base;
struct ethtool_link_ksettings ksettings;
struct ethtool_link_settings *lsettings;
};
#define LINKINFO_REPDATA(__reply_base) \
container_of(__reply_base, struct linkinfo_reply_data, base)
const struct nla_policy ethnl_linkinfo_get_policy[] = {
[ETHTOOL_A_LINKINFO_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int linkinfo_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct linkinfo_reply_data *data = LINKINFO_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
data->lsettings = &data->ksettings.base;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
ret = __ethtool_get_link_ksettings(dev, &data->ksettings);
if (ret < 0 && info)
GENL_SET_ERR_MSG(info, "failed to retrieve link settings");
ethnl_ops_complete(dev);
return ret;
}
static int linkinfo_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
return nla_total_size(sizeof(u8)) /* LINKINFO_PORT */
+ nla_total_size(sizeof(u8)) /* LINKINFO_PHYADDR */
+ nla_total_size(sizeof(u8)) /* LINKINFO_TP_MDIX */
+ nla_total_size(sizeof(u8)) /* LINKINFO_TP_MDIX_CTRL */
+ nla_total_size(sizeof(u8)) /* LINKINFO_TRANSCEIVER */
+ 0;
}
static int linkinfo_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct linkinfo_reply_data *data = LINKINFO_REPDATA(reply_base);
if (nla_put_u8(skb, ETHTOOL_A_LINKINFO_PORT, data->lsettings->port) ||
nla_put_u8(skb, ETHTOOL_A_LINKINFO_PHYADDR,
data->lsettings->phy_address) ||
nla_put_u8(skb, ETHTOOL_A_LINKINFO_TP_MDIX,
data->lsettings->eth_tp_mdix) ||
nla_put_u8(skb, ETHTOOL_A_LINKINFO_TP_MDIX_CTRL,
data->lsettings->eth_tp_mdix_ctrl) ||
nla_put_u8(skb, ETHTOOL_A_LINKINFO_TRANSCEIVER,
data->lsettings->transceiver))
return -EMSGSIZE;
return 0;
}
/* LINKINFO_SET */
const struct nla_policy ethnl_linkinfo_set_policy[] = {
[ETHTOOL_A_LINKINFO_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_LINKINFO_PORT] = { .type = NLA_U8 },
[ETHTOOL_A_LINKINFO_PHYADDR] = { .type = NLA_U8 },
[ETHTOOL_A_LINKINFO_TP_MDIX_CTRL] = { .type = NLA_U8 },
};
static int
ethnl_set_linkinfo_validate(struct ethnl_req_info *req_info,
struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
if (!ops->get_link_ksettings || !ops->set_link_ksettings)
return -EOPNOTSUPP;
return 1;
}
static int
ethnl_set_linkinfo(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct ethtool_link_ksettings ksettings = {};
struct ethtool_link_settings *lsettings;
struct net_device *dev = req_info->dev;
struct nlattr **tb = info->attrs;
bool mod = false;
int ret;
ret = __ethtool_get_link_ksettings(dev, &ksettings);
if (ret < 0) {
GENL_SET_ERR_MSG(info, "failed to retrieve link settings");
return ret;
}
lsettings = &ksettings.base;
ethnl_update_u8(&lsettings->port, tb[ETHTOOL_A_LINKINFO_PORT], &mod);
ethnl_update_u8(&lsettings->phy_address, tb[ETHTOOL_A_LINKINFO_PHYADDR],
&mod);
ethnl_update_u8(&lsettings->eth_tp_mdix_ctrl,
tb[ETHTOOL_A_LINKINFO_TP_MDIX_CTRL], &mod);
if (!mod)
return 0;
ret = dev->ethtool_ops->set_link_ksettings(dev, &ksettings);
if (ret < 0) {
GENL_SET_ERR_MSG(info, "link settings update failed");
return ret;
}
return 1;
}
const struct ethnl_request_ops ethnl_linkinfo_request_ops = {
.request_cmd = ETHTOOL_MSG_LINKINFO_GET,
.reply_cmd = ETHTOOL_MSG_LINKINFO_GET_REPLY,
.hdr_attr = ETHTOOL_A_LINKINFO_HEADER,
.req_info_size = sizeof(struct linkinfo_req_info),
.reply_data_size = sizeof(struct linkinfo_reply_data),
.prepare_data = linkinfo_prepare_data,
.reply_size = linkinfo_reply_size,
.fill_reply = linkinfo_fill_reply,
.set_validate = ethnl_set_linkinfo_validate,
.set = ethnl_set_linkinfo,
.set_ntf_cmd = ETHTOOL_MSG_LINKINFO_NTF,
};
| linux-master | net/ethtool/linkinfo.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/phy.h>
#include <linux/ethtool_netlink.h>
#include "netlink.h"
#include "common.h"
struct plca_req_info {
struct ethnl_req_info base;
};
struct plca_reply_data {
struct ethnl_reply_data base;
struct phy_plca_cfg plca_cfg;
struct phy_plca_status plca_st;
};
// Helpers ------------------------------------------------------------------ //
#define PLCA_REPDATA(__reply_base) \
container_of(__reply_base, struct plca_reply_data, base)
static void plca_update_sint(int *dst, const struct nlattr *attr,
bool *mod)
{
if (!attr)
return;
*dst = nla_get_u32(attr);
*mod = true;
}
// PLCA get configuration message ------------------------------------------- //
const struct nla_policy ethnl_plca_get_cfg_policy[] = {
[ETHTOOL_A_PLCA_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int plca_get_cfg_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct plca_reply_data *data = PLCA_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
const struct ethtool_phy_ops *ops;
int ret;
// check that the PHY device is available and connected
if (!dev->phydev) {
ret = -EOPNOTSUPP;
goto out;
}
// note: rtnl_lock is held already by ethnl_default_doit
ops = ethtool_phy_ops;
if (!ops || !ops->get_plca_cfg) {
ret = -EOPNOTSUPP;
goto out;
}
ret = ethnl_ops_begin(dev);
if (ret < 0)
goto out;
memset(&data->plca_cfg, 0xff,
sizeof_field(struct plca_reply_data, plca_cfg));
ret = ops->get_plca_cfg(dev->phydev, &data->plca_cfg);
ethnl_ops_complete(dev);
out:
return ret;
}
static int plca_get_cfg_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
return nla_total_size(sizeof(u16)) + /* _VERSION */
nla_total_size(sizeof(u8)) + /* _ENABLED */
nla_total_size(sizeof(u32)) + /* _NODE_CNT */
nla_total_size(sizeof(u32)) + /* _NODE_ID */
nla_total_size(sizeof(u32)) + /* _TO_TIMER */
nla_total_size(sizeof(u32)) + /* _BURST_COUNT */
nla_total_size(sizeof(u32)); /* _BURST_TIMER */
}
static int plca_get_cfg_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct plca_reply_data *data = PLCA_REPDATA(reply_base);
const struct phy_plca_cfg *plca = &data->plca_cfg;
if ((plca->version >= 0 &&
nla_put_u16(skb, ETHTOOL_A_PLCA_VERSION, plca->version)) ||
(plca->enabled >= 0 &&
nla_put_u8(skb, ETHTOOL_A_PLCA_ENABLED, !!plca->enabled)) ||
(plca->node_id >= 0 &&
nla_put_u32(skb, ETHTOOL_A_PLCA_NODE_ID, plca->node_id)) ||
(plca->node_cnt >= 0 &&
nla_put_u32(skb, ETHTOOL_A_PLCA_NODE_CNT, plca->node_cnt)) ||
(plca->to_tmr >= 0 &&
nla_put_u32(skb, ETHTOOL_A_PLCA_TO_TMR, plca->to_tmr)) ||
(plca->burst_cnt >= 0 &&
nla_put_u32(skb, ETHTOOL_A_PLCA_BURST_CNT, plca->burst_cnt)) ||
(plca->burst_tmr >= 0 &&
nla_put_u32(skb, ETHTOOL_A_PLCA_BURST_TMR, plca->burst_tmr)))
return -EMSGSIZE;
return 0;
};
// PLCA set configuration message ------------------------------------------- //
const struct nla_policy ethnl_plca_set_cfg_policy[] = {
[ETHTOOL_A_PLCA_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_PLCA_ENABLED] = NLA_POLICY_MAX(NLA_U8, 1),
[ETHTOOL_A_PLCA_NODE_ID] = NLA_POLICY_MAX(NLA_U32, 255),
[ETHTOOL_A_PLCA_NODE_CNT] = NLA_POLICY_RANGE(NLA_U32, 1, 255),
[ETHTOOL_A_PLCA_TO_TMR] = NLA_POLICY_MAX(NLA_U32, 255),
[ETHTOOL_A_PLCA_BURST_CNT] = NLA_POLICY_MAX(NLA_U32, 255),
[ETHTOOL_A_PLCA_BURST_TMR] = NLA_POLICY_MAX(NLA_U32, 255),
};
static int
ethnl_set_plca(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct net_device *dev = req_info->dev;
const struct ethtool_phy_ops *ops;
struct nlattr **tb = info->attrs;
struct phy_plca_cfg plca_cfg;
bool mod = false;
int ret;
// check that the PHY device is available and connected
if (!dev->phydev)
return -EOPNOTSUPP;
ops = ethtool_phy_ops;
if (!ops || !ops->set_plca_cfg)
return -EOPNOTSUPP;
memset(&plca_cfg, 0xff, sizeof(plca_cfg));
plca_update_sint(&plca_cfg.enabled, tb[ETHTOOL_A_PLCA_ENABLED], &mod);
plca_update_sint(&plca_cfg.node_id, tb[ETHTOOL_A_PLCA_NODE_ID], &mod);
plca_update_sint(&plca_cfg.node_cnt, tb[ETHTOOL_A_PLCA_NODE_CNT], &mod);
plca_update_sint(&plca_cfg.to_tmr, tb[ETHTOOL_A_PLCA_TO_TMR], &mod);
plca_update_sint(&plca_cfg.burst_cnt, tb[ETHTOOL_A_PLCA_BURST_CNT],
&mod);
plca_update_sint(&plca_cfg.burst_tmr, tb[ETHTOOL_A_PLCA_BURST_TMR],
&mod);
if (!mod)
return 0;
ret = ops->set_plca_cfg(dev->phydev, &plca_cfg, info->extack);
return ret < 0 ? ret : 1;
}
const struct ethnl_request_ops ethnl_plca_cfg_request_ops = {
.request_cmd = ETHTOOL_MSG_PLCA_GET_CFG,
.reply_cmd = ETHTOOL_MSG_PLCA_GET_CFG_REPLY,
.hdr_attr = ETHTOOL_A_PLCA_HEADER,
.req_info_size = sizeof(struct plca_req_info),
.reply_data_size = sizeof(struct plca_reply_data),
.prepare_data = plca_get_cfg_prepare_data,
.reply_size = plca_get_cfg_reply_size,
.fill_reply = plca_get_cfg_fill_reply,
.set = ethnl_set_plca,
.set_ntf_cmd = ETHTOOL_MSG_PLCA_NTF,
};
// PLCA get status message -------------------------------------------------- //
const struct nla_policy ethnl_plca_get_status_policy[] = {
[ETHTOOL_A_PLCA_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int plca_get_status_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct plca_reply_data *data = PLCA_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
const struct ethtool_phy_ops *ops;
int ret;
// check that the PHY device is available and connected
if (!dev->phydev) {
ret = -EOPNOTSUPP;
goto out;
}
// note: rtnl_lock is held already by ethnl_default_doit
ops = ethtool_phy_ops;
if (!ops || !ops->get_plca_status) {
ret = -EOPNOTSUPP;
goto out;
}
ret = ethnl_ops_begin(dev);
if (ret < 0)
goto out;
memset(&data->plca_st, 0xff,
sizeof_field(struct plca_reply_data, plca_st));
ret = ops->get_plca_status(dev->phydev, &data->plca_st);
ethnl_ops_complete(dev);
out:
return ret;
}
static int plca_get_status_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
return nla_total_size(sizeof(u8)); /* _STATUS */
}
static int plca_get_status_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct plca_reply_data *data = PLCA_REPDATA(reply_base);
const u8 status = data->plca_st.pst;
if (nla_put_u8(skb, ETHTOOL_A_PLCA_STATUS, !!status))
return -EMSGSIZE;
return 0;
};
const struct ethnl_request_ops ethnl_plca_status_request_ops = {
.request_cmd = ETHTOOL_MSG_PLCA_GET_STATUS,
.reply_cmd = ETHTOOL_MSG_PLCA_GET_STATUS_REPLY,
.hdr_attr = ETHTOOL_A_PLCA_HEADER,
.req_info_size = sizeof(struct plca_req_info),
.reply_data_size = sizeof(struct plca_reply_data),
.prepare_data = plca_get_status_prepare_data,
.reply_size = plca_get_status_reply_size,
.fill_reply = plca_get_status_fill_reply,
};
| linux-master | net/ethtool/plca.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
#include "bitset.h"
struct debug_req_info {
struct ethnl_req_info base;
};
struct debug_reply_data {
struct ethnl_reply_data base;
u32 msg_mask;
};
#define DEBUG_REPDATA(__reply_base) \
container_of(__reply_base, struct debug_reply_data, base)
const struct nla_policy ethnl_debug_get_policy[] = {
[ETHTOOL_A_DEBUG_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int debug_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct debug_reply_data *data = DEBUG_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
if (!dev->ethtool_ops->get_msglevel)
return -EOPNOTSUPP;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
data->msg_mask = dev->ethtool_ops->get_msglevel(dev);
ethnl_ops_complete(dev);
return 0;
}
static int debug_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct debug_reply_data *data = DEBUG_REPDATA(reply_base);
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
return ethnl_bitset32_size(&data->msg_mask, NULL, NETIF_MSG_CLASS_COUNT,
netif_msg_class_names, compact);
}
static int debug_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct debug_reply_data *data = DEBUG_REPDATA(reply_base);
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
return ethnl_put_bitset32(skb, ETHTOOL_A_DEBUG_MSGMASK, &data->msg_mask,
NULL, NETIF_MSG_CLASS_COUNT,
netif_msg_class_names, compact);
}
/* DEBUG_SET */
const struct nla_policy ethnl_debug_set_policy[] = {
[ETHTOOL_A_DEBUG_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_DEBUG_MSGMASK] = { .type = NLA_NESTED },
};
static int
ethnl_set_debug_validate(struct ethnl_req_info *req_info,
struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
return ops->get_msglevel && ops->set_msglevel ? 1 : -EOPNOTSUPP;
}
static int
ethnl_set_debug(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct net_device *dev = req_info->dev;
struct nlattr **tb = info->attrs;
bool mod = false;
u32 msg_mask;
int ret;
msg_mask = dev->ethtool_ops->get_msglevel(dev);
ret = ethnl_update_bitset32(&msg_mask, NETIF_MSG_CLASS_COUNT,
tb[ETHTOOL_A_DEBUG_MSGMASK],
netif_msg_class_names, info->extack, &mod);
if (ret < 0 || !mod)
return ret;
dev->ethtool_ops->set_msglevel(dev, msg_mask);
return 1;
}
const struct ethnl_request_ops ethnl_debug_request_ops = {
.request_cmd = ETHTOOL_MSG_DEBUG_GET,
.reply_cmd = ETHTOOL_MSG_DEBUG_GET_REPLY,
.hdr_attr = ETHTOOL_A_DEBUG_HEADER,
.req_info_size = sizeof(struct debug_req_info),
.reply_data_size = sizeof(struct debug_reply_data),
.prepare_data = debug_prepare_data,
.reply_size = debug_reply_size,
.fill_reply = debug_fill_reply,
.set_validate = ethnl_set_debug_validate,
.set = ethnl_set_debug,
.set_ntf_cmd = ETHTOOL_MSG_DEBUG_NTF,
};
| linux-master | net/ethtool/debug.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/ethtool.h>
#include <linux/sfp.h>
#include "netlink.h"
#include "common.h"
struct eeprom_req_info {
struct ethnl_req_info base;
u32 offset;
u32 length;
u8 page;
u8 bank;
u8 i2c_address;
};
struct eeprom_reply_data {
struct ethnl_reply_data base;
u32 length;
u8 *data;
};
#define MODULE_EEPROM_REQINFO(__req_base) \
container_of(__req_base, struct eeprom_req_info, base)
#define MODULE_EEPROM_REPDATA(__reply_base) \
container_of(__reply_base, struct eeprom_reply_data, base)
static int fallback_set_params(struct eeprom_req_info *request,
struct ethtool_modinfo *modinfo,
struct ethtool_eeprom *eeprom)
{
u32 offset = request->offset;
u32 length = request->length;
if (request->page)
offset = request->page * ETH_MODULE_EEPROM_PAGE_LEN + offset;
if (modinfo->type == ETH_MODULE_SFF_8472 &&
request->i2c_address == 0x51)
offset += ETH_MODULE_EEPROM_PAGE_LEN * 2;
if (offset >= modinfo->eeprom_len)
return -EINVAL;
eeprom->cmd = ETHTOOL_GMODULEEEPROM;
eeprom->len = length;
eeprom->offset = offset;
return 0;
}
static int eeprom_fallback(struct eeprom_req_info *request,
struct eeprom_reply_data *reply)
{
struct net_device *dev = reply->base.dev;
struct ethtool_modinfo modinfo = {0};
struct ethtool_eeprom eeprom = {0};
u8 *data;
int err;
modinfo.cmd = ETHTOOL_GMODULEINFO;
err = ethtool_get_module_info_call(dev, &modinfo);
if (err < 0)
return err;
err = fallback_set_params(request, &modinfo, &eeprom);
if (err < 0)
return err;
data = kmalloc(eeprom.len, GFP_KERNEL);
if (!data)
return -ENOMEM;
err = ethtool_get_module_eeprom_call(dev, &eeprom, data);
if (err < 0)
goto err_out;
reply->data = data;
reply->length = eeprom.len;
return 0;
err_out:
kfree(data);
return err;
}
static int get_module_eeprom_by_page(struct net_device *dev,
struct ethtool_module_eeprom *page_data,
struct netlink_ext_ack *extack)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
if (dev->sfp_bus)
return sfp_get_module_eeprom_by_page(dev->sfp_bus, page_data, extack);
if (ops->get_module_eeprom_by_page)
return ops->get_module_eeprom_by_page(dev, page_data, extack);
return -EOPNOTSUPP;
}
static int eeprom_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct eeprom_reply_data *reply = MODULE_EEPROM_REPDATA(reply_base);
struct eeprom_req_info *request = MODULE_EEPROM_REQINFO(req_base);
struct ethtool_module_eeprom page_data = {0};
struct net_device *dev = reply_base->dev;
int ret;
page_data.offset = request->offset;
page_data.length = request->length;
page_data.i2c_address = request->i2c_address;
page_data.page = request->page;
page_data.bank = request->bank;
page_data.data = kmalloc(page_data.length, GFP_KERNEL);
if (!page_data.data)
return -ENOMEM;
ret = ethnl_ops_begin(dev);
if (ret)
goto err_free;
ret = get_module_eeprom_by_page(dev, &page_data, info->extack);
if (ret < 0)
goto err_ops;
reply->length = ret;
reply->data = page_data.data;
ethnl_ops_complete(dev);
return 0;
err_ops:
ethnl_ops_complete(dev);
err_free:
kfree(page_data.data);
if (ret == -EOPNOTSUPP)
return eeprom_fallback(request, reply);
return ret;
}
static int eeprom_parse_request(struct ethnl_req_info *req_info, struct nlattr **tb,
struct netlink_ext_ack *extack)
{
struct eeprom_req_info *request = MODULE_EEPROM_REQINFO(req_info);
if (!tb[ETHTOOL_A_MODULE_EEPROM_OFFSET] ||
!tb[ETHTOOL_A_MODULE_EEPROM_LENGTH] ||
!tb[ETHTOOL_A_MODULE_EEPROM_PAGE] ||
!tb[ETHTOOL_A_MODULE_EEPROM_I2C_ADDRESS])
return -EINVAL;
request->i2c_address = nla_get_u8(tb[ETHTOOL_A_MODULE_EEPROM_I2C_ADDRESS]);
request->offset = nla_get_u32(tb[ETHTOOL_A_MODULE_EEPROM_OFFSET]);
request->length = nla_get_u32(tb[ETHTOOL_A_MODULE_EEPROM_LENGTH]);
/* The following set of conditions limit the API to only dump 1/2
* EEPROM page without crossing low page boundary located at offset 128.
* This means user may only request dumps of length limited to 128 from
* either low 128 bytes or high 128 bytes.
* For pages higher than 0 only high 128 bytes are accessible.
*/
request->page = nla_get_u8(tb[ETHTOOL_A_MODULE_EEPROM_PAGE]);
if (request->page && request->offset < ETH_MODULE_EEPROM_PAGE_LEN) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_MODULE_EEPROM_PAGE],
"reading from lower half page is allowed for page 0 only");
return -EINVAL;
}
if (request->offset < ETH_MODULE_EEPROM_PAGE_LEN &&
request->offset + request->length > ETH_MODULE_EEPROM_PAGE_LEN) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_MODULE_EEPROM_LENGTH],
"reading cross half page boundary is illegal");
return -EINVAL;
} else if (request->offset + request->length > ETH_MODULE_EEPROM_PAGE_LEN * 2) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_MODULE_EEPROM_LENGTH],
"reading cross page boundary is illegal");
return -EINVAL;
}
if (tb[ETHTOOL_A_MODULE_EEPROM_BANK])
request->bank = nla_get_u8(tb[ETHTOOL_A_MODULE_EEPROM_BANK]);
return 0;
}
static int eeprom_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct eeprom_req_info *request = MODULE_EEPROM_REQINFO(req_base);
return nla_total_size(sizeof(u8) * request->length); /* _EEPROM_DATA */
}
static int eeprom_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
struct eeprom_reply_data *reply = MODULE_EEPROM_REPDATA(reply_base);
return nla_put(skb, ETHTOOL_A_MODULE_EEPROM_DATA, reply->length, reply->data);
}
static void eeprom_cleanup_data(struct ethnl_reply_data *reply_base)
{
struct eeprom_reply_data *reply = MODULE_EEPROM_REPDATA(reply_base);
kfree(reply->data);
}
const struct ethnl_request_ops ethnl_module_eeprom_request_ops = {
.request_cmd = ETHTOOL_MSG_MODULE_EEPROM_GET,
.reply_cmd = ETHTOOL_MSG_MODULE_EEPROM_GET_REPLY,
.hdr_attr = ETHTOOL_A_MODULE_EEPROM_HEADER,
.req_info_size = sizeof(struct eeprom_req_info),
.reply_data_size = sizeof(struct eeprom_reply_data),
.parse_request = eeprom_parse_request,
.prepare_data = eeprom_prepare_data,
.reply_size = eeprom_reply_size,
.fill_reply = eeprom_fill_reply,
.cleanup_data = eeprom_cleanup_data,
};
const struct nla_policy ethnl_module_eeprom_get_policy[] = {
[ETHTOOL_A_MODULE_EEPROM_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_MODULE_EEPROM_OFFSET] =
NLA_POLICY_MAX(NLA_U32, ETH_MODULE_EEPROM_PAGE_LEN * 2 - 1),
[ETHTOOL_A_MODULE_EEPROM_LENGTH] =
NLA_POLICY_RANGE(NLA_U32, 1, ETH_MODULE_EEPROM_PAGE_LEN),
[ETHTOOL_A_MODULE_EEPROM_PAGE] = { .type = NLA_U8 },
[ETHTOOL_A_MODULE_EEPROM_BANK] = { .type = NLA_U8 },
[ETHTOOL_A_MODULE_EEPROM_I2C_ADDRESS] =
NLA_POLICY_RANGE(NLA_U8, 0, ETH_MODULE_MAX_I2C_ADDRESS),
};
| linux-master | net/ethtool/eeprom.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/ethtool_netlink.h>
#include <linux/bitmap.h>
#include "netlink.h"
#include "bitset.h"
/* Some bitmaps are internally represented as an array of unsigned long, some
* as an array of u32 (some even as single u32 for now). To avoid the need of
* wrappers on caller side, we provide two set of functions: those with "32"
* suffix in their names expect u32 based bitmaps, those without it expect
* unsigned long bitmaps.
*/
static u32 ethnl_lower_bits(unsigned int n)
{
return ~(u32)0 >> (32 - n % 32);
}
static u32 ethnl_upper_bits(unsigned int n)
{
return ~(u32)0 << (n % 32);
}
/**
* ethnl_bitmap32_clear() - Clear u32 based bitmap
* @dst: bitmap to clear
* @start: beginning of the interval
* @end: end of the interval
* @mod: set if bitmap was modified
*
* Clear @nbits bits of a bitmap with indices @start <= i < @end
*/
static void ethnl_bitmap32_clear(u32 *dst, unsigned int start, unsigned int end,
bool *mod)
{
unsigned int start_word = start / 32;
unsigned int end_word = end / 32;
unsigned int i;
u32 mask;
if (end <= start)
return;
if (start % 32) {
mask = ethnl_upper_bits(start);
if (end_word == start_word) {
mask &= ethnl_lower_bits(end);
if (dst[start_word] & mask) {
dst[start_word] &= ~mask;
*mod = true;
}
return;
}
if (dst[start_word] & mask) {
dst[start_word] &= ~mask;
*mod = true;
}
start_word++;
}
for (i = start_word; i < end_word; i++) {
if (dst[i]) {
dst[i] = 0;
*mod = true;
}
}
if (end % 32) {
mask = ethnl_lower_bits(end);
if (dst[end_word] & mask) {
dst[end_word] &= ~mask;
*mod = true;
}
}
}
/**
* ethnl_bitmap32_not_zero() - Check if any bit is set in an interval
* @map: bitmap to test
* @start: beginning of the interval
* @end: end of the interval
*
* Return: true if there is non-zero bit with index @start <= i < @end,
* false if the whole interval is zero
*/
static bool ethnl_bitmap32_not_zero(const u32 *map, unsigned int start,
unsigned int end)
{
unsigned int start_word = start / 32;
unsigned int end_word = end / 32;
u32 mask;
if (end <= start)
return true;
if (start % 32) {
mask = ethnl_upper_bits(start);
if (end_word == start_word) {
mask &= ethnl_lower_bits(end);
return map[start_word] & mask;
}
if (map[start_word] & mask)
return true;
start_word++;
}
if (!memchr_inv(map + start_word, '\0',
(end_word - start_word) * sizeof(u32)))
return true;
if (end % 32 == 0)
return true;
return map[end_word] & ethnl_lower_bits(end);
}
/**
* ethnl_bitmap32_update() - Modify u32 based bitmap according to value/mask
* pair
* @dst: bitmap to update
* @nbits: bit size of the bitmap
* @value: values to set
* @mask: mask of bits to set
* @mod: set to true if bitmap is modified, preserve if not
*
* Set bits in @dst bitmap which are set in @mask to values from @value, leave
* the rest untouched. If destination bitmap was modified, set @mod to true,
* leave as it is if not.
*/
static void ethnl_bitmap32_update(u32 *dst, unsigned int nbits,
const u32 *value, const u32 *mask, bool *mod)
{
while (nbits > 0) {
u32 real_mask = mask ? *mask : ~(u32)0;
u32 new_value;
if (nbits < 32)
real_mask &= ethnl_lower_bits(nbits);
new_value = (*dst & ~real_mask) | (*value & real_mask);
if (new_value != *dst) {
*dst = new_value;
*mod = true;
}
if (nbits <= 32)
break;
dst++;
nbits -= 32;
value++;
if (mask)
mask++;
}
}
static bool ethnl_bitmap32_test_bit(const u32 *map, unsigned int index)
{
return map[index / 32] & (1U << (index % 32));
}
/**
* ethnl_bitset32_size() - Calculate size of bitset nested attribute
* @val: value bitmap (u32 based)
* @mask: mask bitmap (u32 based, optional)
* @nbits: bit length of the bitset
* @names: array of bit names (optional)
* @compact: assume compact format for output
*
* Estimate length of netlink attribute composed by a later call to
* ethnl_put_bitset32() call with the same arguments.
*
* Return: negative error code or attribute length estimate
*/
int ethnl_bitset32_size(const u32 *val, const u32 *mask, unsigned int nbits,
ethnl_string_array_t names, bool compact)
{
unsigned int len = 0;
/* list flag */
if (!mask)
len += nla_total_size(sizeof(u32));
/* size */
len += nla_total_size(sizeof(u32));
if (compact) {
unsigned int nwords = DIV_ROUND_UP(nbits, 32);
/* value, mask */
len += (mask ? 2 : 1) * nla_total_size(nwords * sizeof(u32));
} else {
unsigned int bits_len = 0;
unsigned int bit_len, i;
for (i = 0; i < nbits; i++) {
const char *name = names ? names[i] : NULL;
if (!ethnl_bitmap32_test_bit(mask ?: val, i))
continue;
/* index */
bit_len = nla_total_size(sizeof(u32));
/* name */
if (name)
bit_len += ethnl_strz_size(name);
/* value */
if (mask && ethnl_bitmap32_test_bit(val, i))
bit_len += nla_total_size(0);
/* bit nest */
bits_len += nla_total_size(bit_len);
}
/* bits nest */
len += nla_total_size(bits_len);
}
/* outermost nest */
return nla_total_size(len);
}
/**
* ethnl_put_bitset32() - Put a bitset nest into a message
* @skb: skb with the message
* @attrtype: attribute type for the bitset nest
* @val: value bitmap (u32 based)
* @mask: mask bitmap (u32 based, optional)
* @nbits: bit length of the bitset
* @names: array of bit names (optional)
* @compact: use compact format for the output
*
* Compose a nested attribute representing a bitset. If @mask is null, simple
* bitmap (bit list) is created, if @mask is provided, represent a value/mask
* pair. Bit names are only used in verbose mode and when provided by calller.
*
* Return: 0 on success, negative error value on error
*/
int ethnl_put_bitset32(struct sk_buff *skb, int attrtype, const u32 *val,
const u32 *mask, unsigned int nbits,
ethnl_string_array_t names, bool compact)
{
struct nlattr *nest;
struct nlattr *attr;
nest = nla_nest_start(skb, attrtype);
if (!nest)
return -EMSGSIZE;
if (!mask && nla_put_flag(skb, ETHTOOL_A_BITSET_NOMASK))
goto nla_put_failure;
if (nla_put_u32(skb, ETHTOOL_A_BITSET_SIZE, nbits))
goto nla_put_failure;
if (compact) {
unsigned int nwords = DIV_ROUND_UP(nbits, 32);
unsigned int nbytes = nwords * sizeof(u32);
u32 *dst;
attr = nla_reserve(skb, ETHTOOL_A_BITSET_VALUE, nbytes);
if (!attr)
goto nla_put_failure;
dst = nla_data(attr);
memcpy(dst, val, nbytes);
if (nbits % 32)
dst[nwords - 1] &= ethnl_lower_bits(nbits);
if (mask) {
attr = nla_reserve(skb, ETHTOOL_A_BITSET_MASK, nbytes);
if (!attr)
goto nla_put_failure;
dst = nla_data(attr);
memcpy(dst, mask, nbytes);
if (nbits % 32)
dst[nwords - 1] &= ethnl_lower_bits(nbits);
}
} else {
struct nlattr *bits;
unsigned int i;
bits = nla_nest_start(skb, ETHTOOL_A_BITSET_BITS);
if (!bits)
goto nla_put_failure;
for (i = 0; i < nbits; i++) {
const char *name = names ? names[i] : NULL;
if (!ethnl_bitmap32_test_bit(mask ?: val, i))
continue;
attr = nla_nest_start(skb, ETHTOOL_A_BITSET_BITS_BIT);
if (!attr)
goto nla_put_failure;
if (nla_put_u32(skb, ETHTOOL_A_BITSET_BIT_INDEX, i))
goto nla_put_failure;
if (name &&
ethnl_put_strz(skb, ETHTOOL_A_BITSET_BIT_NAME, name))
goto nla_put_failure;
if (mask && ethnl_bitmap32_test_bit(val, i) &&
nla_put_flag(skb, ETHTOOL_A_BITSET_BIT_VALUE))
goto nla_put_failure;
nla_nest_end(skb, attr);
}
nla_nest_end(skb, bits);
}
nla_nest_end(skb, nest);
return 0;
nla_put_failure:
nla_nest_cancel(skb, nest);
return -EMSGSIZE;
}
static const struct nla_policy bitset_policy[] = {
[ETHTOOL_A_BITSET_NOMASK] = { .type = NLA_FLAG },
[ETHTOOL_A_BITSET_SIZE] = NLA_POLICY_MAX(NLA_U32,
ETHNL_MAX_BITSET_SIZE),
[ETHTOOL_A_BITSET_BITS] = { .type = NLA_NESTED },
[ETHTOOL_A_BITSET_VALUE] = { .type = NLA_BINARY },
[ETHTOOL_A_BITSET_MASK] = { .type = NLA_BINARY },
};
static const struct nla_policy bit_policy[] = {
[ETHTOOL_A_BITSET_BIT_INDEX] = { .type = NLA_U32 },
[ETHTOOL_A_BITSET_BIT_NAME] = { .type = NLA_NUL_STRING },
[ETHTOOL_A_BITSET_BIT_VALUE] = { .type = NLA_FLAG },
};
/**
* ethnl_bitset_is_compact() - check if bitset attribute represents a compact
* bitset
* @bitset: nested attribute representing a bitset
* @compact: pointer for return value
*
* Return: 0 on success, negative error code on failure
*/
int ethnl_bitset_is_compact(const struct nlattr *bitset, bool *compact)
{
struct nlattr *tb[ARRAY_SIZE(bitset_policy)];
int ret;
ret = nla_parse_nested(tb, ARRAY_SIZE(bitset_policy) - 1, bitset,
bitset_policy, NULL);
if (ret < 0)
return ret;
if (tb[ETHTOOL_A_BITSET_BITS]) {
if (tb[ETHTOOL_A_BITSET_VALUE] || tb[ETHTOOL_A_BITSET_MASK])
return -EINVAL;
*compact = false;
return 0;
}
if (!tb[ETHTOOL_A_BITSET_SIZE] || !tb[ETHTOOL_A_BITSET_VALUE])
return -EINVAL;
*compact = true;
return 0;
}
/**
* ethnl_name_to_idx() - look up string index for a name
* @names: array of ETH_GSTRING_LEN sized strings
* @n_names: number of strings in the array
* @name: name to look up
*
* Return: index of the string if found, -ENOENT if not found
*/
static int ethnl_name_to_idx(ethnl_string_array_t names, unsigned int n_names,
const char *name)
{
unsigned int i;
if (!names)
return -ENOENT;
for (i = 0; i < n_names; i++) {
/* names[i] may not be null terminated */
if (!strncmp(names[i], name, ETH_GSTRING_LEN) &&
strlen(name) <= ETH_GSTRING_LEN)
return i;
}
return -ENOENT;
}
static int ethnl_parse_bit(unsigned int *index, bool *val, unsigned int nbits,
const struct nlattr *bit_attr, bool no_mask,
ethnl_string_array_t names,
struct netlink_ext_ack *extack)
{
struct nlattr *tb[ARRAY_SIZE(bit_policy)];
int ret, idx;
ret = nla_parse_nested(tb, ARRAY_SIZE(bit_policy) - 1, bit_attr,
bit_policy, extack);
if (ret < 0)
return ret;
if (tb[ETHTOOL_A_BITSET_BIT_INDEX]) {
const char *name;
idx = nla_get_u32(tb[ETHTOOL_A_BITSET_BIT_INDEX]);
if (idx >= nbits) {
NL_SET_ERR_MSG_ATTR(extack,
tb[ETHTOOL_A_BITSET_BIT_INDEX],
"bit index too high");
return -EOPNOTSUPP;
}
name = names ? names[idx] : NULL;
if (tb[ETHTOOL_A_BITSET_BIT_NAME] && name &&
strncmp(nla_data(tb[ETHTOOL_A_BITSET_BIT_NAME]), name,
nla_len(tb[ETHTOOL_A_BITSET_BIT_NAME]))) {
NL_SET_ERR_MSG_ATTR(extack, bit_attr,
"bit index and name mismatch");
return -EINVAL;
}
} else if (tb[ETHTOOL_A_BITSET_BIT_NAME]) {
idx = ethnl_name_to_idx(names, nbits,
nla_data(tb[ETHTOOL_A_BITSET_BIT_NAME]));
if (idx < 0) {
NL_SET_ERR_MSG_ATTR(extack,
tb[ETHTOOL_A_BITSET_BIT_NAME],
"bit name not found");
return -EOPNOTSUPP;
}
} else {
NL_SET_ERR_MSG_ATTR(extack, bit_attr,
"neither bit index nor name specified");
return -EINVAL;
}
*index = idx;
*val = no_mask || tb[ETHTOOL_A_BITSET_BIT_VALUE];
return 0;
}
static int
ethnl_update_bitset32_verbose(u32 *bitmap, unsigned int nbits,
const struct nlattr *attr, struct nlattr **tb,
ethnl_string_array_t names,
struct netlink_ext_ack *extack, bool *mod)
{
struct nlattr *bit_attr;
bool no_mask;
int rem;
int ret;
if (tb[ETHTOOL_A_BITSET_VALUE]) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_BITSET_VALUE],
"value only allowed in compact bitset");
return -EINVAL;
}
if (tb[ETHTOOL_A_BITSET_MASK]) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_BITSET_MASK],
"mask only allowed in compact bitset");
return -EINVAL;
}
no_mask = tb[ETHTOOL_A_BITSET_NOMASK];
if (no_mask)
ethnl_bitmap32_clear(bitmap, 0, nbits, mod);
nla_for_each_nested(bit_attr, tb[ETHTOOL_A_BITSET_BITS], rem) {
bool old_val, new_val;
unsigned int idx;
if (nla_type(bit_attr) != ETHTOOL_A_BITSET_BITS_BIT) {
NL_SET_ERR_MSG_ATTR(extack, bit_attr,
"only ETHTOOL_A_BITSET_BITS_BIT allowed in ETHTOOL_A_BITSET_BITS");
return -EINVAL;
}
ret = ethnl_parse_bit(&idx, &new_val, nbits, bit_attr, no_mask,
names, extack);
if (ret < 0)
return ret;
old_val = bitmap[idx / 32] & ((u32)1 << (idx % 32));
if (new_val != old_val) {
if (new_val)
bitmap[idx / 32] |= ((u32)1 << (idx % 32));
else
bitmap[idx / 32] &= ~((u32)1 << (idx % 32));
*mod = true;
}
}
return 0;
}
static int ethnl_compact_sanity_checks(unsigned int nbits,
const struct nlattr *nest,
struct nlattr **tb,
struct netlink_ext_ack *extack)
{
bool no_mask = tb[ETHTOOL_A_BITSET_NOMASK];
unsigned int attr_nbits, attr_nwords;
const struct nlattr *test_attr;
if (no_mask && tb[ETHTOOL_A_BITSET_MASK]) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_BITSET_MASK],
"mask not allowed in list bitset");
return -EINVAL;
}
if (!tb[ETHTOOL_A_BITSET_SIZE]) {
NL_SET_ERR_MSG_ATTR(extack, nest,
"missing size in compact bitset");
return -EINVAL;
}
if (!tb[ETHTOOL_A_BITSET_VALUE]) {
NL_SET_ERR_MSG_ATTR(extack, nest,
"missing value in compact bitset");
return -EINVAL;
}
if (!no_mask && !tb[ETHTOOL_A_BITSET_MASK]) {
NL_SET_ERR_MSG_ATTR(extack, nest,
"missing mask in compact nonlist bitset");
return -EINVAL;
}
attr_nbits = nla_get_u32(tb[ETHTOOL_A_BITSET_SIZE]);
attr_nwords = DIV_ROUND_UP(attr_nbits, 32);
if (nla_len(tb[ETHTOOL_A_BITSET_VALUE]) != attr_nwords * sizeof(u32)) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_BITSET_VALUE],
"bitset value length does not match size");
return -EINVAL;
}
if (tb[ETHTOOL_A_BITSET_MASK] &&
nla_len(tb[ETHTOOL_A_BITSET_MASK]) != attr_nwords * sizeof(u32)) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_BITSET_MASK],
"bitset mask length does not match size");
return -EINVAL;
}
if (attr_nbits <= nbits)
return 0;
test_attr = no_mask ? tb[ETHTOOL_A_BITSET_VALUE] :
tb[ETHTOOL_A_BITSET_MASK];
if (ethnl_bitmap32_not_zero(nla_data(test_attr), nbits, attr_nbits)) {
NL_SET_ERR_MSG_ATTR(extack, test_attr,
"cannot modify bits past kernel bitset size");
return -EINVAL;
}
return 0;
}
/**
* ethnl_update_bitset32() - Apply a bitset nest to a u32 based bitmap
* @bitmap: bitmap to update
* @nbits: size of the updated bitmap in bits
* @attr: nest attribute to parse and apply
* @names: array of bit names; may be null for compact format
* @extack: extack for error reporting
* @mod: set this to true if bitmap is modified, leave as it is if not
*
* Apply bitset netsted attribute to a bitmap. If the attribute represents
* a bit list, @bitmap is set to its contents; otherwise, bits in mask are
* set to values from value. Bitmaps in the attribute may be longer than
* @nbits but the message must not request modifying any bits past @nbits.
*
* Return: negative error code on failure, 0 on success
*/
int ethnl_update_bitset32(u32 *bitmap, unsigned int nbits,
const struct nlattr *attr, ethnl_string_array_t names,
struct netlink_ext_ack *extack, bool *mod)
{
struct nlattr *tb[ARRAY_SIZE(bitset_policy)];
unsigned int change_bits;
bool no_mask;
int ret;
if (!attr)
return 0;
ret = nla_parse_nested(tb, ARRAY_SIZE(bitset_policy) - 1, attr,
bitset_policy, extack);
if (ret < 0)
return ret;
if (tb[ETHTOOL_A_BITSET_BITS])
return ethnl_update_bitset32_verbose(bitmap, nbits, attr, tb,
names, extack, mod);
ret = ethnl_compact_sanity_checks(nbits, attr, tb, extack);
if (ret < 0)
return ret;
no_mask = tb[ETHTOOL_A_BITSET_NOMASK];
change_bits = min_t(unsigned int,
nla_get_u32(tb[ETHTOOL_A_BITSET_SIZE]), nbits);
ethnl_bitmap32_update(bitmap, change_bits,
nla_data(tb[ETHTOOL_A_BITSET_VALUE]),
no_mask ? NULL :
nla_data(tb[ETHTOOL_A_BITSET_MASK]),
mod);
if (no_mask && change_bits < nbits)
ethnl_bitmap32_clear(bitmap, change_bits, nbits, mod);
return 0;
}
/**
* ethnl_parse_bitset() - Compute effective value and mask from bitset nest
* @val: unsigned long based bitmap to put value into
* @mask: unsigned long based bitmap to put mask into
* @nbits: size of @val and @mask bitmaps
* @attr: nest attribute to parse and apply
* @names: array of bit names; may be null for compact format
* @extack: extack for error reporting
*
* Provide @nbits size long bitmaps for value and mask so that
* x = (val & mask) | (x & ~mask) would modify any @nbits sized bitmap x
* the same way ethnl_update_bitset() with the same bitset attribute would.
*
* Return: negative error code on failure, 0 on success
*/
int ethnl_parse_bitset(unsigned long *val, unsigned long *mask,
unsigned int nbits, const struct nlattr *attr,
ethnl_string_array_t names,
struct netlink_ext_ack *extack)
{
struct nlattr *tb[ARRAY_SIZE(bitset_policy)];
const struct nlattr *bit_attr;
bool no_mask;
int rem;
int ret;
if (!attr)
return 0;
ret = nla_parse_nested(tb, ARRAY_SIZE(bitset_policy) - 1, attr,
bitset_policy, extack);
if (ret < 0)
return ret;
no_mask = tb[ETHTOOL_A_BITSET_NOMASK];
if (!tb[ETHTOOL_A_BITSET_BITS]) {
unsigned int change_bits;
ret = ethnl_compact_sanity_checks(nbits, attr, tb, extack);
if (ret < 0)
return ret;
change_bits = nla_get_u32(tb[ETHTOOL_A_BITSET_SIZE]);
if (change_bits > nbits)
change_bits = nbits;
bitmap_from_arr32(val, nla_data(tb[ETHTOOL_A_BITSET_VALUE]),
change_bits);
if (change_bits < nbits)
bitmap_clear(val, change_bits, nbits - change_bits);
if (no_mask) {
bitmap_fill(mask, nbits);
} else {
bitmap_from_arr32(mask,
nla_data(tb[ETHTOOL_A_BITSET_MASK]),
change_bits);
if (change_bits < nbits)
bitmap_clear(mask, change_bits,
nbits - change_bits);
}
return 0;
}
if (tb[ETHTOOL_A_BITSET_VALUE]) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_BITSET_VALUE],
"value only allowed in compact bitset");
return -EINVAL;
}
if (tb[ETHTOOL_A_BITSET_MASK]) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_BITSET_MASK],
"mask only allowed in compact bitset");
return -EINVAL;
}
bitmap_zero(val, nbits);
if (no_mask)
bitmap_fill(mask, nbits);
else
bitmap_zero(mask, nbits);
nla_for_each_nested(bit_attr, tb[ETHTOOL_A_BITSET_BITS], rem) {
unsigned int idx;
bool bit_val;
ret = ethnl_parse_bit(&idx, &bit_val, nbits, bit_attr, no_mask,
names, extack);
if (ret < 0)
return ret;
if (bit_val)
__set_bit(idx, val);
if (!no_mask)
__set_bit(idx, mask);
}
return 0;
}
#if BITS_PER_LONG == 64 && defined(__BIG_ENDIAN)
/* 64-bit big endian architectures are the only case when u32 based bitmaps
* and unsigned long based bitmaps have different memory layout so that we
* cannot simply cast the latter to the former and need actual wrappers
* converting the latter to the former.
*
* To reduce the number of slab allocations, the wrappers use fixed size local
* variables for bitmaps up to ETHNL_SMALL_BITMAP_BITS bits which is the
* majority of bitmaps used by ethtool.
*/
#define ETHNL_SMALL_BITMAP_BITS 128
#define ETHNL_SMALL_BITMAP_WORDS DIV_ROUND_UP(ETHNL_SMALL_BITMAP_BITS, 32)
int ethnl_bitset_size(const unsigned long *val, const unsigned long *mask,
unsigned int nbits, ethnl_string_array_t names,
bool compact)
{
u32 small_mask32[ETHNL_SMALL_BITMAP_WORDS];
u32 small_val32[ETHNL_SMALL_BITMAP_WORDS];
u32 *mask32;
u32 *val32;
int ret;
if (nbits > ETHNL_SMALL_BITMAP_BITS) {
unsigned int nwords = DIV_ROUND_UP(nbits, 32);
val32 = kmalloc_array(2 * nwords, sizeof(u32), GFP_KERNEL);
if (!val32)
return -ENOMEM;
mask32 = val32 + nwords;
} else {
val32 = small_val32;
mask32 = small_mask32;
}
bitmap_to_arr32(val32, val, nbits);
if (mask)
bitmap_to_arr32(mask32, mask, nbits);
else
mask32 = NULL;
ret = ethnl_bitset32_size(val32, mask32, nbits, names, compact);
if (nbits > ETHNL_SMALL_BITMAP_BITS)
kfree(val32);
return ret;
}
int ethnl_put_bitset(struct sk_buff *skb, int attrtype,
const unsigned long *val, const unsigned long *mask,
unsigned int nbits, ethnl_string_array_t names,
bool compact)
{
u32 small_mask32[ETHNL_SMALL_BITMAP_WORDS];
u32 small_val32[ETHNL_SMALL_BITMAP_WORDS];
u32 *mask32;
u32 *val32;
int ret;
if (nbits > ETHNL_SMALL_BITMAP_BITS) {
unsigned int nwords = DIV_ROUND_UP(nbits, 32);
val32 = kmalloc_array(2 * nwords, sizeof(u32), GFP_KERNEL);
if (!val32)
return -ENOMEM;
mask32 = val32 + nwords;
} else {
val32 = small_val32;
mask32 = small_mask32;
}
bitmap_to_arr32(val32, val, nbits);
if (mask)
bitmap_to_arr32(mask32, mask, nbits);
else
mask32 = NULL;
ret = ethnl_put_bitset32(skb, attrtype, val32, mask32, nbits, names,
compact);
if (nbits > ETHNL_SMALL_BITMAP_BITS)
kfree(val32);
return ret;
}
int ethnl_update_bitset(unsigned long *bitmap, unsigned int nbits,
const struct nlattr *attr, ethnl_string_array_t names,
struct netlink_ext_ack *extack, bool *mod)
{
u32 small_bitmap32[ETHNL_SMALL_BITMAP_WORDS];
u32 *bitmap32 = small_bitmap32;
bool u32_mod = false;
int ret;
if (nbits > ETHNL_SMALL_BITMAP_BITS) {
unsigned int dst_words = DIV_ROUND_UP(nbits, 32);
bitmap32 = kmalloc_array(dst_words, sizeof(u32), GFP_KERNEL);
if (!bitmap32)
return -ENOMEM;
}
bitmap_to_arr32(bitmap32, bitmap, nbits);
ret = ethnl_update_bitset32(bitmap32, nbits, attr, names, extack,
&u32_mod);
if (u32_mod) {
bitmap_from_arr32(bitmap, bitmap32, nbits);
*mod = true;
}
if (nbits > ETHNL_SMALL_BITMAP_BITS)
kfree(bitmap32);
return ret;
}
#else
/* On little endian 64-bit and all 32-bit architectures, an unsigned long
* based bitmap can be interpreted as u32 based one using a simple cast.
*/
int ethnl_bitset_size(const unsigned long *val, const unsigned long *mask,
unsigned int nbits, ethnl_string_array_t names,
bool compact)
{
return ethnl_bitset32_size((const u32 *)val, (const u32 *)mask, nbits,
names, compact);
}
int ethnl_put_bitset(struct sk_buff *skb, int attrtype,
const unsigned long *val, const unsigned long *mask,
unsigned int nbits, ethnl_string_array_t names,
bool compact)
{
return ethnl_put_bitset32(skb, attrtype, (const u32 *)val,
(const u32 *)mask, nbits, names, compact);
}
int ethnl_update_bitset(unsigned long *bitmap, unsigned int nbits,
const struct nlattr *attr, ethnl_string_array_t names,
struct netlink_ext_ack *extack, bool *mod)
{
return ethnl_update_bitset32((u32 *)bitmap, nbits, attr, names, extack,
mod);
}
#endif /* BITS_PER_LONG == 64 && defined(__BIG_ENDIAN) */
| linux-master | net/ethtool/bitset.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
#include "bitset.h"
struct fec_req_info {
struct ethnl_req_info base;
};
struct fec_reply_data {
struct ethnl_reply_data base;
__ETHTOOL_DECLARE_LINK_MODE_MASK(fec_link_modes);
u32 active_fec;
u8 fec_auto;
struct fec_stat_grp {
u64 stats[1 + ETHTOOL_MAX_LANES];
u8 cnt;
} corr, uncorr, corr_bits;
};
#define FEC_REPDATA(__reply_base) \
container_of(__reply_base, struct fec_reply_data, base)
#define ETHTOOL_FEC_MASK ((ETHTOOL_FEC_LLRS << 1) - 1)
const struct nla_policy ethnl_fec_get_policy[ETHTOOL_A_FEC_HEADER + 1] = {
[ETHTOOL_A_FEC_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy_stats),
};
static void
ethtool_fec_to_link_modes(u32 fec, unsigned long *link_modes, u8 *fec_auto)
{
if (fec_auto)
*fec_auto = !!(fec & ETHTOOL_FEC_AUTO);
if (fec & ETHTOOL_FEC_OFF)
__set_bit(ETHTOOL_LINK_MODE_FEC_NONE_BIT, link_modes);
if (fec & ETHTOOL_FEC_RS)
__set_bit(ETHTOOL_LINK_MODE_FEC_RS_BIT, link_modes);
if (fec & ETHTOOL_FEC_BASER)
__set_bit(ETHTOOL_LINK_MODE_FEC_BASER_BIT, link_modes);
if (fec & ETHTOOL_FEC_LLRS)
__set_bit(ETHTOOL_LINK_MODE_FEC_LLRS_BIT, link_modes);
}
static int
ethtool_link_modes_to_fecparam(struct ethtool_fecparam *fec,
unsigned long *link_modes, u8 fec_auto)
{
memset(fec, 0, sizeof(*fec));
if (fec_auto)
fec->fec |= ETHTOOL_FEC_AUTO;
if (__test_and_clear_bit(ETHTOOL_LINK_MODE_FEC_NONE_BIT, link_modes))
fec->fec |= ETHTOOL_FEC_OFF;
if (__test_and_clear_bit(ETHTOOL_LINK_MODE_FEC_RS_BIT, link_modes))
fec->fec |= ETHTOOL_FEC_RS;
if (__test_and_clear_bit(ETHTOOL_LINK_MODE_FEC_BASER_BIT, link_modes))
fec->fec |= ETHTOOL_FEC_BASER;
if (__test_and_clear_bit(ETHTOOL_LINK_MODE_FEC_LLRS_BIT, link_modes))
fec->fec |= ETHTOOL_FEC_LLRS;
if (!bitmap_empty(link_modes, __ETHTOOL_LINK_MODE_MASK_NBITS))
return -EINVAL;
return 0;
}
static void
fec_stats_recalc(struct fec_stat_grp *grp, struct ethtool_fec_stat *stats)
{
int i;
if (stats->lanes[0] == ETHTOOL_STAT_NOT_SET) {
grp->stats[0] = stats->total;
grp->cnt = stats->total != ETHTOOL_STAT_NOT_SET;
return;
}
grp->cnt = 1;
grp->stats[0] = 0;
for (i = 0; i < ETHTOOL_MAX_LANES; i++) {
if (stats->lanes[i] == ETHTOOL_STAT_NOT_SET)
break;
grp->stats[0] += stats->lanes[i];
grp->stats[grp->cnt++] = stats->lanes[i];
}
}
static int fec_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
__ETHTOOL_DECLARE_LINK_MODE_MASK(active_fec_modes) = {};
struct fec_reply_data *data = FEC_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
struct ethtool_fecparam fec = {};
int ret;
if (!dev->ethtool_ops->get_fecparam)
return -EOPNOTSUPP;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
ret = dev->ethtool_ops->get_fecparam(dev, &fec);
if (ret)
goto out_complete;
if (req_base->flags & ETHTOOL_FLAG_STATS &&
dev->ethtool_ops->get_fec_stats) {
struct ethtool_fec_stats stats;
ethtool_stats_init((u64 *)&stats, sizeof(stats) / 8);
dev->ethtool_ops->get_fec_stats(dev, &stats);
fec_stats_recalc(&data->corr, &stats.corrected_blocks);
fec_stats_recalc(&data->uncorr, &stats.uncorrectable_blocks);
fec_stats_recalc(&data->corr_bits, &stats.corrected_bits);
}
WARN_ON_ONCE(fec.reserved);
ethtool_fec_to_link_modes(fec.fec, data->fec_link_modes,
&data->fec_auto);
ethtool_fec_to_link_modes(fec.active_fec, active_fec_modes, NULL);
data->active_fec = find_first_bit(active_fec_modes,
__ETHTOOL_LINK_MODE_MASK_NBITS);
/* Don't report attr if no FEC mode set. Note that
* ethtool_fecparam_to_link_modes() ignores NONE and AUTO.
*/
if (data->active_fec == __ETHTOOL_LINK_MODE_MASK_NBITS)
data->active_fec = 0;
out_complete:
ethnl_ops_complete(dev);
return ret;
}
static int fec_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const struct fec_reply_data *data = FEC_REPDATA(reply_base);
int len = 0;
int ret;
ret = ethnl_bitset_size(data->fec_link_modes, NULL,
__ETHTOOL_LINK_MODE_MASK_NBITS,
link_mode_names, compact);
if (ret < 0)
return ret;
len += ret;
len += nla_total_size(sizeof(u8)) + /* _FEC_AUTO */
nla_total_size(sizeof(u32)); /* _FEC_ACTIVE */
if (req_base->flags & ETHTOOL_FLAG_STATS)
len += 3 * nla_total_size_64bit(sizeof(u64) *
(1 + ETHTOOL_MAX_LANES));
return len;
}
static int fec_put_stats(struct sk_buff *skb, const struct fec_reply_data *data)
{
struct nlattr *nest;
nest = nla_nest_start(skb, ETHTOOL_A_FEC_STATS);
if (!nest)
return -EMSGSIZE;
if (nla_put_64bit(skb, ETHTOOL_A_FEC_STAT_CORRECTED,
sizeof(u64) * data->corr.cnt,
data->corr.stats, ETHTOOL_A_FEC_STAT_PAD) ||
nla_put_64bit(skb, ETHTOOL_A_FEC_STAT_UNCORR,
sizeof(u64) * data->uncorr.cnt,
data->uncorr.stats, ETHTOOL_A_FEC_STAT_PAD) ||
nla_put_64bit(skb, ETHTOOL_A_FEC_STAT_CORR_BITS,
sizeof(u64) * data->corr_bits.cnt,
data->corr_bits.stats, ETHTOOL_A_FEC_STAT_PAD))
goto err_cancel;
nla_nest_end(skb, nest);
return 0;
err_cancel:
nla_nest_cancel(skb, nest);
return -EMSGSIZE;
}
static int fec_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const struct fec_reply_data *data = FEC_REPDATA(reply_base);
int ret;
ret = ethnl_put_bitset(skb, ETHTOOL_A_FEC_MODES,
data->fec_link_modes, NULL,
__ETHTOOL_LINK_MODE_MASK_NBITS,
link_mode_names, compact);
if (ret < 0)
return ret;
if (nla_put_u8(skb, ETHTOOL_A_FEC_AUTO, data->fec_auto) ||
(data->active_fec &&
nla_put_u32(skb, ETHTOOL_A_FEC_ACTIVE, data->active_fec)))
return -EMSGSIZE;
if (req_base->flags & ETHTOOL_FLAG_STATS && fec_put_stats(skb, data))
return -EMSGSIZE;
return 0;
}
/* FEC_SET */
const struct nla_policy ethnl_fec_set_policy[ETHTOOL_A_FEC_AUTO + 1] = {
[ETHTOOL_A_FEC_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_FEC_MODES] = { .type = NLA_NESTED },
[ETHTOOL_A_FEC_AUTO] = NLA_POLICY_MAX(NLA_U8, 1),
};
static int
ethnl_set_fec_validate(struct ethnl_req_info *req_info, struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
return ops->get_fecparam && ops->set_fecparam ? 1 : -EOPNOTSUPP;
}
static int
ethnl_set_fec(struct ethnl_req_info *req_info, struct genl_info *info)
{
__ETHTOOL_DECLARE_LINK_MODE_MASK(fec_link_modes) = {};
struct net_device *dev = req_info->dev;
struct nlattr **tb = info->attrs;
struct ethtool_fecparam fec = {};
bool mod = false;
u8 fec_auto;
int ret;
ret = dev->ethtool_ops->get_fecparam(dev, &fec);
if (ret < 0)
return ret;
ethtool_fec_to_link_modes(fec.fec, fec_link_modes, &fec_auto);
ret = ethnl_update_bitset(fec_link_modes,
__ETHTOOL_LINK_MODE_MASK_NBITS,
tb[ETHTOOL_A_FEC_MODES],
link_mode_names, info->extack, &mod);
if (ret < 0)
return ret;
ethnl_update_u8(&fec_auto, tb[ETHTOOL_A_FEC_AUTO], &mod);
if (!mod)
return 0;
ret = ethtool_link_modes_to_fecparam(&fec, fec_link_modes, fec_auto);
if (ret) {
NL_SET_ERR_MSG_ATTR(info->extack, tb[ETHTOOL_A_FEC_MODES],
"invalid FEC modes requested");
return ret;
}
if (!fec.fec) {
NL_SET_ERR_MSG_ATTR(info->extack, tb[ETHTOOL_A_FEC_MODES],
"no FEC modes set");
return -EINVAL;
}
ret = dev->ethtool_ops->set_fecparam(dev, &fec);
return ret < 0 ? ret : 1;
}
const struct ethnl_request_ops ethnl_fec_request_ops = {
.request_cmd = ETHTOOL_MSG_FEC_GET,
.reply_cmd = ETHTOOL_MSG_FEC_GET_REPLY,
.hdr_attr = ETHTOOL_A_FEC_HEADER,
.req_info_size = sizeof(struct fec_req_info),
.reply_data_size = sizeof(struct fec_reply_data),
.prepare_data = fec_prepare_data,
.reply_size = fec_reply_size,
.fill_reply = fec_fill_reply,
.set_validate = ethnl_set_fec_validate,
.set = ethnl_set_fec,
.set_ntf_cmd = ETHTOOL_MSG_FEC_NTF,
};
| linux-master | net/ethtool/fec.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <net/xdp_sock_drv.h>
#include "netlink.h"
#include "common.h"
struct channels_req_info {
struct ethnl_req_info base;
};
struct channels_reply_data {
struct ethnl_reply_data base;
struct ethtool_channels channels;
};
#define CHANNELS_REPDATA(__reply_base) \
container_of(__reply_base, struct channels_reply_data, base)
const struct nla_policy ethnl_channels_get_policy[] = {
[ETHTOOL_A_CHANNELS_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int channels_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct channels_reply_data *data = CHANNELS_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
if (!dev->ethtool_ops->get_channels)
return -EOPNOTSUPP;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
dev->ethtool_ops->get_channels(dev, &data->channels);
ethnl_ops_complete(dev);
return 0;
}
static int channels_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
return nla_total_size(sizeof(u32)) + /* _CHANNELS_RX_MAX */
nla_total_size(sizeof(u32)) + /* _CHANNELS_TX_MAX */
nla_total_size(sizeof(u32)) + /* _CHANNELS_OTHER_MAX */
nla_total_size(sizeof(u32)) + /* _CHANNELS_COMBINED_MAX */
nla_total_size(sizeof(u32)) + /* _CHANNELS_RX_COUNT */
nla_total_size(sizeof(u32)) + /* _CHANNELS_TX_COUNT */
nla_total_size(sizeof(u32)) + /* _CHANNELS_OTHER_COUNT */
nla_total_size(sizeof(u32)); /* _CHANNELS_COMBINED_COUNT */
}
static int channels_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct channels_reply_data *data = CHANNELS_REPDATA(reply_base);
const struct ethtool_channels *channels = &data->channels;
if ((channels->max_rx &&
(nla_put_u32(skb, ETHTOOL_A_CHANNELS_RX_MAX,
channels->max_rx) ||
nla_put_u32(skb, ETHTOOL_A_CHANNELS_RX_COUNT,
channels->rx_count))) ||
(channels->max_tx &&
(nla_put_u32(skb, ETHTOOL_A_CHANNELS_TX_MAX,
channels->max_tx) ||
nla_put_u32(skb, ETHTOOL_A_CHANNELS_TX_COUNT,
channels->tx_count))) ||
(channels->max_other &&
(nla_put_u32(skb, ETHTOOL_A_CHANNELS_OTHER_MAX,
channels->max_other) ||
nla_put_u32(skb, ETHTOOL_A_CHANNELS_OTHER_COUNT,
channels->other_count))) ||
(channels->max_combined &&
(nla_put_u32(skb, ETHTOOL_A_CHANNELS_COMBINED_MAX,
channels->max_combined) ||
nla_put_u32(skb, ETHTOOL_A_CHANNELS_COMBINED_COUNT,
channels->combined_count))))
return -EMSGSIZE;
return 0;
}
/* CHANNELS_SET */
const struct nla_policy ethnl_channels_set_policy[] = {
[ETHTOOL_A_CHANNELS_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_CHANNELS_RX_COUNT] = { .type = NLA_U32 },
[ETHTOOL_A_CHANNELS_TX_COUNT] = { .type = NLA_U32 },
[ETHTOOL_A_CHANNELS_OTHER_COUNT] = { .type = NLA_U32 },
[ETHTOOL_A_CHANNELS_COMBINED_COUNT] = { .type = NLA_U32 },
};
static int
ethnl_set_channels_validate(struct ethnl_req_info *req_info,
struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
return ops->get_channels && ops->set_channels ? 1 : -EOPNOTSUPP;
}
static int
ethnl_set_channels(struct ethnl_req_info *req_info, struct genl_info *info)
{
unsigned int from_channel, old_total, i;
bool mod = false, mod_combined = false;
struct net_device *dev = req_info->dev;
struct ethtool_channels channels = {};
struct nlattr **tb = info->attrs;
u32 err_attr, max_rxfh_in_use;
u64 max_rxnfc_in_use;
int ret;
dev->ethtool_ops->get_channels(dev, &channels);
old_total = channels.combined_count +
max(channels.rx_count, channels.tx_count);
ethnl_update_u32(&channels.rx_count, tb[ETHTOOL_A_CHANNELS_RX_COUNT],
&mod);
ethnl_update_u32(&channels.tx_count, tb[ETHTOOL_A_CHANNELS_TX_COUNT],
&mod);
ethnl_update_u32(&channels.other_count,
tb[ETHTOOL_A_CHANNELS_OTHER_COUNT], &mod);
ethnl_update_u32(&channels.combined_count,
tb[ETHTOOL_A_CHANNELS_COMBINED_COUNT], &mod_combined);
mod |= mod_combined;
if (!mod)
return 0;
/* ensure new channel counts are within limits */
if (channels.rx_count > channels.max_rx)
err_attr = ETHTOOL_A_CHANNELS_RX_COUNT;
else if (channels.tx_count > channels.max_tx)
err_attr = ETHTOOL_A_CHANNELS_TX_COUNT;
else if (channels.other_count > channels.max_other)
err_attr = ETHTOOL_A_CHANNELS_OTHER_COUNT;
else if (channels.combined_count > channels.max_combined)
err_attr = ETHTOOL_A_CHANNELS_COMBINED_COUNT;
else
err_attr = 0;
if (err_attr) {
NL_SET_ERR_MSG_ATTR(info->extack, tb[err_attr],
"requested channel count exceeds maximum");
return -EINVAL;
}
/* ensure there is at least one RX and one TX channel */
if (!channels.combined_count && !channels.rx_count)
err_attr = ETHTOOL_A_CHANNELS_RX_COUNT;
else if (!channels.combined_count && !channels.tx_count)
err_attr = ETHTOOL_A_CHANNELS_TX_COUNT;
else
err_attr = 0;
if (err_attr) {
if (mod_combined)
err_attr = ETHTOOL_A_CHANNELS_COMBINED_COUNT;
NL_SET_ERR_MSG_ATTR(info->extack, tb[err_attr],
"requested channel counts would result in no RX or TX channel being configured");
return -EINVAL;
}
/* ensure the new Rx count fits within the configured Rx flow
* indirection table/rxnfc settings
*/
if (ethtool_get_max_rxnfc_channel(dev, &max_rxnfc_in_use))
max_rxnfc_in_use = 0;
if (!netif_is_rxfh_configured(dev) ||
ethtool_get_max_rxfh_channel(dev, &max_rxfh_in_use))
max_rxfh_in_use = 0;
if (channels.combined_count + channels.rx_count <= max_rxfh_in_use) {
GENL_SET_ERR_MSG(info, "requested channel counts are too low for existing indirection table settings");
return -EINVAL;
}
if (channels.combined_count + channels.rx_count <= max_rxnfc_in_use) {
GENL_SET_ERR_MSG(info, "requested channel counts are too low for existing ntuple filter settings");
return -EINVAL;
}
/* Disabling channels, query zero-copy AF_XDP sockets */
from_channel = channels.combined_count +
min(channels.rx_count, channels.tx_count);
for (i = from_channel; i < old_total; i++)
if (xsk_get_pool_from_qid(dev, i)) {
GENL_SET_ERR_MSG(info, "requested channel counts are too low for existing zerocopy AF_XDP sockets");
return -EINVAL;
}
ret = dev->ethtool_ops->set_channels(dev, &channels);
return ret < 0 ? ret : 1;
}
const struct ethnl_request_ops ethnl_channels_request_ops = {
.request_cmd = ETHTOOL_MSG_CHANNELS_GET,
.reply_cmd = ETHTOOL_MSG_CHANNELS_GET_REPLY,
.hdr_attr = ETHTOOL_A_CHANNELS_HEADER,
.req_info_size = sizeof(struct channels_req_info),
.reply_data_size = sizeof(struct channels_reply_data),
.prepare_data = channels_prepare_data,
.reply_size = channels_reply_size,
.fill_reply = channels_fill_reply,
.set_validate = ethnl_set_channels_validate,
.set = ethnl_set_channels,
.set_ntf_cmd = ETHTOOL_MSG_CHANNELS_NTF,
};
| linux-master | net/ethtool/channels.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* net/core/ethtool.c - Ethtool ioctl handler
* Copyright (c) 2003 Matthew Wilcox <[email protected]>
*
* This file is where we call all the ethtool_ops commands to get
* the information ethtool needs.
*/
#include <linux/compat.h>
#include <linux/etherdevice.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/ethtool.h>
#include <linux/netdevice.h>
#include <linux/net_tstamp.h>
#include <linux/phy.h>
#include <linux/bitops.h>
#include <linux/uaccess.h>
#include <linux/vmalloc.h>
#include <linux/sfp.h>
#include <linux/slab.h>
#include <linux/rtnetlink.h>
#include <linux/sched/signal.h>
#include <linux/net.h>
#include <linux/pm_runtime.h>
#include <net/devlink.h>
#include <net/ipv6.h>
#include <net/xdp_sock_drv.h>
#include <net/flow_offload.h>
#include <linux/ethtool_netlink.h>
#include <generated/utsrelease.h>
#include "common.h"
/* State held across locks and calls for commands which have devlink fallback */
struct ethtool_devlink_compat {
struct devlink *devlink;
union {
struct ethtool_flash efl;
struct ethtool_drvinfo info;
};
};
static struct devlink *netdev_to_devlink_get(struct net_device *dev)
{
if (!dev->devlink_port)
return NULL;
return devlink_try_get(dev->devlink_port->devlink);
}
/*
* Some useful ethtool_ops methods that're device independent.
* If we find that all drivers want to do the same thing here,
* we can turn these into dev_() function calls.
*/
u32 ethtool_op_get_link(struct net_device *dev)
{
return netif_carrier_ok(dev) ? 1 : 0;
}
EXPORT_SYMBOL(ethtool_op_get_link);
int ethtool_op_get_ts_info(struct net_device *dev, struct ethtool_ts_info *info)
{
info->so_timestamping =
SOF_TIMESTAMPING_TX_SOFTWARE |
SOF_TIMESTAMPING_RX_SOFTWARE |
SOF_TIMESTAMPING_SOFTWARE;
info->phc_index = -1;
return 0;
}
EXPORT_SYMBOL(ethtool_op_get_ts_info);
/* Handlers for each ethtool command */
static int ethtool_get_features(struct net_device *dev, void __user *useraddr)
{
struct ethtool_gfeatures cmd = {
.cmd = ETHTOOL_GFEATURES,
.size = ETHTOOL_DEV_FEATURE_WORDS,
};
struct ethtool_get_features_block features[ETHTOOL_DEV_FEATURE_WORDS];
u32 __user *sizeaddr;
u32 copy_size;
int i;
/* in case feature bits run out again */
BUILD_BUG_ON(ETHTOOL_DEV_FEATURE_WORDS * sizeof(u32) > sizeof(netdev_features_t));
for (i = 0; i < ETHTOOL_DEV_FEATURE_WORDS; ++i) {
features[i].available = (u32)(dev->hw_features >> (32 * i));
features[i].requested = (u32)(dev->wanted_features >> (32 * i));
features[i].active = (u32)(dev->features >> (32 * i));
features[i].never_changed =
(u32)(NETIF_F_NEVER_CHANGE >> (32 * i));
}
sizeaddr = useraddr + offsetof(struct ethtool_gfeatures, size);
if (get_user(copy_size, sizeaddr))
return -EFAULT;
if (copy_size > ETHTOOL_DEV_FEATURE_WORDS)
copy_size = ETHTOOL_DEV_FEATURE_WORDS;
if (copy_to_user(useraddr, &cmd, sizeof(cmd)))
return -EFAULT;
useraddr += sizeof(cmd);
if (copy_to_user(useraddr, features,
array_size(copy_size, sizeof(*features))))
return -EFAULT;
return 0;
}
static int ethtool_set_features(struct net_device *dev, void __user *useraddr)
{
struct ethtool_sfeatures cmd;
struct ethtool_set_features_block features[ETHTOOL_DEV_FEATURE_WORDS];
netdev_features_t wanted = 0, valid = 0;
int i, ret = 0;
if (copy_from_user(&cmd, useraddr, sizeof(cmd)))
return -EFAULT;
useraddr += sizeof(cmd);
if (cmd.size != ETHTOOL_DEV_FEATURE_WORDS)
return -EINVAL;
if (copy_from_user(features, useraddr, sizeof(features)))
return -EFAULT;
for (i = 0; i < ETHTOOL_DEV_FEATURE_WORDS; ++i) {
valid |= (netdev_features_t)features[i].valid << (32 * i);
wanted |= (netdev_features_t)features[i].requested << (32 * i);
}
if (valid & ~NETIF_F_ETHTOOL_BITS)
return -EINVAL;
if (valid & ~dev->hw_features) {
valid &= dev->hw_features;
ret |= ETHTOOL_F_UNSUPPORTED;
}
dev->wanted_features &= ~valid;
dev->wanted_features |= wanted & valid;
__netdev_update_features(dev);
if ((dev->wanted_features ^ dev->features) & valid)
ret |= ETHTOOL_F_WISH;
return ret;
}
static int __ethtool_get_sset_count(struct net_device *dev, int sset)
{
const struct ethtool_phy_ops *phy_ops = ethtool_phy_ops;
const struct ethtool_ops *ops = dev->ethtool_ops;
if (sset == ETH_SS_FEATURES)
return ARRAY_SIZE(netdev_features_strings);
if (sset == ETH_SS_RSS_HASH_FUNCS)
return ARRAY_SIZE(rss_hash_func_strings);
if (sset == ETH_SS_TUNABLES)
return ARRAY_SIZE(tunable_strings);
if (sset == ETH_SS_PHY_TUNABLES)
return ARRAY_SIZE(phy_tunable_strings);
if (sset == ETH_SS_PHY_STATS && dev->phydev &&
!ops->get_ethtool_phy_stats &&
phy_ops && phy_ops->get_sset_count)
return phy_ops->get_sset_count(dev->phydev);
if (sset == ETH_SS_LINK_MODES)
return __ETHTOOL_LINK_MODE_MASK_NBITS;
if (ops->get_sset_count && ops->get_strings)
return ops->get_sset_count(dev, sset);
else
return -EOPNOTSUPP;
}
static void __ethtool_get_strings(struct net_device *dev,
u32 stringset, u8 *data)
{
const struct ethtool_phy_ops *phy_ops = ethtool_phy_ops;
const struct ethtool_ops *ops = dev->ethtool_ops;
if (stringset == ETH_SS_FEATURES)
memcpy(data, netdev_features_strings,
sizeof(netdev_features_strings));
else if (stringset == ETH_SS_RSS_HASH_FUNCS)
memcpy(data, rss_hash_func_strings,
sizeof(rss_hash_func_strings));
else if (stringset == ETH_SS_TUNABLES)
memcpy(data, tunable_strings, sizeof(tunable_strings));
else if (stringset == ETH_SS_PHY_TUNABLES)
memcpy(data, phy_tunable_strings, sizeof(phy_tunable_strings));
else if (stringset == ETH_SS_PHY_STATS && dev->phydev &&
!ops->get_ethtool_phy_stats && phy_ops &&
phy_ops->get_strings)
phy_ops->get_strings(dev->phydev, data);
else if (stringset == ETH_SS_LINK_MODES)
memcpy(data, link_mode_names,
__ETHTOOL_LINK_MODE_MASK_NBITS * ETH_GSTRING_LEN);
else
/* ops->get_strings is valid because checked earlier */
ops->get_strings(dev, stringset, data);
}
static netdev_features_t ethtool_get_feature_mask(u32 eth_cmd)
{
/* feature masks of legacy discrete ethtool ops */
switch (eth_cmd) {
case ETHTOOL_GTXCSUM:
case ETHTOOL_STXCSUM:
return NETIF_F_CSUM_MASK | NETIF_F_FCOE_CRC |
NETIF_F_SCTP_CRC;
case ETHTOOL_GRXCSUM:
case ETHTOOL_SRXCSUM:
return NETIF_F_RXCSUM;
case ETHTOOL_GSG:
case ETHTOOL_SSG:
return NETIF_F_SG | NETIF_F_FRAGLIST;
case ETHTOOL_GTSO:
case ETHTOOL_STSO:
return NETIF_F_ALL_TSO;
case ETHTOOL_GGSO:
case ETHTOOL_SGSO:
return NETIF_F_GSO;
case ETHTOOL_GGRO:
case ETHTOOL_SGRO:
return NETIF_F_GRO;
default:
BUG();
}
}
static int ethtool_get_one_feature(struct net_device *dev,
char __user *useraddr, u32 ethcmd)
{
netdev_features_t mask = ethtool_get_feature_mask(ethcmd);
struct ethtool_value edata = {
.cmd = ethcmd,
.data = !!(dev->features & mask),
};
if (copy_to_user(useraddr, &edata, sizeof(edata)))
return -EFAULT;
return 0;
}
static int ethtool_set_one_feature(struct net_device *dev,
void __user *useraddr, u32 ethcmd)
{
struct ethtool_value edata;
netdev_features_t mask;
if (copy_from_user(&edata, useraddr, sizeof(edata)))
return -EFAULT;
mask = ethtool_get_feature_mask(ethcmd);
mask &= dev->hw_features;
if (!mask)
return -EOPNOTSUPP;
if (edata.data)
dev->wanted_features |= mask;
else
dev->wanted_features &= ~mask;
__netdev_update_features(dev);
return 0;
}
#define ETH_ALL_FLAGS (ETH_FLAG_LRO | ETH_FLAG_RXVLAN | ETH_FLAG_TXVLAN | \
ETH_FLAG_NTUPLE | ETH_FLAG_RXHASH)
#define ETH_ALL_FEATURES (NETIF_F_LRO | NETIF_F_HW_VLAN_CTAG_RX | \
NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_NTUPLE | \
NETIF_F_RXHASH)
static u32 __ethtool_get_flags(struct net_device *dev)
{
u32 flags = 0;
if (dev->features & NETIF_F_LRO)
flags |= ETH_FLAG_LRO;
if (dev->features & NETIF_F_HW_VLAN_CTAG_RX)
flags |= ETH_FLAG_RXVLAN;
if (dev->features & NETIF_F_HW_VLAN_CTAG_TX)
flags |= ETH_FLAG_TXVLAN;
if (dev->features & NETIF_F_NTUPLE)
flags |= ETH_FLAG_NTUPLE;
if (dev->features & NETIF_F_RXHASH)
flags |= ETH_FLAG_RXHASH;
return flags;
}
static int __ethtool_set_flags(struct net_device *dev, u32 data)
{
netdev_features_t features = 0, changed;
if (data & ~ETH_ALL_FLAGS)
return -EINVAL;
if (data & ETH_FLAG_LRO)
features |= NETIF_F_LRO;
if (data & ETH_FLAG_RXVLAN)
features |= NETIF_F_HW_VLAN_CTAG_RX;
if (data & ETH_FLAG_TXVLAN)
features |= NETIF_F_HW_VLAN_CTAG_TX;
if (data & ETH_FLAG_NTUPLE)
features |= NETIF_F_NTUPLE;
if (data & ETH_FLAG_RXHASH)
features |= NETIF_F_RXHASH;
/* allow changing only bits set in hw_features */
changed = (features ^ dev->features) & ETH_ALL_FEATURES;
if (changed & ~dev->hw_features)
return (changed & dev->hw_features) ? -EINVAL : -EOPNOTSUPP;
dev->wanted_features =
(dev->wanted_features & ~changed) | (features & changed);
__netdev_update_features(dev);
return 0;
}
/* Given two link masks, AND them together and save the result in dst. */
void ethtool_intersect_link_masks(struct ethtool_link_ksettings *dst,
struct ethtool_link_ksettings *src)
{
unsigned int size = BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS);
unsigned int idx = 0;
for (; idx < size; idx++) {
dst->link_modes.supported[idx] &=
src->link_modes.supported[idx];
dst->link_modes.advertising[idx] &=
src->link_modes.advertising[idx];
}
}
EXPORT_SYMBOL(ethtool_intersect_link_masks);
void ethtool_convert_legacy_u32_to_link_mode(unsigned long *dst,
u32 legacy_u32)
{
linkmode_zero(dst);
dst[0] = legacy_u32;
}
EXPORT_SYMBOL(ethtool_convert_legacy_u32_to_link_mode);
/* return false if src had higher bits set. lower bits always updated. */
bool ethtool_convert_link_mode_to_legacy_u32(u32 *legacy_u32,
const unsigned long *src)
{
*legacy_u32 = src[0];
return find_next_bit(src, __ETHTOOL_LINK_MODE_MASK_NBITS, 32) ==
__ETHTOOL_LINK_MODE_MASK_NBITS;
}
EXPORT_SYMBOL(ethtool_convert_link_mode_to_legacy_u32);
/* return false if ksettings link modes had higher bits
* set. legacy_settings always updated (best effort)
*/
static bool
convert_link_ksettings_to_legacy_settings(
struct ethtool_cmd *legacy_settings,
const struct ethtool_link_ksettings *link_ksettings)
{
bool retval = true;
memset(legacy_settings, 0, sizeof(*legacy_settings));
/* this also clears the deprecated fields in legacy structure:
* __u8 transceiver;
* __u32 maxtxpkt;
* __u32 maxrxpkt;
*/
retval &= ethtool_convert_link_mode_to_legacy_u32(
&legacy_settings->supported,
link_ksettings->link_modes.supported);
retval &= ethtool_convert_link_mode_to_legacy_u32(
&legacy_settings->advertising,
link_ksettings->link_modes.advertising);
retval &= ethtool_convert_link_mode_to_legacy_u32(
&legacy_settings->lp_advertising,
link_ksettings->link_modes.lp_advertising);
ethtool_cmd_speed_set(legacy_settings, link_ksettings->base.speed);
legacy_settings->duplex
= link_ksettings->base.duplex;
legacy_settings->port
= link_ksettings->base.port;
legacy_settings->phy_address
= link_ksettings->base.phy_address;
legacy_settings->autoneg
= link_ksettings->base.autoneg;
legacy_settings->mdio_support
= link_ksettings->base.mdio_support;
legacy_settings->eth_tp_mdix
= link_ksettings->base.eth_tp_mdix;
legacy_settings->eth_tp_mdix_ctrl
= link_ksettings->base.eth_tp_mdix_ctrl;
legacy_settings->transceiver
= link_ksettings->base.transceiver;
return retval;
}
/* number of 32-bit words to store the user's link mode bitmaps */
#define __ETHTOOL_LINK_MODE_MASK_NU32 \
DIV_ROUND_UP(__ETHTOOL_LINK_MODE_MASK_NBITS, 32)
/* layout of the struct passed from/to userland */
struct ethtool_link_usettings {
struct ethtool_link_settings base;
struct {
__u32 supported[__ETHTOOL_LINK_MODE_MASK_NU32];
__u32 advertising[__ETHTOOL_LINK_MODE_MASK_NU32];
__u32 lp_advertising[__ETHTOOL_LINK_MODE_MASK_NU32];
} link_modes;
};
/* Internal kernel helper to query a device ethtool_link_settings. */
int __ethtool_get_link_ksettings(struct net_device *dev,
struct ethtool_link_ksettings *link_ksettings)
{
ASSERT_RTNL();
if (!dev->ethtool_ops->get_link_ksettings)
return -EOPNOTSUPP;
memset(link_ksettings, 0, sizeof(*link_ksettings));
return dev->ethtool_ops->get_link_ksettings(dev, link_ksettings);
}
EXPORT_SYMBOL(__ethtool_get_link_ksettings);
/* convert ethtool_link_usettings in user space to a kernel internal
* ethtool_link_ksettings. return 0 on success, errno on error.
*/
static int load_link_ksettings_from_user(struct ethtool_link_ksettings *to,
const void __user *from)
{
struct ethtool_link_usettings link_usettings;
if (copy_from_user(&link_usettings, from, sizeof(link_usettings)))
return -EFAULT;
memcpy(&to->base, &link_usettings.base, sizeof(to->base));
bitmap_from_arr32(to->link_modes.supported,
link_usettings.link_modes.supported,
__ETHTOOL_LINK_MODE_MASK_NBITS);
bitmap_from_arr32(to->link_modes.advertising,
link_usettings.link_modes.advertising,
__ETHTOOL_LINK_MODE_MASK_NBITS);
bitmap_from_arr32(to->link_modes.lp_advertising,
link_usettings.link_modes.lp_advertising,
__ETHTOOL_LINK_MODE_MASK_NBITS);
return 0;
}
/* Check if the user is trying to change anything besides speed/duplex */
bool ethtool_virtdev_validate_cmd(const struct ethtool_link_ksettings *cmd)
{
struct ethtool_link_settings base2 = {};
base2.speed = cmd->base.speed;
base2.port = PORT_OTHER;
base2.duplex = cmd->base.duplex;
base2.cmd = cmd->base.cmd;
base2.link_mode_masks_nwords = cmd->base.link_mode_masks_nwords;
return !memcmp(&base2, &cmd->base, sizeof(base2)) &&
bitmap_empty(cmd->link_modes.supported,
__ETHTOOL_LINK_MODE_MASK_NBITS) &&
bitmap_empty(cmd->link_modes.lp_advertising,
__ETHTOOL_LINK_MODE_MASK_NBITS);
}
/* convert a kernel internal ethtool_link_ksettings to
* ethtool_link_usettings in user space. return 0 on success, errno on
* error.
*/
static int
store_link_ksettings_for_user(void __user *to,
const struct ethtool_link_ksettings *from)
{
struct ethtool_link_usettings link_usettings;
memcpy(&link_usettings, from, sizeof(link_usettings));
bitmap_to_arr32(link_usettings.link_modes.supported,
from->link_modes.supported,
__ETHTOOL_LINK_MODE_MASK_NBITS);
bitmap_to_arr32(link_usettings.link_modes.advertising,
from->link_modes.advertising,
__ETHTOOL_LINK_MODE_MASK_NBITS);
bitmap_to_arr32(link_usettings.link_modes.lp_advertising,
from->link_modes.lp_advertising,
__ETHTOOL_LINK_MODE_MASK_NBITS);
if (copy_to_user(to, &link_usettings, sizeof(link_usettings)))
return -EFAULT;
return 0;
}
/* Query device for its ethtool_link_settings. */
static int ethtool_get_link_ksettings(struct net_device *dev,
void __user *useraddr)
{
int err = 0;
struct ethtool_link_ksettings link_ksettings;
ASSERT_RTNL();
if (!dev->ethtool_ops->get_link_ksettings)
return -EOPNOTSUPP;
/* handle bitmap nbits handshake */
if (copy_from_user(&link_ksettings.base, useraddr,
sizeof(link_ksettings.base)))
return -EFAULT;
if (__ETHTOOL_LINK_MODE_MASK_NU32
!= link_ksettings.base.link_mode_masks_nwords) {
/* wrong link mode nbits requested */
memset(&link_ksettings, 0, sizeof(link_ksettings));
link_ksettings.base.cmd = ETHTOOL_GLINKSETTINGS;
/* send back number of words required as negative val */
compiletime_assert(__ETHTOOL_LINK_MODE_MASK_NU32 <= S8_MAX,
"need too many bits for link modes!");
link_ksettings.base.link_mode_masks_nwords
= -((s8)__ETHTOOL_LINK_MODE_MASK_NU32);
/* copy the base fields back to user, not the link
* mode bitmaps
*/
if (copy_to_user(useraddr, &link_ksettings.base,
sizeof(link_ksettings.base)))
return -EFAULT;
return 0;
}
/* handshake successful: user/kernel agree on
* link_mode_masks_nwords
*/
memset(&link_ksettings, 0, sizeof(link_ksettings));
err = dev->ethtool_ops->get_link_ksettings(dev, &link_ksettings);
if (err < 0)
return err;
/* make sure we tell the right values to user */
link_ksettings.base.cmd = ETHTOOL_GLINKSETTINGS;
link_ksettings.base.link_mode_masks_nwords
= __ETHTOOL_LINK_MODE_MASK_NU32;
link_ksettings.base.master_slave_cfg = MASTER_SLAVE_CFG_UNSUPPORTED;
link_ksettings.base.master_slave_state = MASTER_SLAVE_STATE_UNSUPPORTED;
link_ksettings.base.rate_matching = RATE_MATCH_NONE;
return store_link_ksettings_for_user(useraddr, &link_ksettings);
}
/* Update device ethtool_link_settings. */
static int ethtool_set_link_ksettings(struct net_device *dev,
void __user *useraddr)
{
struct ethtool_link_ksettings link_ksettings = {};
int err;
ASSERT_RTNL();
if (!dev->ethtool_ops->set_link_ksettings)
return -EOPNOTSUPP;
/* make sure nbits field has expected value */
if (copy_from_user(&link_ksettings.base, useraddr,
sizeof(link_ksettings.base)))
return -EFAULT;
if (__ETHTOOL_LINK_MODE_MASK_NU32
!= link_ksettings.base.link_mode_masks_nwords)
return -EINVAL;
/* copy the whole structure, now that we know it has expected
* format
*/
err = load_link_ksettings_from_user(&link_ksettings, useraddr);
if (err)
return err;
/* re-check nwords field, just in case */
if (__ETHTOOL_LINK_MODE_MASK_NU32
!= link_ksettings.base.link_mode_masks_nwords)
return -EINVAL;
if (link_ksettings.base.master_slave_cfg ||
link_ksettings.base.master_slave_state)
return -EINVAL;
err = dev->ethtool_ops->set_link_ksettings(dev, &link_ksettings);
if (err >= 0) {
ethtool_notify(dev, ETHTOOL_MSG_LINKINFO_NTF, NULL);
ethtool_notify(dev, ETHTOOL_MSG_LINKMODES_NTF, NULL);
}
return err;
}
int ethtool_virtdev_set_link_ksettings(struct net_device *dev,
const struct ethtool_link_ksettings *cmd,
u32 *dev_speed, u8 *dev_duplex)
{
u32 speed;
u8 duplex;
speed = cmd->base.speed;
duplex = cmd->base.duplex;
/* don't allow custom speed and duplex */
if (!ethtool_validate_speed(speed) ||
!ethtool_validate_duplex(duplex) ||
!ethtool_virtdev_validate_cmd(cmd))
return -EINVAL;
*dev_speed = speed;
*dev_duplex = duplex;
return 0;
}
EXPORT_SYMBOL(ethtool_virtdev_set_link_ksettings);
/* Query device for its ethtool_cmd settings.
*
* Backward compatibility note: for compatibility with legacy ethtool, this is
* now implemented via get_link_ksettings. When driver reports higher link mode
* bits, a kernel warning is logged once (with name of 1st driver/device) to
* recommend user to upgrade ethtool, but the command is successful (only the
* lower link mode bits reported back to user). Deprecated fields from
* ethtool_cmd (transceiver/maxrxpkt/maxtxpkt) are always set to zero.
*/
static int ethtool_get_settings(struct net_device *dev, void __user *useraddr)
{
struct ethtool_link_ksettings link_ksettings;
struct ethtool_cmd cmd;
int err;
ASSERT_RTNL();
if (!dev->ethtool_ops->get_link_ksettings)
return -EOPNOTSUPP;
memset(&link_ksettings, 0, sizeof(link_ksettings));
err = dev->ethtool_ops->get_link_ksettings(dev, &link_ksettings);
if (err < 0)
return err;
convert_link_ksettings_to_legacy_settings(&cmd, &link_ksettings);
/* send a sensible cmd tag back to user */
cmd.cmd = ETHTOOL_GSET;
if (copy_to_user(useraddr, &cmd, sizeof(cmd)))
return -EFAULT;
return 0;
}
/* Update device link settings with given ethtool_cmd.
*
* Backward compatibility note: for compatibility with legacy ethtool, this is
* now always implemented via set_link_settings. When user's request updates
* deprecated ethtool_cmd fields (transceiver/maxrxpkt/maxtxpkt), a kernel
* warning is logged once (with name of 1st driver/device) to recommend user to
* upgrade ethtool, and the request is rejected.
*/
static int ethtool_set_settings(struct net_device *dev, void __user *useraddr)
{
struct ethtool_link_ksettings link_ksettings;
struct ethtool_cmd cmd;
int ret;
ASSERT_RTNL();
if (copy_from_user(&cmd, useraddr, sizeof(cmd)))
return -EFAULT;
if (!dev->ethtool_ops->set_link_ksettings)
return -EOPNOTSUPP;
if (!convert_legacy_settings_to_link_ksettings(&link_ksettings, &cmd))
return -EINVAL;
link_ksettings.base.link_mode_masks_nwords =
__ETHTOOL_LINK_MODE_MASK_NU32;
ret = dev->ethtool_ops->set_link_ksettings(dev, &link_ksettings);
if (ret >= 0) {
ethtool_notify(dev, ETHTOOL_MSG_LINKINFO_NTF, NULL);
ethtool_notify(dev, ETHTOOL_MSG_LINKMODES_NTF, NULL);
}
return ret;
}
static int
ethtool_get_drvinfo(struct net_device *dev, struct ethtool_devlink_compat *rsp)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct device *parent = dev->dev.parent;
rsp->info.cmd = ETHTOOL_GDRVINFO;
strscpy(rsp->info.version, UTS_RELEASE, sizeof(rsp->info.version));
if (ops->get_drvinfo) {
ops->get_drvinfo(dev, &rsp->info);
if (!rsp->info.bus_info[0] && parent)
strscpy(rsp->info.bus_info, dev_name(parent),
sizeof(rsp->info.bus_info));
if (!rsp->info.driver[0] && parent && parent->driver)
strscpy(rsp->info.driver, parent->driver->name,
sizeof(rsp->info.driver));
} else if (parent && parent->driver) {
strscpy(rsp->info.bus_info, dev_name(parent),
sizeof(rsp->info.bus_info));
strscpy(rsp->info.driver, parent->driver->name,
sizeof(rsp->info.driver));
} else if (dev->rtnl_link_ops) {
strscpy(rsp->info.driver, dev->rtnl_link_ops->kind,
sizeof(rsp->info.driver));
} else {
return -EOPNOTSUPP;
}
/*
* this method of obtaining string set info is deprecated;
* Use ETHTOOL_GSSET_INFO instead.
*/
if (ops->get_sset_count) {
int rc;
rc = ops->get_sset_count(dev, ETH_SS_TEST);
if (rc >= 0)
rsp->info.testinfo_len = rc;
rc = ops->get_sset_count(dev, ETH_SS_STATS);
if (rc >= 0)
rsp->info.n_stats = rc;
rc = ops->get_sset_count(dev, ETH_SS_PRIV_FLAGS);
if (rc >= 0)
rsp->info.n_priv_flags = rc;
}
if (ops->get_regs_len) {
int ret = ops->get_regs_len(dev);
if (ret > 0)
rsp->info.regdump_len = ret;
}
if (ops->get_eeprom_len)
rsp->info.eedump_len = ops->get_eeprom_len(dev);
if (!rsp->info.fw_version[0])
rsp->devlink = netdev_to_devlink_get(dev);
return 0;
}
static noinline_for_stack int ethtool_get_sset_info(struct net_device *dev,
void __user *useraddr)
{
struct ethtool_sset_info info;
u64 sset_mask;
int i, idx = 0, n_bits = 0, ret, rc;
u32 *info_buf = NULL;
if (copy_from_user(&info, useraddr, sizeof(info)))
return -EFAULT;
/* store copy of mask, because we zero struct later on */
sset_mask = info.sset_mask;
if (!sset_mask)
return 0;
/* calculate size of return buffer */
n_bits = hweight64(sset_mask);
memset(&info, 0, sizeof(info));
info.cmd = ETHTOOL_GSSET_INFO;
info_buf = kcalloc(n_bits, sizeof(u32), GFP_USER);
if (!info_buf)
return -ENOMEM;
/*
* fill return buffer based on input bitmask and successful
* get_sset_count return
*/
for (i = 0; i < 64; i++) {
if (!(sset_mask & (1ULL << i)))
continue;
rc = __ethtool_get_sset_count(dev, i);
if (rc >= 0) {
info.sset_mask |= (1ULL << i);
info_buf[idx++] = rc;
}
}
ret = -EFAULT;
if (copy_to_user(useraddr, &info, sizeof(info)))
goto out;
useraddr += offsetof(struct ethtool_sset_info, data);
if (copy_to_user(useraddr, info_buf, array_size(idx, sizeof(u32))))
goto out;
ret = 0;
out:
kfree(info_buf);
return ret;
}
static noinline_for_stack int
ethtool_rxnfc_copy_from_compat(struct ethtool_rxnfc *rxnfc,
const struct compat_ethtool_rxnfc __user *useraddr,
size_t size)
{
struct compat_ethtool_rxnfc crxnfc = {};
/* We expect there to be holes between fs.m_ext and
* fs.ring_cookie and at the end of fs, but nowhere else.
* On non-x86, no conversion should be needed.
*/
BUILD_BUG_ON(!IS_ENABLED(CONFIG_X86_64) &&
sizeof(struct compat_ethtool_rxnfc) !=
sizeof(struct ethtool_rxnfc));
BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.m_ext) +
sizeof(useraddr->fs.m_ext) !=
offsetof(struct ethtool_rxnfc, fs.m_ext) +
sizeof(rxnfc->fs.m_ext));
BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.location) -
offsetof(struct compat_ethtool_rxnfc, fs.ring_cookie) !=
offsetof(struct ethtool_rxnfc, fs.location) -
offsetof(struct ethtool_rxnfc, fs.ring_cookie));
if (copy_from_user(&crxnfc, useraddr, min(size, sizeof(crxnfc))))
return -EFAULT;
*rxnfc = (struct ethtool_rxnfc) {
.cmd = crxnfc.cmd,
.flow_type = crxnfc.flow_type,
.data = crxnfc.data,
.fs = {
.flow_type = crxnfc.fs.flow_type,
.h_u = crxnfc.fs.h_u,
.h_ext = crxnfc.fs.h_ext,
.m_u = crxnfc.fs.m_u,
.m_ext = crxnfc.fs.m_ext,
.ring_cookie = crxnfc.fs.ring_cookie,
.location = crxnfc.fs.location,
},
.rule_cnt = crxnfc.rule_cnt,
};
return 0;
}
static int ethtool_rxnfc_copy_from_user(struct ethtool_rxnfc *rxnfc,
const void __user *useraddr,
size_t size)
{
if (compat_need_64bit_alignment_fixup())
return ethtool_rxnfc_copy_from_compat(rxnfc, useraddr, size);
if (copy_from_user(rxnfc, useraddr, size))
return -EFAULT;
return 0;
}
static int ethtool_rxnfc_copy_to_compat(void __user *useraddr,
const struct ethtool_rxnfc *rxnfc,
size_t size, const u32 *rule_buf)
{
struct compat_ethtool_rxnfc crxnfc;
memset(&crxnfc, 0, sizeof(crxnfc));
crxnfc = (struct compat_ethtool_rxnfc) {
.cmd = rxnfc->cmd,
.flow_type = rxnfc->flow_type,
.data = rxnfc->data,
.fs = {
.flow_type = rxnfc->fs.flow_type,
.h_u = rxnfc->fs.h_u,
.h_ext = rxnfc->fs.h_ext,
.m_u = rxnfc->fs.m_u,
.m_ext = rxnfc->fs.m_ext,
.ring_cookie = rxnfc->fs.ring_cookie,
.location = rxnfc->fs.location,
},
.rule_cnt = rxnfc->rule_cnt,
};
if (copy_to_user(useraddr, &crxnfc, min(size, sizeof(crxnfc))))
return -EFAULT;
return 0;
}
static int ethtool_rxnfc_copy_struct(u32 cmd, struct ethtool_rxnfc *info,
size_t *info_size, void __user *useraddr)
{
/* struct ethtool_rxnfc was originally defined for
* ETHTOOL_{G,S}RXFH with only the cmd, flow_type and data
* members. User-space might still be using that
* definition.
*/
if (cmd == ETHTOOL_GRXFH || cmd == ETHTOOL_SRXFH)
*info_size = (offsetof(struct ethtool_rxnfc, data) +
sizeof(info->data));
if (ethtool_rxnfc_copy_from_user(info, useraddr, *info_size))
return -EFAULT;
if ((cmd == ETHTOOL_GRXFH || cmd == ETHTOOL_SRXFH) && info->flow_type & FLOW_RSS) {
*info_size = sizeof(*info);
if (ethtool_rxnfc_copy_from_user(info, useraddr, *info_size))
return -EFAULT;
/* Since malicious users may modify the original data,
* we need to check whether FLOW_RSS is still requested.
*/
if (!(info->flow_type & FLOW_RSS))
return -EINVAL;
}
if (info->cmd != cmd)
return -EINVAL;
return 0;
}
static int ethtool_rxnfc_copy_to_user(void __user *useraddr,
const struct ethtool_rxnfc *rxnfc,
size_t size, const u32 *rule_buf)
{
int ret;
if (compat_need_64bit_alignment_fixup()) {
ret = ethtool_rxnfc_copy_to_compat(useraddr, rxnfc, size,
rule_buf);
useraddr += offsetof(struct compat_ethtool_rxnfc, rule_locs);
} else {
ret = copy_to_user(useraddr, rxnfc, size);
useraddr += offsetof(struct ethtool_rxnfc, rule_locs);
}
if (ret)
return -EFAULT;
if (rule_buf) {
if (copy_to_user(useraddr, rule_buf,
rxnfc->rule_cnt * sizeof(u32)))
return -EFAULT;
}
return 0;
}
static noinline_for_stack int ethtool_set_rxnfc(struct net_device *dev,
u32 cmd, void __user *useraddr)
{
struct ethtool_rxnfc info;
size_t info_size = sizeof(info);
int rc;
if (!dev->ethtool_ops->set_rxnfc)
return -EOPNOTSUPP;
rc = ethtool_rxnfc_copy_struct(cmd, &info, &info_size, useraddr);
if (rc)
return rc;
rc = dev->ethtool_ops->set_rxnfc(dev, &info);
if (rc)
return rc;
if (cmd == ETHTOOL_SRXCLSRLINS &&
ethtool_rxnfc_copy_to_user(useraddr, &info, info_size, NULL))
return -EFAULT;
return 0;
}
static noinline_for_stack int ethtool_get_rxnfc(struct net_device *dev,
u32 cmd, void __user *useraddr)
{
struct ethtool_rxnfc info;
size_t info_size = sizeof(info);
const struct ethtool_ops *ops = dev->ethtool_ops;
int ret;
void *rule_buf = NULL;
if (!ops->get_rxnfc)
return -EOPNOTSUPP;
ret = ethtool_rxnfc_copy_struct(cmd, &info, &info_size, useraddr);
if (ret)
return ret;
if (info.cmd == ETHTOOL_GRXCLSRLALL) {
if (info.rule_cnt > 0) {
if (info.rule_cnt <= KMALLOC_MAX_SIZE / sizeof(u32))
rule_buf = kcalloc(info.rule_cnt, sizeof(u32),
GFP_USER);
if (!rule_buf)
return -ENOMEM;
}
}
ret = ops->get_rxnfc(dev, &info, rule_buf);
if (ret < 0)
goto err_out;
ret = ethtool_rxnfc_copy_to_user(useraddr, &info, info_size, rule_buf);
err_out:
kfree(rule_buf);
return ret;
}
static int ethtool_copy_validate_indir(u32 *indir, void __user *useraddr,
struct ethtool_rxnfc *rx_rings,
u32 size)
{
int i;
if (copy_from_user(indir, useraddr, array_size(size, sizeof(indir[0]))))
return -EFAULT;
/* Validate ring indices */
for (i = 0; i < size; i++)
if (indir[i] >= rx_rings->data)
return -EINVAL;
return 0;
}
u8 netdev_rss_key[NETDEV_RSS_KEY_LEN] __read_mostly;
void netdev_rss_key_fill(void *buffer, size_t len)
{
BUG_ON(len > sizeof(netdev_rss_key));
net_get_random_once(netdev_rss_key, sizeof(netdev_rss_key));
memcpy(buffer, netdev_rss_key, len);
}
EXPORT_SYMBOL(netdev_rss_key_fill);
static noinline_for_stack int ethtool_get_rxfh_indir(struct net_device *dev,
void __user *useraddr)
{
u32 user_size, dev_size;
u32 *indir;
int ret;
if (!dev->ethtool_ops->get_rxfh_indir_size ||
!dev->ethtool_ops->get_rxfh)
return -EOPNOTSUPP;
dev_size = dev->ethtool_ops->get_rxfh_indir_size(dev);
if (dev_size == 0)
return -EOPNOTSUPP;
if (copy_from_user(&user_size,
useraddr + offsetof(struct ethtool_rxfh_indir, size),
sizeof(user_size)))
return -EFAULT;
if (copy_to_user(useraddr + offsetof(struct ethtool_rxfh_indir, size),
&dev_size, sizeof(dev_size)))
return -EFAULT;
/* If the user buffer size is 0, this is just a query for the
* device table size. Otherwise, if it's smaller than the
* device table size it's an error.
*/
if (user_size < dev_size)
return user_size == 0 ? 0 : -EINVAL;
indir = kcalloc(dev_size, sizeof(indir[0]), GFP_USER);
if (!indir)
return -ENOMEM;
ret = dev->ethtool_ops->get_rxfh(dev, indir, NULL, NULL);
if (ret)
goto out;
if (copy_to_user(useraddr +
offsetof(struct ethtool_rxfh_indir, ring_index[0]),
indir, dev_size * sizeof(indir[0])))
ret = -EFAULT;
out:
kfree(indir);
return ret;
}
static noinline_for_stack int ethtool_set_rxfh_indir(struct net_device *dev,
void __user *useraddr)
{
struct ethtool_rxnfc rx_rings;
u32 user_size, dev_size, i;
u32 *indir;
const struct ethtool_ops *ops = dev->ethtool_ops;
int ret;
u32 ringidx_offset = offsetof(struct ethtool_rxfh_indir, ring_index[0]);
if (!ops->get_rxfh_indir_size || !ops->set_rxfh ||
!ops->get_rxnfc)
return -EOPNOTSUPP;
dev_size = ops->get_rxfh_indir_size(dev);
if (dev_size == 0)
return -EOPNOTSUPP;
if (copy_from_user(&user_size,
useraddr + offsetof(struct ethtool_rxfh_indir, size),
sizeof(user_size)))
return -EFAULT;
if (user_size != 0 && user_size != dev_size)
return -EINVAL;
indir = kcalloc(dev_size, sizeof(indir[0]), GFP_USER);
if (!indir)
return -ENOMEM;
rx_rings.cmd = ETHTOOL_GRXRINGS;
ret = ops->get_rxnfc(dev, &rx_rings, NULL);
if (ret)
goto out;
if (user_size == 0) {
for (i = 0; i < dev_size; i++)
indir[i] = ethtool_rxfh_indir_default(i, rx_rings.data);
} else {
ret = ethtool_copy_validate_indir(indir,
useraddr + ringidx_offset,
&rx_rings,
dev_size);
if (ret)
goto out;
}
ret = ops->set_rxfh(dev, indir, NULL, ETH_RSS_HASH_NO_CHANGE);
if (ret)
goto out;
/* indicate whether rxfh was set to default */
if (user_size == 0)
dev->priv_flags &= ~IFF_RXFH_CONFIGURED;
else
dev->priv_flags |= IFF_RXFH_CONFIGURED;
out:
kfree(indir);
return ret;
}
static noinline_for_stack int ethtool_get_rxfh(struct net_device *dev,
void __user *useraddr)
{
int ret;
const struct ethtool_ops *ops = dev->ethtool_ops;
u32 user_indir_size, user_key_size;
u32 dev_indir_size = 0, dev_key_size = 0;
struct ethtool_rxfh rxfh;
u32 total_size;
u32 indir_bytes;
u32 *indir = NULL;
u8 dev_hfunc = 0;
u8 *hkey = NULL;
u8 *rss_config;
if (!ops->get_rxfh)
return -EOPNOTSUPP;
if (ops->get_rxfh_indir_size)
dev_indir_size = ops->get_rxfh_indir_size(dev);
if (ops->get_rxfh_key_size)
dev_key_size = ops->get_rxfh_key_size(dev);
if (copy_from_user(&rxfh, useraddr, sizeof(rxfh)))
return -EFAULT;
user_indir_size = rxfh.indir_size;
user_key_size = rxfh.key_size;
/* Check that reserved fields are 0 for now */
if (rxfh.rsvd8[0] || rxfh.rsvd8[1] || rxfh.rsvd8[2] || rxfh.rsvd32)
return -EINVAL;
/* Most drivers don't handle rss_context, check it's 0 as well */
if (rxfh.rss_context && !ops->get_rxfh_context)
return -EOPNOTSUPP;
rxfh.indir_size = dev_indir_size;
rxfh.key_size = dev_key_size;
if (copy_to_user(useraddr, &rxfh, sizeof(rxfh)))
return -EFAULT;
if ((user_indir_size && (user_indir_size != dev_indir_size)) ||
(user_key_size && (user_key_size != dev_key_size)))
return -EINVAL;
indir_bytes = user_indir_size * sizeof(indir[0]);
total_size = indir_bytes + user_key_size;
rss_config = kzalloc(total_size, GFP_USER);
if (!rss_config)
return -ENOMEM;
if (user_indir_size)
indir = (u32 *)rss_config;
if (user_key_size)
hkey = rss_config + indir_bytes;
if (rxfh.rss_context)
ret = dev->ethtool_ops->get_rxfh_context(dev, indir, hkey,
&dev_hfunc,
rxfh.rss_context);
else
ret = dev->ethtool_ops->get_rxfh(dev, indir, hkey, &dev_hfunc);
if (ret)
goto out;
if (copy_to_user(useraddr + offsetof(struct ethtool_rxfh, hfunc),
&dev_hfunc, sizeof(rxfh.hfunc))) {
ret = -EFAULT;
} else if (copy_to_user(useraddr +
offsetof(struct ethtool_rxfh, rss_config[0]),
rss_config, total_size)) {
ret = -EFAULT;
}
out:
kfree(rss_config);
return ret;
}
static noinline_for_stack int ethtool_set_rxfh(struct net_device *dev,
void __user *useraddr)
{
int ret;
const struct ethtool_ops *ops = dev->ethtool_ops;
struct ethtool_rxnfc rx_rings;
struct ethtool_rxfh rxfh;
u32 dev_indir_size = 0, dev_key_size = 0, i;
u32 *indir = NULL, indir_bytes = 0;
u8 *hkey = NULL;
u8 *rss_config;
u32 rss_cfg_offset = offsetof(struct ethtool_rxfh, rss_config[0]);
bool delete = false;
if (!ops->get_rxnfc || !ops->set_rxfh)
return -EOPNOTSUPP;
if (ops->get_rxfh_indir_size)
dev_indir_size = ops->get_rxfh_indir_size(dev);
if (ops->get_rxfh_key_size)
dev_key_size = ops->get_rxfh_key_size(dev);
if (copy_from_user(&rxfh, useraddr, sizeof(rxfh)))
return -EFAULT;
/* Check that reserved fields are 0 for now */
if (rxfh.rsvd8[0] || rxfh.rsvd8[1] || rxfh.rsvd8[2] || rxfh.rsvd32)
return -EINVAL;
/* Most drivers don't handle rss_context, check it's 0 as well */
if (rxfh.rss_context && !ops->set_rxfh_context)
return -EOPNOTSUPP;
/* If either indir, hash key or function is valid, proceed further.
* Must request at least one change: indir size, hash key or function.
*/
if ((rxfh.indir_size &&
rxfh.indir_size != ETH_RXFH_INDIR_NO_CHANGE &&
rxfh.indir_size != dev_indir_size) ||
(rxfh.key_size && (rxfh.key_size != dev_key_size)) ||
(rxfh.indir_size == ETH_RXFH_INDIR_NO_CHANGE &&
rxfh.key_size == 0 && rxfh.hfunc == ETH_RSS_HASH_NO_CHANGE))
return -EINVAL;
if (rxfh.indir_size != ETH_RXFH_INDIR_NO_CHANGE)
indir_bytes = dev_indir_size * sizeof(indir[0]);
rss_config = kzalloc(indir_bytes + rxfh.key_size, GFP_USER);
if (!rss_config)
return -ENOMEM;
rx_rings.cmd = ETHTOOL_GRXRINGS;
ret = ops->get_rxnfc(dev, &rx_rings, NULL);
if (ret)
goto out;
/* rxfh.indir_size == 0 means reset the indir table to default (master
* context) or delete the context (other RSS contexts).
* rxfh.indir_size == ETH_RXFH_INDIR_NO_CHANGE means leave it unchanged.
*/
if (rxfh.indir_size &&
rxfh.indir_size != ETH_RXFH_INDIR_NO_CHANGE) {
indir = (u32 *)rss_config;
ret = ethtool_copy_validate_indir(indir,
useraddr + rss_cfg_offset,
&rx_rings,
rxfh.indir_size);
if (ret)
goto out;
} else if (rxfh.indir_size == 0) {
if (rxfh.rss_context == 0) {
indir = (u32 *)rss_config;
for (i = 0; i < dev_indir_size; i++)
indir[i] = ethtool_rxfh_indir_default(i, rx_rings.data);
} else {
delete = true;
}
}
if (rxfh.key_size) {
hkey = rss_config + indir_bytes;
if (copy_from_user(hkey,
useraddr + rss_cfg_offset + indir_bytes,
rxfh.key_size)) {
ret = -EFAULT;
goto out;
}
}
if (rxfh.rss_context)
ret = ops->set_rxfh_context(dev, indir, hkey, rxfh.hfunc,
&rxfh.rss_context, delete);
else
ret = ops->set_rxfh(dev, indir, hkey, rxfh.hfunc);
if (ret)
goto out;
if (copy_to_user(useraddr + offsetof(struct ethtool_rxfh, rss_context),
&rxfh.rss_context, sizeof(rxfh.rss_context)))
ret = -EFAULT;
if (!rxfh.rss_context) {
/* indicate whether rxfh was set to default */
if (rxfh.indir_size == 0)
dev->priv_flags &= ~IFF_RXFH_CONFIGURED;
else if (rxfh.indir_size != ETH_RXFH_INDIR_NO_CHANGE)
dev->priv_flags |= IFF_RXFH_CONFIGURED;
}
out:
kfree(rss_config);
return ret;
}
static int ethtool_get_regs(struct net_device *dev, char __user *useraddr)
{
struct ethtool_regs regs;
const struct ethtool_ops *ops = dev->ethtool_ops;
void *regbuf;
int reglen, ret;
if (!ops->get_regs || !ops->get_regs_len)
return -EOPNOTSUPP;
if (copy_from_user(®s, useraddr, sizeof(regs)))
return -EFAULT;
reglen = ops->get_regs_len(dev);
if (reglen <= 0)
return reglen;
if (regs.len > reglen)
regs.len = reglen;
regbuf = vzalloc(reglen);
if (!regbuf)
return -ENOMEM;
if (regs.len < reglen)
reglen = regs.len;
ops->get_regs(dev, ®s, regbuf);
ret = -EFAULT;
if (copy_to_user(useraddr, ®s, sizeof(regs)))
goto out;
useraddr += offsetof(struct ethtool_regs, data);
if (copy_to_user(useraddr, regbuf, reglen))
goto out;
ret = 0;
out:
vfree(regbuf);
return ret;
}
static int ethtool_reset(struct net_device *dev, char __user *useraddr)
{
struct ethtool_value reset;
int ret;
if (!dev->ethtool_ops->reset)
return -EOPNOTSUPP;
if (copy_from_user(&reset, useraddr, sizeof(reset)))
return -EFAULT;
ret = dev->ethtool_ops->reset(dev, &reset.data);
if (ret)
return ret;
if (copy_to_user(useraddr, &reset, sizeof(reset)))
return -EFAULT;
return 0;
}
static int ethtool_get_wol(struct net_device *dev, char __user *useraddr)
{
struct ethtool_wolinfo wol;
if (!dev->ethtool_ops->get_wol)
return -EOPNOTSUPP;
memset(&wol, 0, sizeof(struct ethtool_wolinfo));
wol.cmd = ETHTOOL_GWOL;
dev->ethtool_ops->get_wol(dev, &wol);
if (copy_to_user(useraddr, &wol, sizeof(wol)))
return -EFAULT;
return 0;
}
static int ethtool_set_wol(struct net_device *dev, char __user *useraddr)
{
struct ethtool_wolinfo wol, cur_wol;
int ret;
if (!dev->ethtool_ops->get_wol || !dev->ethtool_ops->set_wol)
return -EOPNOTSUPP;
memset(&cur_wol, 0, sizeof(struct ethtool_wolinfo));
cur_wol.cmd = ETHTOOL_GWOL;
dev->ethtool_ops->get_wol(dev, &cur_wol);
if (copy_from_user(&wol, useraddr, sizeof(wol)))
return -EFAULT;
if (wol.wolopts & ~cur_wol.supported)
return -EINVAL;
if (wol.wolopts == cur_wol.wolopts &&
!memcmp(wol.sopass, cur_wol.sopass, sizeof(wol.sopass)))
return 0;
ret = dev->ethtool_ops->set_wol(dev, &wol);
if (ret)
return ret;
dev->wol_enabled = !!wol.wolopts;
ethtool_notify(dev, ETHTOOL_MSG_WOL_NTF, NULL);
return 0;
}
static int ethtool_get_eee(struct net_device *dev, char __user *useraddr)
{
struct ethtool_eee edata;
int rc;
if (!dev->ethtool_ops->get_eee)
return -EOPNOTSUPP;
memset(&edata, 0, sizeof(struct ethtool_eee));
edata.cmd = ETHTOOL_GEEE;
rc = dev->ethtool_ops->get_eee(dev, &edata);
if (rc)
return rc;
if (copy_to_user(useraddr, &edata, sizeof(edata)))
return -EFAULT;
return 0;
}
static int ethtool_set_eee(struct net_device *dev, char __user *useraddr)
{
struct ethtool_eee edata;
int ret;
if (!dev->ethtool_ops->set_eee)
return -EOPNOTSUPP;
if (copy_from_user(&edata, useraddr, sizeof(edata)))
return -EFAULT;
ret = dev->ethtool_ops->set_eee(dev, &edata);
if (!ret)
ethtool_notify(dev, ETHTOOL_MSG_EEE_NTF, NULL);
return ret;
}
static int ethtool_nway_reset(struct net_device *dev)
{
if (!dev->ethtool_ops->nway_reset)
return -EOPNOTSUPP;
return dev->ethtool_ops->nway_reset(dev);
}
static int ethtool_get_link(struct net_device *dev, char __user *useraddr)
{
struct ethtool_value edata = { .cmd = ETHTOOL_GLINK };
int link = __ethtool_get_link(dev);
if (link < 0)
return link;
edata.data = link;
if (copy_to_user(useraddr, &edata, sizeof(edata)))
return -EFAULT;
return 0;
}
static int ethtool_get_any_eeprom(struct net_device *dev, void __user *useraddr,
int (*getter)(struct net_device *,
struct ethtool_eeprom *, u8 *),
u32 total_len)
{
struct ethtool_eeprom eeprom;
void __user *userbuf = useraddr + sizeof(eeprom);
u32 bytes_remaining;
u8 *data;
int ret = 0;
if (copy_from_user(&eeprom, useraddr, sizeof(eeprom)))
return -EFAULT;
/* Check for wrap and zero */
if (eeprom.offset + eeprom.len <= eeprom.offset)
return -EINVAL;
/* Check for exceeding total eeprom len */
if (eeprom.offset + eeprom.len > total_len)
return -EINVAL;
data = kzalloc(PAGE_SIZE, GFP_USER);
if (!data)
return -ENOMEM;
bytes_remaining = eeprom.len;
while (bytes_remaining > 0) {
eeprom.len = min(bytes_remaining, (u32)PAGE_SIZE);
ret = getter(dev, &eeprom, data);
if (ret)
break;
if (!eeprom.len) {
ret = -EIO;
break;
}
if (copy_to_user(userbuf, data, eeprom.len)) {
ret = -EFAULT;
break;
}
userbuf += eeprom.len;
eeprom.offset += eeprom.len;
bytes_remaining -= eeprom.len;
}
eeprom.len = userbuf - (useraddr + sizeof(eeprom));
eeprom.offset -= eeprom.len;
if (copy_to_user(useraddr, &eeprom, sizeof(eeprom)))
ret = -EFAULT;
kfree(data);
return ret;
}
static int ethtool_get_eeprom(struct net_device *dev, void __user *useraddr)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
if (!ops->get_eeprom || !ops->get_eeprom_len ||
!ops->get_eeprom_len(dev))
return -EOPNOTSUPP;
return ethtool_get_any_eeprom(dev, useraddr, ops->get_eeprom,
ops->get_eeprom_len(dev));
}
static int ethtool_set_eeprom(struct net_device *dev, void __user *useraddr)
{
struct ethtool_eeprom eeprom;
const struct ethtool_ops *ops = dev->ethtool_ops;
void __user *userbuf = useraddr + sizeof(eeprom);
u32 bytes_remaining;
u8 *data;
int ret = 0;
if (!ops->set_eeprom || !ops->get_eeprom_len ||
!ops->get_eeprom_len(dev))
return -EOPNOTSUPP;
if (copy_from_user(&eeprom, useraddr, sizeof(eeprom)))
return -EFAULT;
/* Check for wrap and zero */
if (eeprom.offset + eeprom.len <= eeprom.offset)
return -EINVAL;
/* Check for exceeding total eeprom len */
if (eeprom.offset + eeprom.len > ops->get_eeprom_len(dev))
return -EINVAL;
data = kzalloc(PAGE_SIZE, GFP_USER);
if (!data)
return -ENOMEM;
bytes_remaining = eeprom.len;
while (bytes_remaining > 0) {
eeprom.len = min(bytes_remaining, (u32)PAGE_SIZE);
if (copy_from_user(data, userbuf, eeprom.len)) {
ret = -EFAULT;
break;
}
ret = ops->set_eeprom(dev, &eeprom, data);
if (ret)
break;
userbuf += eeprom.len;
eeprom.offset += eeprom.len;
bytes_remaining -= eeprom.len;
}
kfree(data);
return ret;
}
static noinline_for_stack int ethtool_get_coalesce(struct net_device *dev,
void __user *useraddr)
{
struct ethtool_coalesce coalesce = { .cmd = ETHTOOL_GCOALESCE };
struct kernel_ethtool_coalesce kernel_coalesce = {};
int ret;
if (!dev->ethtool_ops->get_coalesce)
return -EOPNOTSUPP;
ret = dev->ethtool_ops->get_coalesce(dev, &coalesce, &kernel_coalesce,
NULL);
if (ret)
return ret;
if (copy_to_user(useraddr, &coalesce, sizeof(coalesce)))
return -EFAULT;
return 0;
}
static bool
ethtool_set_coalesce_supported(struct net_device *dev,
struct ethtool_coalesce *coalesce)
{
u32 supported_params = dev->ethtool_ops->supported_coalesce_params;
u32 nonzero_params = 0;
if (coalesce->rx_coalesce_usecs)
nonzero_params |= ETHTOOL_COALESCE_RX_USECS;
if (coalesce->rx_max_coalesced_frames)
nonzero_params |= ETHTOOL_COALESCE_RX_MAX_FRAMES;
if (coalesce->rx_coalesce_usecs_irq)
nonzero_params |= ETHTOOL_COALESCE_RX_USECS_IRQ;
if (coalesce->rx_max_coalesced_frames_irq)
nonzero_params |= ETHTOOL_COALESCE_RX_MAX_FRAMES_IRQ;
if (coalesce->tx_coalesce_usecs)
nonzero_params |= ETHTOOL_COALESCE_TX_USECS;
if (coalesce->tx_max_coalesced_frames)
nonzero_params |= ETHTOOL_COALESCE_TX_MAX_FRAMES;
if (coalesce->tx_coalesce_usecs_irq)
nonzero_params |= ETHTOOL_COALESCE_TX_USECS_IRQ;
if (coalesce->tx_max_coalesced_frames_irq)
nonzero_params |= ETHTOOL_COALESCE_TX_MAX_FRAMES_IRQ;
if (coalesce->stats_block_coalesce_usecs)
nonzero_params |= ETHTOOL_COALESCE_STATS_BLOCK_USECS;
if (coalesce->use_adaptive_rx_coalesce)
nonzero_params |= ETHTOOL_COALESCE_USE_ADAPTIVE_RX;
if (coalesce->use_adaptive_tx_coalesce)
nonzero_params |= ETHTOOL_COALESCE_USE_ADAPTIVE_TX;
if (coalesce->pkt_rate_low)
nonzero_params |= ETHTOOL_COALESCE_PKT_RATE_LOW;
if (coalesce->rx_coalesce_usecs_low)
nonzero_params |= ETHTOOL_COALESCE_RX_USECS_LOW;
if (coalesce->rx_max_coalesced_frames_low)
nonzero_params |= ETHTOOL_COALESCE_RX_MAX_FRAMES_LOW;
if (coalesce->tx_coalesce_usecs_low)
nonzero_params |= ETHTOOL_COALESCE_TX_USECS_LOW;
if (coalesce->tx_max_coalesced_frames_low)
nonzero_params |= ETHTOOL_COALESCE_TX_MAX_FRAMES_LOW;
if (coalesce->pkt_rate_high)
nonzero_params |= ETHTOOL_COALESCE_PKT_RATE_HIGH;
if (coalesce->rx_coalesce_usecs_high)
nonzero_params |= ETHTOOL_COALESCE_RX_USECS_HIGH;
if (coalesce->rx_max_coalesced_frames_high)
nonzero_params |= ETHTOOL_COALESCE_RX_MAX_FRAMES_HIGH;
if (coalesce->tx_coalesce_usecs_high)
nonzero_params |= ETHTOOL_COALESCE_TX_USECS_HIGH;
if (coalesce->tx_max_coalesced_frames_high)
nonzero_params |= ETHTOOL_COALESCE_TX_MAX_FRAMES_HIGH;
if (coalesce->rate_sample_interval)
nonzero_params |= ETHTOOL_COALESCE_RATE_SAMPLE_INTERVAL;
return (supported_params & nonzero_params) == nonzero_params;
}
static noinline_for_stack int ethtool_set_coalesce(struct net_device *dev,
void __user *useraddr)
{
struct kernel_ethtool_coalesce kernel_coalesce = {};
struct ethtool_coalesce coalesce;
int ret;
if (!dev->ethtool_ops->set_coalesce || !dev->ethtool_ops->get_coalesce)
return -EOPNOTSUPP;
ret = dev->ethtool_ops->get_coalesce(dev, &coalesce, &kernel_coalesce,
NULL);
if (ret)
return ret;
if (copy_from_user(&coalesce, useraddr, sizeof(coalesce)))
return -EFAULT;
if (!ethtool_set_coalesce_supported(dev, &coalesce))
return -EOPNOTSUPP;
ret = dev->ethtool_ops->set_coalesce(dev, &coalesce, &kernel_coalesce,
NULL);
if (!ret)
ethtool_notify(dev, ETHTOOL_MSG_COALESCE_NTF, NULL);
return ret;
}
static int ethtool_get_ringparam(struct net_device *dev, void __user *useraddr)
{
struct ethtool_ringparam ringparam = { .cmd = ETHTOOL_GRINGPARAM };
struct kernel_ethtool_ringparam kernel_ringparam = {};
if (!dev->ethtool_ops->get_ringparam)
return -EOPNOTSUPP;
dev->ethtool_ops->get_ringparam(dev, &ringparam,
&kernel_ringparam, NULL);
if (copy_to_user(useraddr, &ringparam, sizeof(ringparam)))
return -EFAULT;
return 0;
}
static int ethtool_set_ringparam(struct net_device *dev, void __user *useraddr)
{
struct ethtool_ringparam ringparam, max = { .cmd = ETHTOOL_GRINGPARAM };
struct kernel_ethtool_ringparam kernel_ringparam;
int ret;
if (!dev->ethtool_ops->set_ringparam || !dev->ethtool_ops->get_ringparam)
return -EOPNOTSUPP;
if (copy_from_user(&ringparam, useraddr, sizeof(ringparam)))
return -EFAULT;
dev->ethtool_ops->get_ringparam(dev, &max, &kernel_ringparam, NULL);
/* ensure new ring parameters are within the maximums */
if (ringparam.rx_pending > max.rx_max_pending ||
ringparam.rx_mini_pending > max.rx_mini_max_pending ||
ringparam.rx_jumbo_pending > max.rx_jumbo_max_pending ||
ringparam.tx_pending > max.tx_max_pending)
return -EINVAL;
ret = dev->ethtool_ops->set_ringparam(dev, &ringparam,
&kernel_ringparam, NULL);
if (!ret)
ethtool_notify(dev, ETHTOOL_MSG_RINGS_NTF, NULL);
return ret;
}
static noinline_for_stack int ethtool_get_channels(struct net_device *dev,
void __user *useraddr)
{
struct ethtool_channels channels = { .cmd = ETHTOOL_GCHANNELS };
if (!dev->ethtool_ops->get_channels)
return -EOPNOTSUPP;
dev->ethtool_ops->get_channels(dev, &channels);
if (copy_to_user(useraddr, &channels, sizeof(channels)))
return -EFAULT;
return 0;
}
static noinline_for_stack int ethtool_set_channels(struct net_device *dev,
void __user *useraddr)
{
struct ethtool_channels channels, curr = { .cmd = ETHTOOL_GCHANNELS };
u16 from_channel, to_channel;
u64 max_rxnfc_in_use;
u32 max_rxfh_in_use;
unsigned int i;
int ret;
if (!dev->ethtool_ops->set_channels || !dev->ethtool_ops->get_channels)
return -EOPNOTSUPP;
if (copy_from_user(&channels, useraddr, sizeof(channels)))
return -EFAULT;
dev->ethtool_ops->get_channels(dev, &curr);
if (channels.rx_count == curr.rx_count &&
channels.tx_count == curr.tx_count &&
channels.combined_count == curr.combined_count &&
channels.other_count == curr.other_count)
return 0;
/* ensure new counts are within the maximums */
if (channels.rx_count > curr.max_rx ||
channels.tx_count > curr.max_tx ||
channels.combined_count > curr.max_combined ||
channels.other_count > curr.max_other)
return -EINVAL;
/* ensure there is at least one RX and one TX channel */
if (!channels.combined_count &&
(!channels.rx_count || !channels.tx_count))
return -EINVAL;
/* ensure the new Rx count fits within the configured Rx flow
* indirection table/rxnfc settings */
if (ethtool_get_max_rxnfc_channel(dev, &max_rxnfc_in_use))
max_rxnfc_in_use = 0;
if (!netif_is_rxfh_configured(dev) ||
ethtool_get_max_rxfh_channel(dev, &max_rxfh_in_use))
max_rxfh_in_use = 0;
if (channels.combined_count + channels.rx_count <=
max_t(u64, max_rxnfc_in_use, max_rxfh_in_use))
return -EINVAL;
/* Disabling channels, query zero-copy AF_XDP sockets */
from_channel = channels.combined_count +
min(channels.rx_count, channels.tx_count);
to_channel = curr.combined_count + max(curr.rx_count, curr.tx_count);
for (i = from_channel; i < to_channel; i++)
if (xsk_get_pool_from_qid(dev, i))
return -EINVAL;
ret = dev->ethtool_ops->set_channels(dev, &channels);
if (!ret)
ethtool_notify(dev, ETHTOOL_MSG_CHANNELS_NTF, NULL);
return ret;
}
static int ethtool_get_pauseparam(struct net_device *dev, void __user *useraddr)
{
struct ethtool_pauseparam pauseparam = { .cmd = ETHTOOL_GPAUSEPARAM };
if (!dev->ethtool_ops->get_pauseparam)
return -EOPNOTSUPP;
dev->ethtool_ops->get_pauseparam(dev, &pauseparam);
if (copy_to_user(useraddr, &pauseparam, sizeof(pauseparam)))
return -EFAULT;
return 0;
}
static int ethtool_set_pauseparam(struct net_device *dev, void __user *useraddr)
{
struct ethtool_pauseparam pauseparam;
int ret;
if (!dev->ethtool_ops->set_pauseparam)
return -EOPNOTSUPP;
if (copy_from_user(&pauseparam, useraddr, sizeof(pauseparam)))
return -EFAULT;
ret = dev->ethtool_ops->set_pauseparam(dev, &pauseparam);
if (!ret)
ethtool_notify(dev, ETHTOOL_MSG_PAUSE_NTF, NULL);
return ret;
}
static int ethtool_self_test(struct net_device *dev, char __user *useraddr)
{
struct ethtool_test test;
const struct ethtool_ops *ops = dev->ethtool_ops;
u64 *data;
int ret, test_len;
if (!ops->self_test || !ops->get_sset_count)
return -EOPNOTSUPP;
test_len = ops->get_sset_count(dev, ETH_SS_TEST);
if (test_len < 0)
return test_len;
WARN_ON(test_len == 0);
if (copy_from_user(&test, useraddr, sizeof(test)))
return -EFAULT;
test.len = test_len;
data = kcalloc(test_len, sizeof(u64), GFP_USER);
if (!data)
return -ENOMEM;
netif_testing_on(dev);
ops->self_test(dev, &test, data);
netif_testing_off(dev);
ret = -EFAULT;
if (copy_to_user(useraddr, &test, sizeof(test)))
goto out;
useraddr += sizeof(test);
if (copy_to_user(useraddr, data, array_size(test.len, sizeof(u64))))
goto out;
ret = 0;
out:
kfree(data);
return ret;
}
static int ethtool_get_strings(struct net_device *dev, void __user *useraddr)
{
struct ethtool_gstrings gstrings;
u8 *data;
int ret;
if (copy_from_user(&gstrings, useraddr, sizeof(gstrings)))
return -EFAULT;
ret = __ethtool_get_sset_count(dev, gstrings.string_set);
if (ret < 0)
return ret;
if (ret > S32_MAX / ETH_GSTRING_LEN)
return -ENOMEM;
WARN_ON_ONCE(!ret);
gstrings.len = ret;
if (gstrings.len) {
data = vzalloc(array_size(gstrings.len, ETH_GSTRING_LEN));
if (!data)
return -ENOMEM;
__ethtool_get_strings(dev, gstrings.string_set, data);
} else {
data = NULL;
}
ret = -EFAULT;
if (copy_to_user(useraddr, &gstrings, sizeof(gstrings)))
goto out;
useraddr += sizeof(gstrings);
if (gstrings.len &&
copy_to_user(useraddr, data,
array_size(gstrings.len, ETH_GSTRING_LEN)))
goto out;
ret = 0;
out:
vfree(data);
return ret;
}
__printf(2, 3) void ethtool_sprintf(u8 **data, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vsnprintf(*data, ETH_GSTRING_LEN, fmt, args);
va_end(args);
*data += ETH_GSTRING_LEN;
}
EXPORT_SYMBOL(ethtool_sprintf);
static int ethtool_phys_id(struct net_device *dev, void __user *useraddr)
{
struct ethtool_value id;
static bool busy;
const struct ethtool_ops *ops = dev->ethtool_ops;
netdevice_tracker dev_tracker;
int rc;
if (!ops->set_phys_id)
return -EOPNOTSUPP;
if (busy)
return -EBUSY;
if (copy_from_user(&id, useraddr, sizeof(id)))
return -EFAULT;
rc = ops->set_phys_id(dev, ETHTOOL_ID_ACTIVE);
if (rc < 0)
return rc;
/* Drop the RTNL lock while waiting, but prevent reentry or
* removal of the device.
*/
busy = true;
netdev_hold(dev, &dev_tracker, GFP_KERNEL);
rtnl_unlock();
if (rc == 0) {
/* Driver will handle this itself */
schedule_timeout_interruptible(
id.data ? (id.data * HZ) : MAX_SCHEDULE_TIMEOUT);
} else {
/* Driver expects to be called at twice the frequency in rc */
int n = rc * 2, interval = HZ / n;
u64 count = mul_u32_u32(n, id.data);
u64 i = 0;
do {
rtnl_lock();
rc = ops->set_phys_id(dev,
(i++ & 1) ? ETHTOOL_ID_OFF : ETHTOOL_ID_ON);
rtnl_unlock();
if (rc)
break;
schedule_timeout_interruptible(interval);
} while (!signal_pending(current) && (!id.data || i < count));
}
rtnl_lock();
netdev_put(dev, &dev_tracker);
busy = false;
(void) ops->set_phys_id(dev, ETHTOOL_ID_INACTIVE);
return rc;
}
static int ethtool_get_stats(struct net_device *dev, void __user *useraddr)
{
struct ethtool_stats stats;
const struct ethtool_ops *ops = dev->ethtool_ops;
u64 *data;
int ret, n_stats;
if (!ops->get_ethtool_stats || !ops->get_sset_count)
return -EOPNOTSUPP;
n_stats = ops->get_sset_count(dev, ETH_SS_STATS);
if (n_stats < 0)
return n_stats;
if (n_stats > S32_MAX / sizeof(u64))
return -ENOMEM;
WARN_ON_ONCE(!n_stats);
if (copy_from_user(&stats, useraddr, sizeof(stats)))
return -EFAULT;
stats.n_stats = n_stats;
if (n_stats) {
data = vzalloc(array_size(n_stats, sizeof(u64)));
if (!data)
return -ENOMEM;
ops->get_ethtool_stats(dev, &stats, data);
} else {
data = NULL;
}
ret = -EFAULT;
if (copy_to_user(useraddr, &stats, sizeof(stats)))
goto out;
useraddr += sizeof(stats);
if (n_stats && copy_to_user(useraddr, data, array_size(n_stats, sizeof(u64))))
goto out;
ret = 0;
out:
vfree(data);
return ret;
}
static int ethtool_vzalloc_stats_array(int n_stats, u64 **data)
{
if (n_stats < 0)
return n_stats;
if (n_stats > S32_MAX / sizeof(u64))
return -ENOMEM;
if (WARN_ON_ONCE(!n_stats))
return -EOPNOTSUPP;
*data = vzalloc(array_size(n_stats, sizeof(u64)));
if (!*data)
return -ENOMEM;
return 0;
}
static int ethtool_get_phy_stats_phydev(struct phy_device *phydev,
struct ethtool_stats *stats,
u64 **data)
{
const struct ethtool_phy_ops *phy_ops = ethtool_phy_ops;
int n_stats, ret;
if (!phy_ops || !phy_ops->get_sset_count || !phy_ops->get_stats)
return -EOPNOTSUPP;
n_stats = phy_ops->get_sset_count(phydev);
ret = ethtool_vzalloc_stats_array(n_stats, data);
if (ret)
return ret;
stats->n_stats = n_stats;
return phy_ops->get_stats(phydev, stats, *data);
}
static int ethtool_get_phy_stats_ethtool(struct net_device *dev,
struct ethtool_stats *stats,
u64 **data)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
int n_stats, ret;
if (!ops || !ops->get_sset_count || ops->get_ethtool_phy_stats)
return -EOPNOTSUPP;
n_stats = ops->get_sset_count(dev, ETH_SS_PHY_STATS);
ret = ethtool_vzalloc_stats_array(n_stats, data);
if (ret)
return ret;
stats->n_stats = n_stats;
ops->get_ethtool_phy_stats(dev, stats, *data);
return 0;
}
static int ethtool_get_phy_stats(struct net_device *dev, void __user *useraddr)
{
struct phy_device *phydev = dev->phydev;
struct ethtool_stats stats;
u64 *data = NULL;
int ret = -EOPNOTSUPP;
if (copy_from_user(&stats, useraddr, sizeof(stats)))
return -EFAULT;
if (phydev)
ret = ethtool_get_phy_stats_phydev(phydev, &stats, &data);
if (ret == -EOPNOTSUPP)
ret = ethtool_get_phy_stats_ethtool(dev, &stats, &data);
if (ret)
goto out;
if (copy_to_user(useraddr, &stats, sizeof(stats))) {
ret = -EFAULT;
goto out;
}
useraddr += sizeof(stats);
if (copy_to_user(useraddr, data, array_size(stats.n_stats, sizeof(u64))))
ret = -EFAULT;
out:
vfree(data);
return ret;
}
static int ethtool_get_perm_addr(struct net_device *dev, void __user *useraddr)
{
struct ethtool_perm_addr epaddr;
if (copy_from_user(&epaddr, useraddr, sizeof(epaddr)))
return -EFAULT;
if (epaddr.size < dev->addr_len)
return -ETOOSMALL;
epaddr.size = dev->addr_len;
if (copy_to_user(useraddr, &epaddr, sizeof(epaddr)))
return -EFAULT;
useraddr += sizeof(epaddr);
if (copy_to_user(useraddr, dev->perm_addr, epaddr.size))
return -EFAULT;
return 0;
}
static int ethtool_get_value(struct net_device *dev, char __user *useraddr,
u32 cmd, u32 (*actor)(struct net_device *))
{
struct ethtool_value edata = { .cmd = cmd };
if (!actor)
return -EOPNOTSUPP;
edata.data = actor(dev);
if (copy_to_user(useraddr, &edata, sizeof(edata)))
return -EFAULT;
return 0;
}
static int ethtool_set_value_void(struct net_device *dev, char __user *useraddr,
void (*actor)(struct net_device *, u32))
{
struct ethtool_value edata;
if (!actor)
return -EOPNOTSUPP;
if (copy_from_user(&edata, useraddr, sizeof(edata)))
return -EFAULT;
actor(dev, edata.data);
return 0;
}
static int ethtool_set_value(struct net_device *dev, char __user *useraddr,
int (*actor)(struct net_device *, u32))
{
struct ethtool_value edata;
if (!actor)
return -EOPNOTSUPP;
if (copy_from_user(&edata, useraddr, sizeof(edata)))
return -EFAULT;
return actor(dev, edata.data);
}
static int
ethtool_flash_device(struct net_device *dev, struct ethtool_devlink_compat *req)
{
if (!dev->ethtool_ops->flash_device) {
req->devlink = netdev_to_devlink_get(dev);
return 0;
}
return dev->ethtool_ops->flash_device(dev, &req->efl);
}
static int ethtool_set_dump(struct net_device *dev,
void __user *useraddr)
{
struct ethtool_dump dump;
if (!dev->ethtool_ops->set_dump)
return -EOPNOTSUPP;
if (copy_from_user(&dump, useraddr, sizeof(dump)))
return -EFAULT;
return dev->ethtool_ops->set_dump(dev, &dump);
}
static int ethtool_get_dump_flag(struct net_device *dev,
void __user *useraddr)
{
int ret;
struct ethtool_dump dump;
const struct ethtool_ops *ops = dev->ethtool_ops;
if (!ops->get_dump_flag)
return -EOPNOTSUPP;
if (copy_from_user(&dump, useraddr, sizeof(dump)))
return -EFAULT;
ret = ops->get_dump_flag(dev, &dump);
if (ret)
return ret;
if (copy_to_user(useraddr, &dump, sizeof(dump)))
return -EFAULT;
return 0;
}
static int ethtool_get_dump_data(struct net_device *dev,
void __user *useraddr)
{
int ret;
__u32 len;
struct ethtool_dump dump, tmp;
const struct ethtool_ops *ops = dev->ethtool_ops;
void *data = NULL;
if (!ops->get_dump_data || !ops->get_dump_flag)
return -EOPNOTSUPP;
if (copy_from_user(&dump, useraddr, sizeof(dump)))
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
tmp.cmd = ETHTOOL_GET_DUMP_FLAG;
ret = ops->get_dump_flag(dev, &tmp);
if (ret)
return ret;
len = min(tmp.len, dump.len);
if (!len)
return -EFAULT;
/* Don't ever let the driver think there's more space available
* than it requested with .get_dump_flag().
*/
dump.len = len;
/* Always allocate enough space to hold the whole thing so that the
* driver does not need to check the length and bother with partial
* dumping.
*/
data = vzalloc(tmp.len);
if (!data)
return -ENOMEM;
ret = ops->get_dump_data(dev, &dump, data);
if (ret)
goto out;
/* There are two sane possibilities:
* 1. The driver's .get_dump_data() does not touch dump.len.
* 2. Or it may set dump.len to how much it really writes, which
* should be tmp.len (or len if it can do a partial dump).
* In any case respond to userspace with the actual length of data
* it's receiving.
*/
WARN_ON(dump.len != len && dump.len != tmp.len);
dump.len = len;
if (copy_to_user(useraddr, &dump, sizeof(dump))) {
ret = -EFAULT;
goto out;
}
useraddr += offsetof(struct ethtool_dump, data);
if (copy_to_user(useraddr, data, len))
ret = -EFAULT;
out:
vfree(data);
return ret;
}
static int ethtool_get_ts_info(struct net_device *dev, void __user *useraddr)
{
struct ethtool_ts_info info;
int err;
err = __ethtool_get_ts_info(dev, &info);
if (err)
return err;
if (copy_to_user(useraddr, &info, sizeof(info)))
return -EFAULT;
return 0;
}
int ethtool_get_module_info_call(struct net_device *dev,
struct ethtool_modinfo *modinfo)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct phy_device *phydev = dev->phydev;
if (dev->sfp_bus)
return sfp_get_module_info(dev->sfp_bus, modinfo);
if (phydev && phydev->drv && phydev->drv->module_info)
return phydev->drv->module_info(phydev, modinfo);
if (ops->get_module_info)
return ops->get_module_info(dev, modinfo);
return -EOPNOTSUPP;
}
static int ethtool_get_module_info(struct net_device *dev,
void __user *useraddr)
{
int ret;
struct ethtool_modinfo modinfo;
if (copy_from_user(&modinfo, useraddr, sizeof(modinfo)))
return -EFAULT;
ret = ethtool_get_module_info_call(dev, &modinfo);
if (ret)
return ret;
if (copy_to_user(useraddr, &modinfo, sizeof(modinfo)))
return -EFAULT;
return 0;
}
int ethtool_get_module_eeprom_call(struct net_device *dev,
struct ethtool_eeprom *ee, u8 *data)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct phy_device *phydev = dev->phydev;
if (dev->sfp_bus)
return sfp_get_module_eeprom(dev->sfp_bus, ee, data);
if (phydev && phydev->drv && phydev->drv->module_eeprom)
return phydev->drv->module_eeprom(phydev, ee, data);
if (ops->get_module_eeprom)
return ops->get_module_eeprom(dev, ee, data);
return -EOPNOTSUPP;
}
static int ethtool_get_module_eeprom(struct net_device *dev,
void __user *useraddr)
{
int ret;
struct ethtool_modinfo modinfo;
ret = ethtool_get_module_info_call(dev, &modinfo);
if (ret)
return ret;
return ethtool_get_any_eeprom(dev, useraddr,
ethtool_get_module_eeprom_call,
modinfo.eeprom_len);
}
static int ethtool_tunable_valid(const struct ethtool_tunable *tuna)
{
switch (tuna->id) {
case ETHTOOL_RX_COPYBREAK:
case ETHTOOL_TX_COPYBREAK:
case ETHTOOL_TX_COPYBREAK_BUF_SIZE:
if (tuna->len != sizeof(u32) ||
tuna->type_id != ETHTOOL_TUNABLE_U32)
return -EINVAL;
break;
case ETHTOOL_PFC_PREVENTION_TOUT:
if (tuna->len != sizeof(u16) ||
tuna->type_id != ETHTOOL_TUNABLE_U16)
return -EINVAL;
break;
default:
return -EINVAL;
}
return 0;
}
static int ethtool_get_tunable(struct net_device *dev, void __user *useraddr)
{
int ret;
struct ethtool_tunable tuna;
const struct ethtool_ops *ops = dev->ethtool_ops;
void *data;
if (!ops->get_tunable)
return -EOPNOTSUPP;
if (copy_from_user(&tuna, useraddr, sizeof(tuna)))
return -EFAULT;
ret = ethtool_tunable_valid(&tuna);
if (ret)
return ret;
data = kzalloc(tuna.len, GFP_USER);
if (!data)
return -ENOMEM;
ret = ops->get_tunable(dev, &tuna, data);
if (ret)
goto out;
useraddr += sizeof(tuna);
ret = -EFAULT;
if (copy_to_user(useraddr, data, tuna.len))
goto out;
ret = 0;
out:
kfree(data);
return ret;
}
static int ethtool_set_tunable(struct net_device *dev, void __user *useraddr)
{
int ret;
struct ethtool_tunable tuna;
const struct ethtool_ops *ops = dev->ethtool_ops;
void *data;
if (!ops->set_tunable)
return -EOPNOTSUPP;
if (copy_from_user(&tuna, useraddr, sizeof(tuna)))
return -EFAULT;
ret = ethtool_tunable_valid(&tuna);
if (ret)
return ret;
useraddr += sizeof(tuna);
data = memdup_user(useraddr, tuna.len);
if (IS_ERR(data))
return PTR_ERR(data);
ret = ops->set_tunable(dev, &tuna, data);
kfree(data);
return ret;
}
static noinline_for_stack int
ethtool_get_per_queue_coalesce(struct net_device *dev,
void __user *useraddr,
struct ethtool_per_queue_op *per_queue_opt)
{
u32 bit;
int ret;
DECLARE_BITMAP(queue_mask, MAX_NUM_QUEUE);
if (!dev->ethtool_ops->get_per_queue_coalesce)
return -EOPNOTSUPP;
useraddr += sizeof(*per_queue_opt);
bitmap_from_arr32(queue_mask, per_queue_opt->queue_mask,
MAX_NUM_QUEUE);
for_each_set_bit(bit, queue_mask, MAX_NUM_QUEUE) {
struct ethtool_coalesce coalesce = { .cmd = ETHTOOL_GCOALESCE };
ret = dev->ethtool_ops->get_per_queue_coalesce(dev, bit, &coalesce);
if (ret != 0)
return ret;
if (copy_to_user(useraddr, &coalesce, sizeof(coalesce)))
return -EFAULT;
useraddr += sizeof(coalesce);
}
return 0;
}
static noinline_for_stack int
ethtool_set_per_queue_coalesce(struct net_device *dev,
void __user *useraddr,
struct ethtool_per_queue_op *per_queue_opt)
{
u32 bit;
int i, ret = 0;
int n_queue;
struct ethtool_coalesce *backup = NULL, *tmp = NULL;
DECLARE_BITMAP(queue_mask, MAX_NUM_QUEUE);
if ((!dev->ethtool_ops->set_per_queue_coalesce) ||
(!dev->ethtool_ops->get_per_queue_coalesce))
return -EOPNOTSUPP;
useraddr += sizeof(*per_queue_opt);
bitmap_from_arr32(queue_mask, per_queue_opt->queue_mask, MAX_NUM_QUEUE);
n_queue = bitmap_weight(queue_mask, MAX_NUM_QUEUE);
tmp = backup = kmalloc_array(n_queue, sizeof(*backup), GFP_KERNEL);
if (!backup)
return -ENOMEM;
for_each_set_bit(bit, queue_mask, MAX_NUM_QUEUE) {
struct ethtool_coalesce coalesce;
ret = dev->ethtool_ops->get_per_queue_coalesce(dev, bit, tmp);
if (ret != 0)
goto roll_back;
tmp++;
if (copy_from_user(&coalesce, useraddr, sizeof(coalesce))) {
ret = -EFAULT;
goto roll_back;
}
if (!ethtool_set_coalesce_supported(dev, &coalesce)) {
ret = -EOPNOTSUPP;
goto roll_back;
}
ret = dev->ethtool_ops->set_per_queue_coalesce(dev, bit, &coalesce);
if (ret != 0)
goto roll_back;
useraddr += sizeof(coalesce);
}
roll_back:
if (ret != 0) {
tmp = backup;
for_each_set_bit(i, queue_mask, bit) {
dev->ethtool_ops->set_per_queue_coalesce(dev, i, tmp);
tmp++;
}
}
kfree(backup);
return ret;
}
static int noinline_for_stack ethtool_set_per_queue(struct net_device *dev,
void __user *useraddr, u32 sub_cmd)
{
struct ethtool_per_queue_op per_queue_opt;
if (copy_from_user(&per_queue_opt, useraddr, sizeof(per_queue_opt)))
return -EFAULT;
if (per_queue_opt.sub_command != sub_cmd)
return -EINVAL;
switch (per_queue_opt.sub_command) {
case ETHTOOL_GCOALESCE:
return ethtool_get_per_queue_coalesce(dev, useraddr, &per_queue_opt);
case ETHTOOL_SCOALESCE:
return ethtool_set_per_queue_coalesce(dev, useraddr, &per_queue_opt);
default:
return -EOPNOTSUPP;
}
}
static int ethtool_phy_tunable_valid(const struct ethtool_tunable *tuna)
{
switch (tuna->id) {
case ETHTOOL_PHY_DOWNSHIFT:
case ETHTOOL_PHY_FAST_LINK_DOWN:
if (tuna->len != sizeof(u8) ||
tuna->type_id != ETHTOOL_TUNABLE_U8)
return -EINVAL;
break;
case ETHTOOL_PHY_EDPD:
if (tuna->len != sizeof(u16) ||
tuna->type_id != ETHTOOL_TUNABLE_U16)
return -EINVAL;
break;
default:
return -EINVAL;
}
return 0;
}
static int get_phy_tunable(struct net_device *dev, void __user *useraddr)
{
struct phy_device *phydev = dev->phydev;
struct ethtool_tunable tuna;
bool phy_drv_tunable;
void *data;
int ret;
phy_drv_tunable = phydev && phydev->drv && phydev->drv->get_tunable;
if (!phy_drv_tunable && !dev->ethtool_ops->get_phy_tunable)
return -EOPNOTSUPP;
if (copy_from_user(&tuna, useraddr, sizeof(tuna)))
return -EFAULT;
ret = ethtool_phy_tunable_valid(&tuna);
if (ret)
return ret;
data = kzalloc(tuna.len, GFP_USER);
if (!data)
return -ENOMEM;
if (phy_drv_tunable) {
mutex_lock(&phydev->lock);
ret = phydev->drv->get_tunable(phydev, &tuna, data);
mutex_unlock(&phydev->lock);
} else {
ret = dev->ethtool_ops->get_phy_tunable(dev, &tuna, data);
}
if (ret)
goto out;
useraddr += sizeof(tuna);
ret = -EFAULT;
if (copy_to_user(useraddr, data, tuna.len))
goto out;
ret = 0;
out:
kfree(data);
return ret;
}
static int set_phy_tunable(struct net_device *dev, void __user *useraddr)
{
struct phy_device *phydev = dev->phydev;
struct ethtool_tunable tuna;
bool phy_drv_tunable;
void *data;
int ret;
phy_drv_tunable = phydev && phydev->drv && phydev->drv->get_tunable;
if (!phy_drv_tunable && !dev->ethtool_ops->set_phy_tunable)
return -EOPNOTSUPP;
if (copy_from_user(&tuna, useraddr, sizeof(tuna)))
return -EFAULT;
ret = ethtool_phy_tunable_valid(&tuna);
if (ret)
return ret;
useraddr += sizeof(tuna);
data = memdup_user(useraddr, tuna.len);
if (IS_ERR(data))
return PTR_ERR(data);
if (phy_drv_tunable) {
mutex_lock(&phydev->lock);
ret = phydev->drv->set_tunable(phydev, &tuna, data);
mutex_unlock(&phydev->lock);
} else {
ret = dev->ethtool_ops->set_phy_tunable(dev, &tuna, data);
}
kfree(data);
return ret;
}
static int ethtool_get_fecparam(struct net_device *dev, void __user *useraddr)
{
struct ethtool_fecparam fecparam = { .cmd = ETHTOOL_GFECPARAM };
int rc;
if (!dev->ethtool_ops->get_fecparam)
return -EOPNOTSUPP;
rc = dev->ethtool_ops->get_fecparam(dev, &fecparam);
if (rc)
return rc;
if (WARN_ON_ONCE(fecparam.reserved))
fecparam.reserved = 0;
if (copy_to_user(useraddr, &fecparam, sizeof(fecparam)))
return -EFAULT;
return 0;
}
static int ethtool_set_fecparam(struct net_device *dev, void __user *useraddr)
{
struct ethtool_fecparam fecparam;
if (!dev->ethtool_ops->set_fecparam)
return -EOPNOTSUPP;
if (copy_from_user(&fecparam, useraddr, sizeof(fecparam)))
return -EFAULT;
if (!fecparam.fec || fecparam.fec & ETHTOOL_FEC_NONE)
return -EINVAL;
fecparam.active_fec = 0;
fecparam.reserved = 0;
return dev->ethtool_ops->set_fecparam(dev, &fecparam);
}
/* The main entry point in this file. Called from net/core/dev_ioctl.c */
static int
__dev_ethtool(struct net *net, struct ifreq *ifr, void __user *useraddr,
u32 ethcmd, struct ethtool_devlink_compat *devlink_state)
{
struct net_device *dev;
u32 sub_cmd;
int rc;
netdev_features_t old_features;
dev = __dev_get_by_name(net, ifr->ifr_name);
if (!dev)
return -ENODEV;
if (ethcmd == ETHTOOL_PERQUEUE) {
if (copy_from_user(&sub_cmd, useraddr + sizeof(ethcmd), sizeof(sub_cmd)))
return -EFAULT;
} else {
sub_cmd = ethcmd;
}
/* Allow some commands to be done by anyone */
switch (sub_cmd) {
case ETHTOOL_GSET:
case ETHTOOL_GDRVINFO:
case ETHTOOL_GMSGLVL:
case ETHTOOL_GLINK:
case ETHTOOL_GCOALESCE:
case ETHTOOL_GRINGPARAM:
case ETHTOOL_GPAUSEPARAM:
case ETHTOOL_GRXCSUM:
case ETHTOOL_GTXCSUM:
case ETHTOOL_GSG:
case ETHTOOL_GSSET_INFO:
case ETHTOOL_GSTRINGS:
case ETHTOOL_GSTATS:
case ETHTOOL_GPHYSTATS:
case ETHTOOL_GTSO:
case ETHTOOL_GPERMADDR:
case ETHTOOL_GUFO:
case ETHTOOL_GGSO:
case ETHTOOL_GGRO:
case ETHTOOL_GFLAGS:
case ETHTOOL_GPFLAGS:
case ETHTOOL_GRXFH:
case ETHTOOL_GRXRINGS:
case ETHTOOL_GRXCLSRLCNT:
case ETHTOOL_GRXCLSRULE:
case ETHTOOL_GRXCLSRLALL:
case ETHTOOL_GRXFHINDIR:
case ETHTOOL_GRSSH:
case ETHTOOL_GFEATURES:
case ETHTOOL_GCHANNELS:
case ETHTOOL_GET_TS_INFO:
case ETHTOOL_GEEE:
case ETHTOOL_GTUNABLE:
case ETHTOOL_PHY_GTUNABLE:
case ETHTOOL_GLINKSETTINGS:
case ETHTOOL_GFECPARAM:
break;
default:
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
}
if (dev->dev.parent)
pm_runtime_get_sync(dev->dev.parent);
if (!netif_device_present(dev)) {
rc = -ENODEV;
goto out;
}
if (dev->ethtool_ops->begin) {
rc = dev->ethtool_ops->begin(dev);
if (rc < 0)
goto out;
}
old_features = dev->features;
switch (ethcmd) {
case ETHTOOL_GSET:
rc = ethtool_get_settings(dev, useraddr);
break;
case ETHTOOL_SSET:
rc = ethtool_set_settings(dev, useraddr);
break;
case ETHTOOL_GDRVINFO:
rc = ethtool_get_drvinfo(dev, devlink_state);
break;
case ETHTOOL_GREGS:
rc = ethtool_get_regs(dev, useraddr);
break;
case ETHTOOL_GWOL:
rc = ethtool_get_wol(dev, useraddr);
break;
case ETHTOOL_SWOL:
rc = ethtool_set_wol(dev, useraddr);
break;
case ETHTOOL_GMSGLVL:
rc = ethtool_get_value(dev, useraddr, ethcmd,
dev->ethtool_ops->get_msglevel);
break;
case ETHTOOL_SMSGLVL:
rc = ethtool_set_value_void(dev, useraddr,
dev->ethtool_ops->set_msglevel);
if (!rc)
ethtool_notify(dev, ETHTOOL_MSG_DEBUG_NTF, NULL);
break;
case ETHTOOL_GEEE:
rc = ethtool_get_eee(dev, useraddr);
break;
case ETHTOOL_SEEE:
rc = ethtool_set_eee(dev, useraddr);
break;
case ETHTOOL_NWAY_RST:
rc = ethtool_nway_reset(dev);
break;
case ETHTOOL_GLINK:
rc = ethtool_get_link(dev, useraddr);
break;
case ETHTOOL_GEEPROM:
rc = ethtool_get_eeprom(dev, useraddr);
break;
case ETHTOOL_SEEPROM:
rc = ethtool_set_eeprom(dev, useraddr);
break;
case ETHTOOL_GCOALESCE:
rc = ethtool_get_coalesce(dev, useraddr);
break;
case ETHTOOL_SCOALESCE:
rc = ethtool_set_coalesce(dev, useraddr);
break;
case ETHTOOL_GRINGPARAM:
rc = ethtool_get_ringparam(dev, useraddr);
break;
case ETHTOOL_SRINGPARAM:
rc = ethtool_set_ringparam(dev, useraddr);
break;
case ETHTOOL_GPAUSEPARAM:
rc = ethtool_get_pauseparam(dev, useraddr);
break;
case ETHTOOL_SPAUSEPARAM:
rc = ethtool_set_pauseparam(dev, useraddr);
break;
case ETHTOOL_TEST:
rc = ethtool_self_test(dev, useraddr);
break;
case ETHTOOL_GSTRINGS:
rc = ethtool_get_strings(dev, useraddr);
break;
case ETHTOOL_PHYS_ID:
rc = ethtool_phys_id(dev, useraddr);
break;
case ETHTOOL_GSTATS:
rc = ethtool_get_stats(dev, useraddr);
break;
case ETHTOOL_GPERMADDR:
rc = ethtool_get_perm_addr(dev, useraddr);
break;
case ETHTOOL_GFLAGS:
rc = ethtool_get_value(dev, useraddr, ethcmd,
__ethtool_get_flags);
break;
case ETHTOOL_SFLAGS:
rc = ethtool_set_value(dev, useraddr, __ethtool_set_flags);
break;
case ETHTOOL_GPFLAGS:
rc = ethtool_get_value(dev, useraddr, ethcmd,
dev->ethtool_ops->get_priv_flags);
if (!rc)
ethtool_notify(dev, ETHTOOL_MSG_PRIVFLAGS_NTF, NULL);
break;
case ETHTOOL_SPFLAGS:
rc = ethtool_set_value(dev, useraddr,
dev->ethtool_ops->set_priv_flags);
break;
case ETHTOOL_GRXFH:
case ETHTOOL_GRXRINGS:
case ETHTOOL_GRXCLSRLCNT:
case ETHTOOL_GRXCLSRULE:
case ETHTOOL_GRXCLSRLALL:
rc = ethtool_get_rxnfc(dev, ethcmd, useraddr);
break;
case ETHTOOL_SRXFH:
case ETHTOOL_SRXCLSRLDEL:
case ETHTOOL_SRXCLSRLINS:
rc = ethtool_set_rxnfc(dev, ethcmd, useraddr);
break;
case ETHTOOL_FLASHDEV:
rc = ethtool_flash_device(dev, devlink_state);
break;
case ETHTOOL_RESET:
rc = ethtool_reset(dev, useraddr);
break;
case ETHTOOL_GSSET_INFO:
rc = ethtool_get_sset_info(dev, useraddr);
break;
case ETHTOOL_GRXFHINDIR:
rc = ethtool_get_rxfh_indir(dev, useraddr);
break;
case ETHTOOL_SRXFHINDIR:
rc = ethtool_set_rxfh_indir(dev, useraddr);
break;
case ETHTOOL_GRSSH:
rc = ethtool_get_rxfh(dev, useraddr);
break;
case ETHTOOL_SRSSH:
rc = ethtool_set_rxfh(dev, useraddr);
break;
case ETHTOOL_GFEATURES:
rc = ethtool_get_features(dev, useraddr);
break;
case ETHTOOL_SFEATURES:
rc = ethtool_set_features(dev, useraddr);
break;
case ETHTOOL_GTXCSUM:
case ETHTOOL_GRXCSUM:
case ETHTOOL_GSG:
case ETHTOOL_GTSO:
case ETHTOOL_GGSO:
case ETHTOOL_GGRO:
rc = ethtool_get_one_feature(dev, useraddr, ethcmd);
break;
case ETHTOOL_STXCSUM:
case ETHTOOL_SRXCSUM:
case ETHTOOL_SSG:
case ETHTOOL_STSO:
case ETHTOOL_SGSO:
case ETHTOOL_SGRO:
rc = ethtool_set_one_feature(dev, useraddr, ethcmd);
break;
case ETHTOOL_GCHANNELS:
rc = ethtool_get_channels(dev, useraddr);
break;
case ETHTOOL_SCHANNELS:
rc = ethtool_set_channels(dev, useraddr);
break;
case ETHTOOL_SET_DUMP:
rc = ethtool_set_dump(dev, useraddr);
break;
case ETHTOOL_GET_DUMP_FLAG:
rc = ethtool_get_dump_flag(dev, useraddr);
break;
case ETHTOOL_GET_DUMP_DATA:
rc = ethtool_get_dump_data(dev, useraddr);
break;
case ETHTOOL_GET_TS_INFO:
rc = ethtool_get_ts_info(dev, useraddr);
break;
case ETHTOOL_GMODULEINFO:
rc = ethtool_get_module_info(dev, useraddr);
break;
case ETHTOOL_GMODULEEEPROM:
rc = ethtool_get_module_eeprom(dev, useraddr);
break;
case ETHTOOL_GTUNABLE:
rc = ethtool_get_tunable(dev, useraddr);
break;
case ETHTOOL_STUNABLE:
rc = ethtool_set_tunable(dev, useraddr);
break;
case ETHTOOL_GPHYSTATS:
rc = ethtool_get_phy_stats(dev, useraddr);
break;
case ETHTOOL_PERQUEUE:
rc = ethtool_set_per_queue(dev, useraddr, sub_cmd);
break;
case ETHTOOL_GLINKSETTINGS:
rc = ethtool_get_link_ksettings(dev, useraddr);
break;
case ETHTOOL_SLINKSETTINGS:
rc = ethtool_set_link_ksettings(dev, useraddr);
break;
case ETHTOOL_PHY_GTUNABLE:
rc = get_phy_tunable(dev, useraddr);
break;
case ETHTOOL_PHY_STUNABLE:
rc = set_phy_tunable(dev, useraddr);
break;
case ETHTOOL_GFECPARAM:
rc = ethtool_get_fecparam(dev, useraddr);
break;
case ETHTOOL_SFECPARAM:
rc = ethtool_set_fecparam(dev, useraddr);
break;
default:
rc = -EOPNOTSUPP;
}
if (dev->ethtool_ops->complete)
dev->ethtool_ops->complete(dev);
if (old_features != dev->features)
netdev_features_change(dev);
out:
if (dev->dev.parent)
pm_runtime_put(dev->dev.parent);
return rc;
}
int dev_ethtool(struct net *net, struct ifreq *ifr, void __user *useraddr)
{
struct ethtool_devlink_compat *state;
u32 ethcmd;
int rc;
if (copy_from_user(ðcmd, useraddr, sizeof(ethcmd)))
return -EFAULT;
state = kzalloc(sizeof(*state), GFP_KERNEL);
if (!state)
return -ENOMEM;
switch (ethcmd) {
case ETHTOOL_FLASHDEV:
if (copy_from_user(&state->efl, useraddr, sizeof(state->efl))) {
rc = -EFAULT;
goto exit_free;
}
state->efl.data[ETHTOOL_FLASH_MAX_FILENAME - 1] = 0;
break;
}
rtnl_lock();
rc = __dev_ethtool(net, ifr, useraddr, ethcmd, state);
rtnl_unlock();
if (rc)
goto exit_free;
switch (ethcmd) {
case ETHTOOL_FLASHDEV:
if (state->devlink)
rc = devlink_compat_flash_update(state->devlink,
state->efl.data);
break;
case ETHTOOL_GDRVINFO:
if (state->devlink)
devlink_compat_running_version(state->devlink,
state->info.fw_version,
sizeof(state->info.fw_version));
if (copy_to_user(useraddr, &state->info, sizeof(state->info))) {
rc = -EFAULT;
goto exit_free;
}
break;
}
exit_free:
if (state->devlink)
devlink_put(state->devlink);
kfree(state);
return rc;
}
struct ethtool_rx_flow_key {
struct flow_dissector_key_basic basic;
union {
struct flow_dissector_key_ipv4_addrs ipv4;
struct flow_dissector_key_ipv6_addrs ipv6;
};
struct flow_dissector_key_ports tp;
struct flow_dissector_key_ip ip;
struct flow_dissector_key_vlan vlan;
struct flow_dissector_key_eth_addrs eth_addrs;
} __aligned(BITS_PER_LONG / 8); /* Ensure that we can do comparisons as longs. */
struct ethtool_rx_flow_match {
struct flow_dissector dissector;
struct ethtool_rx_flow_key key;
struct ethtool_rx_flow_key mask;
};
struct ethtool_rx_flow_rule *
ethtool_rx_flow_rule_create(const struct ethtool_rx_flow_spec_input *input)
{
const struct ethtool_rx_flow_spec *fs = input->fs;
struct ethtool_rx_flow_match *match;
struct ethtool_rx_flow_rule *flow;
struct flow_action_entry *act;
flow = kzalloc(sizeof(struct ethtool_rx_flow_rule) +
sizeof(struct ethtool_rx_flow_match), GFP_KERNEL);
if (!flow)
return ERR_PTR(-ENOMEM);
/* ethtool_rx supports only one single action per rule. */
flow->rule = flow_rule_alloc(1);
if (!flow->rule) {
kfree(flow);
return ERR_PTR(-ENOMEM);
}
match = (struct ethtool_rx_flow_match *)flow->priv;
flow->rule->match.dissector = &match->dissector;
flow->rule->match.mask = &match->mask;
flow->rule->match.key = &match->key;
match->mask.basic.n_proto = htons(0xffff);
switch (fs->flow_type & ~(FLOW_EXT | FLOW_MAC_EXT | FLOW_RSS)) {
case ETHER_FLOW: {
const struct ethhdr *ether_spec, *ether_m_spec;
ether_spec = &fs->h_u.ether_spec;
ether_m_spec = &fs->m_u.ether_spec;
if (!is_zero_ether_addr(ether_m_spec->h_source)) {
ether_addr_copy(match->key.eth_addrs.src,
ether_spec->h_source);
ether_addr_copy(match->mask.eth_addrs.src,
ether_m_spec->h_source);
}
if (!is_zero_ether_addr(ether_m_spec->h_dest)) {
ether_addr_copy(match->key.eth_addrs.dst,
ether_spec->h_dest);
ether_addr_copy(match->mask.eth_addrs.dst,
ether_m_spec->h_dest);
}
if (ether_m_spec->h_proto) {
match->key.basic.n_proto = ether_spec->h_proto;
match->mask.basic.n_proto = ether_m_spec->h_proto;
}
}
break;
case TCP_V4_FLOW:
case UDP_V4_FLOW: {
const struct ethtool_tcpip4_spec *v4_spec, *v4_m_spec;
match->key.basic.n_proto = htons(ETH_P_IP);
v4_spec = &fs->h_u.tcp_ip4_spec;
v4_m_spec = &fs->m_u.tcp_ip4_spec;
if (v4_m_spec->ip4src) {
match->key.ipv4.src = v4_spec->ip4src;
match->mask.ipv4.src = v4_m_spec->ip4src;
}
if (v4_m_spec->ip4dst) {
match->key.ipv4.dst = v4_spec->ip4dst;
match->mask.ipv4.dst = v4_m_spec->ip4dst;
}
if (v4_m_spec->ip4src ||
v4_m_spec->ip4dst) {
match->dissector.used_keys |=
BIT_ULL(FLOW_DISSECTOR_KEY_IPV4_ADDRS);
match->dissector.offset[FLOW_DISSECTOR_KEY_IPV4_ADDRS] =
offsetof(struct ethtool_rx_flow_key, ipv4);
}
if (v4_m_spec->psrc) {
match->key.tp.src = v4_spec->psrc;
match->mask.tp.src = v4_m_spec->psrc;
}
if (v4_m_spec->pdst) {
match->key.tp.dst = v4_spec->pdst;
match->mask.tp.dst = v4_m_spec->pdst;
}
if (v4_m_spec->psrc ||
v4_m_spec->pdst) {
match->dissector.used_keys |=
BIT_ULL(FLOW_DISSECTOR_KEY_PORTS);
match->dissector.offset[FLOW_DISSECTOR_KEY_PORTS] =
offsetof(struct ethtool_rx_flow_key, tp);
}
if (v4_m_spec->tos) {
match->key.ip.tos = v4_spec->tos;
match->mask.ip.tos = v4_m_spec->tos;
match->dissector.used_keys |=
BIT(FLOW_DISSECTOR_KEY_IP);
match->dissector.offset[FLOW_DISSECTOR_KEY_IP] =
offsetof(struct ethtool_rx_flow_key, ip);
}
}
break;
case TCP_V6_FLOW:
case UDP_V6_FLOW: {
const struct ethtool_tcpip6_spec *v6_spec, *v6_m_spec;
match->key.basic.n_proto = htons(ETH_P_IPV6);
v6_spec = &fs->h_u.tcp_ip6_spec;
v6_m_spec = &fs->m_u.tcp_ip6_spec;
if (!ipv6_addr_any((struct in6_addr *)v6_m_spec->ip6src)) {
memcpy(&match->key.ipv6.src, v6_spec->ip6src,
sizeof(match->key.ipv6.src));
memcpy(&match->mask.ipv6.src, v6_m_spec->ip6src,
sizeof(match->mask.ipv6.src));
}
if (!ipv6_addr_any((struct in6_addr *)v6_m_spec->ip6dst)) {
memcpy(&match->key.ipv6.dst, v6_spec->ip6dst,
sizeof(match->key.ipv6.dst));
memcpy(&match->mask.ipv6.dst, v6_m_spec->ip6dst,
sizeof(match->mask.ipv6.dst));
}
if (!ipv6_addr_any((struct in6_addr *)v6_m_spec->ip6src) ||
!ipv6_addr_any((struct in6_addr *)v6_m_spec->ip6dst)) {
match->dissector.used_keys |=
BIT_ULL(FLOW_DISSECTOR_KEY_IPV6_ADDRS);
match->dissector.offset[FLOW_DISSECTOR_KEY_IPV6_ADDRS] =
offsetof(struct ethtool_rx_flow_key, ipv6);
}
if (v6_m_spec->psrc) {
match->key.tp.src = v6_spec->psrc;
match->mask.tp.src = v6_m_spec->psrc;
}
if (v6_m_spec->pdst) {
match->key.tp.dst = v6_spec->pdst;
match->mask.tp.dst = v6_m_spec->pdst;
}
if (v6_m_spec->psrc ||
v6_m_spec->pdst) {
match->dissector.used_keys |=
BIT_ULL(FLOW_DISSECTOR_KEY_PORTS);
match->dissector.offset[FLOW_DISSECTOR_KEY_PORTS] =
offsetof(struct ethtool_rx_flow_key, tp);
}
if (v6_m_spec->tclass) {
match->key.ip.tos = v6_spec->tclass;
match->mask.ip.tos = v6_m_spec->tclass;
match->dissector.used_keys |=
BIT_ULL(FLOW_DISSECTOR_KEY_IP);
match->dissector.offset[FLOW_DISSECTOR_KEY_IP] =
offsetof(struct ethtool_rx_flow_key, ip);
}
}
break;
default:
ethtool_rx_flow_rule_destroy(flow);
return ERR_PTR(-EINVAL);
}
switch (fs->flow_type & ~(FLOW_EXT | FLOW_MAC_EXT | FLOW_RSS)) {
case TCP_V4_FLOW:
case TCP_V6_FLOW:
match->key.basic.ip_proto = IPPROTO_TCP;
match->mask.basic.ip_proto = 0xff;
break;
case UDP_V4_FLOW:
case UDP_V6_FLOW:
match->key.basic.ip_proto = IPPROTO_UDP;
match->mask.basic.ip_proto = 0xff;
break;
}
match->dissector.used_keys |= BIT_ULL(FLOW_DISSECTOR_KEY_BASIC);
match->dissector.offset[FLOW_DISSECTOR_KEY_BASIC] =
offsetof(struct ethtool_rx_flow_key, basic);
if (fs->flow_type & FLOW_EXT) {
const struct ethtool_flow_ext *ext_h_spec = &fs->h_ext;
const struct ethtool_flow_ext *ext_m_spec = &fs->m_ext;
if (ext_m_spec->vlan_etype) {
match->key.vlan.vlan_tpid = ext_h_spec->vlan_etype;
match->mask.vlan.vlan_tpid = ext_m_spec->vlan_etype;
}
if (ext_m_spec->vlan_tci) {
match->key.vlan.vlan_id =
ntohs(ext_h_spec->vlan_tci) & 0x0fff;
match->mask.vlan.vlan_id =
ntohs(ext_m_spec->vlan_tci) & 0x0fff;
match->key.vlan.vlan_dei =
!!(ext_h_spec->vlan_tci & htons(0x1000));
match->mask.vlan.vlan_dei =
!!(ext_m_spec->vlan_tci & htons(0x1000));
match->key.vlan.vlan_priority =
(ntohs(ext_h_spec->vlan_tci) & 0xe000) >> 13;
match->mask.vlan.vlan_priority =
(ntohs(ext_m_spec->vlan_tci) & 0xe000) >> 13;
}
if (ext_m_spec->vlan_etype ||
ext_m_spec->vlan_tci) {
match->dissector.used_keys |=
BIT_ULL(FLOW_DISSECTOR_KEY_VLAN);
match->dissector.offset[FLOW_DISSECTOR_KEY_VLAN] =
offsetof(struct ethtool_rx_flow_key, vlan);
}
}
if (fs->flow_type & FLOW_MAC_EXT) {
const struct ethtool_flow_ext *ext_h_spec = &fs->h_ext;
const struct ethtool_flow_ext *ext_m_spec = &fs->m_ext;
memcpy(match->key.eth_addrs.dst, ext_h_spec->h_dest,
ETH_ALEN);
memcpy(match->mask.eth_addrs.dst, ext_m_spec->h_dest,
ETH_ALEN);
match->dissector.used_keys |=
BIT_ULL(FLOW_DISSECTOR_KEY_ETH_ADDRS);
match->dissector.offset[FLOW_DISSECTOR_KEY_ETH_ADDRS] =
offsetof(struct ethtool_rx_flow_key, eth_addrs);
}
act = &flow->rule->action.entries[0];
switch (fs->ring_cookie) {
case RX_CLS_FLOW_DISC:
act->id = FLOW_ACTION_DROP;
break;
case RX_CLS_FLOW_WAKE:
act->id = FLOW_ACTION_WAKE;
break;
default:
act->id = FLOW_ACTION_QUEUE;
if (fs->flow_type & FLOW_RSS)
act->queue.ctx = input->rss_ctx;
act->queue.vf = ethtool_get_flow_spec_ring_vf(fs->ring_cookie);
act->queue.index = ethtool_get_flow_spec_ring(fs->ring_cookie);
break;
}
return flow;
}
EXPORT_SYMBOL(ethtool_rx_flow_rule_create);
void ethtool_rx_flow_rule_destroy(struct ethtool_rx_flow_rule *flow)
{
kfree(flow->rule);
kfree(flow);
}
EXPORT_SYMBOL(ethtool_rx_flow_rule_destroy);
| linux-master | net/ethtool/ioctl.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
#include "bitset.h"
struct features_req_info {
struct ethnl_req_info base;
};
struct features_reply_data {
struct ethnl_reply_data base;
u32 hw[ETHTOOL_DEV_FEATURE_WORDS];
u32 wanted[ETHTOOL_DEV_FEATURE_WORDS];
u32 active[ETHTOOL_DEV_FEATURE_WORDS];
u32 nochange[ETHTOOL_DEV_FEATURE_WORDS];
u32 all[ETHTOOL_DEV_FEATURE_WORDS];
};
#define FEATURES_REPDATA(__reply_base) \
container_of(__reply_base, struct features_reply_data, base)
const struct nla_policy ethnl_features_get_policy[] = {
[ETHTOOL_A_FEATURES_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static void ethnl_features_to_bitmap32(u32 *dest, netdev_features_t src)
{
unsigned int i;
for (i = 0; i < ETHTOOL_DEV_FEATURE_WORDS; i++)
dest[i] = src >> (32 * i);
}
static int features_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct features_reply_data *data = FEATURES_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
netdev_features_t all_features;
ethnl_features_to_bitmap32(data->hw, dev->hw_features);
ethnl_features_to_bitmap32(data->wanted, dev->wanted_features);
ethnl_features_to_bitmap32(data->active, dev->features);
ethnl_features_to_bitmap32(data->nochange, NETIF_F_NEVER_CHANGE);
all_features = GENMASK_ULL(NETDEV_FEATURE_COUNT - 1, 0);
ethnl_features_to_bitmap32(data->all, all_features);
return 0;
}
static int features_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct features_reply_data *data = FEATURES_REPDATA(reply_base);
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
unsigned int len = 0;
int ret;
ret = ethnl_bitset32_size(data->hw, data->all, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
return ret;
len += ret;
ret = ethnl_bitset32_size(data->wanted, NULL, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
return ret;
len += ret;
ret = ethnl_bitset32_size(data->active, NULL, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
return ret;
len += ret;
ret = ethnl_bitset32_size(data->nochange, NULL, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
return ret;
len += ret;
return len;
}
static int features_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct features_reply_data *data = FEATURES_REPDATA(reply_base);
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
int ret;
ret = ethnl_put_bitset32(skb, ETHTOOL_A_FEATURES_HW, data->hw,
data->all, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
return ret;
ret = ethnl_put_bitset32(skb, ETHTOOL_A_FEATURES_WANTED, data->wanted,
NULL, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
return ret;
ret = ethnl_put_bitset32(skb, ETHTOOL_A_FEATURES_ACTIVE, data->active,
NULL, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
return ret;
return ethnl_put_bitset32(skb, ETHTOOL_A_FEATURES_NOCHANGE,
data->nochange, NULL, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
}
const struct ethnl_request_ops ethnl_features_request_ops = {
.request_cmd = ETHTOOL_MSG_FEATURES_GET,
.reply_cmd = ETHTOOL_MSG_FEATURES_GET_REPLY,
.hdr_attr = ETHTOOL_A_FEATURES_HEADER,
.req_info_size = sizeof(struct features_req_info),
.reply_data_size = sizeof(struct features_reply_data),
.prepare_data = features_prepare_data,
.reply_size = features_reply_size,
.fill_reply = features_fill_reply,
};
/* FEATURES_SET */
const struct nla_policy ethnl_features_set_policy[] = {
[ETHTOOL_A_FEATURES_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_FEATURES_WANTED] = { .type = NLA_NESTED },
};
static void ethnl_features_to_bitmap(unsigned long *dest, netdev_features_t val)
{
const unsigned int words = BITS_TO_LONGS(NETDEV_FEATURE_COUNT);
unsigned int i;
for (i = 0; i < words; i++)
dest[i] = (unsigned long)(val >> (i * BITS_PER_LONG));
}
static netdev_features_t ethnl_bitmap_to_features(unsigned long *src)
{
const unsigned int nft_bits = sizeof(netdev_features_t) * BITS_PER_BYTE;
const unsigned int words = BITS_TO_LONGS(NETDEV_FEATURE_COUNT);
netdev_features_t ret = 0;
unsigned int i;
for (i = 0; i < words; i++)
ret |= (netdev_features_t)(src[i]) << (i * BITS_PER_LONG);
ret &= ~(netdev_features_t)0 >> (nft_bits - NETDEV_FEATURE_COUNT);
return ret;
}
static int features_send_reply(struct net_device *dev, struct genl_info *info,
const unsigned long *wanted,
const unsigned long *wanted_mask,
const unsigned long *active,
const unsigned long *active_mask, bool compact)
{
struct sk_buff *rskb;
void *reply_payload;
int reply_len = 0;
int ret;
reply_len = ethnl_reply_header_size();
ret = ethnl_bitset_size(wanted, wanted_mask, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
goto err;
reply_len += ret;
ret = ethnl_bitset_size(active, active_mask, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
goto err;
reply_len += ret;
ret = -ENOMEM;
rskb = ethnl_reply_init(reply_len, dev, ETHTOOL_MSG_FEATURES_SET_REPLY,
ETHTOOL_A_FEATURES_HEADER, info,
&reply_payload);
if (!rskb)
goto err;
ret = ethnl_put_bitset(rskb, ETHTOOL_A_FEATURES_WANTED, wanted,
wanted_mask, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
goto nla_put_failure;
ret = ethnl_put_bitset(rskb, ETHTOOL_A_FEATURES_ACTIVE, active,
active_mask, NETDEV_FEATURE_COUNT,
netdev_features_strings, compact);
if (ret < 0)
goto nla_put_failure;
genlmsg_end(rskb, reply_payload);
ret = genlmsg_reply(rskb, info);
return ret;
nla_put_failure:
nlmsg_free(rskb);
WARN_ONCE(1, "calculated message payload length (%d) not sufficient\n",
reply_len);
err:
GENL_SET_ERR_MSG(info, "failed to send reply message");
return ret;
}
int ethnl_set_features(struct sk_buff *skb, struct genl_info *info)
{
DECLARE_BITMAP(wanted_diff_mask, NETDEV_FEATURE_COUNT);
DECLARE_BITMAP(active_diff_mask, NETDEV_FEATURE_COUNT);
DECLARE_BITMAP(old_active, NETDEV_FEATURE_COUNT);
DECLARE_BITMAP(old_wanted, NETDEV_FEATURE_COUNT);
DECLARE_BITMAP(new_active, NETDEV_FEATURE_COUNT);
DECLARE_BITMAP(new_wanted, NETDEV_FEATURE_COUNT);
DECLARE_BITMAP(req_wanted, NETDEV_FEATURE_COUNT);
DECLARE_BITMAP(req_mask, NETDEV_FEATURE_COUNT);
struct ethnl_req_info req_info = {};
struct nlattr **tb = info->attrs;
struct net_device *dev;
bool mod;
int ret;
if (!tb[ETHTOOL_A_FEATURES_WANTED])
return -EINVAL;
ret = ethnl_parse_header_dev_get(&req_info,
tb[ETHTOOL_A_FEATURES_HEADER],
genl_info_net(info), info->extack,
true);
if (ret < 0)
return ret;
dev = req_info.dev;
rtnl_lock();
ethnl_features_to_bitmap(old_active, dev->features);
ethnl_features_to_bitmap(old_wanted, dev->wanted_features);
ret = ethnl_parse_bitset(req_wanted, req_mask, NETDEV_FEATURE_COUNT,
tb[ETHTOOL_A_FEATURES_WANTED],
netdev_features_strings, info->extack);
if (ret < 0)
goto out_rtnl;
if (ethnl_bitmap_to_features(req_mask) & ~NETIF_F_ETHTOOL_BITS) {
GENL_SET_ERR_MSG(info, "attempt to change non-ethtool features");
ret = -EINVAL;
goto out_rtnl;
}
/* set req_wanted bits not in req_mask from old_wanted */
bitmap_and(req_wanted, req_wanted, req_mask, NETDEV_FEATURE_COUNT);
bitmap_andnot(new_wanted, old_wanted, req_mask, NETDEV_FEATURE_COUNT);
bitmap_or(req_wanted, new_wanted, req_wanted, NETDEV_FEATURE_COUNT);
if (!bitmap_equal(req_wanted, old_wanted, NETDEV_FEATURE_COUNT)) {
dev->wanted_features &= ~dev->hw_features;
dev->wanted_features |= ethnl_bitmap_to_features(req_wanted) & dev->hw_features;
__netdev_update_features(dev);
}
ethnl_features_to_bitmap(new_active, dev->features);
mod = !bitmap_equal(old_active, new_active, NETDEV_FEATURE_COUNT);
ret = 0;
if (!(req_info.flags & ETHTOOL_FLAG_OMIT_REPLY)) {
bool compact = req_info.flags & ETHTOOL_FLAG_COMPACT_BITSETS;
bitmap_xor(wanted_diff_mask, req_wanted, new_active,
NETDEV_FEATURE_COUNT);
bitmap_xor(active_diff_mask, old_active, new_active,
NETDEV_FEATURE_COUNT);
bitmap_and(wanted_diff_mask, wanted_diff_mask, req_mask,
NETDEV_FEATURE_COUNT);
bitmap_and(req_wanted, req_wanted, wanted_diff_mask,
NETDEV_FEATURE_COUNT);
bitmap_and(new_active, new_active, active_diff_mask,
NETDEV_FEATURE_COUNT);
ret = features_send_reply(dev, info, req_wanted,
wanted_diff_mask, new_active,
active_diff_mask, compact);
}
if (mod)
netdev_features_change(dev);
out_rtnl:
rtnl_unlock();
ethnl_parse_header_dev_put(&req_info);
return ret;
}
| linux-master | net/ethtool/features.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright 2022-2023 NXP
*/
#include "common.h"
#include "netlink.h"
struct mm_req_info {
struct ethnl_req_info base;
};
struct mm_reply_data {
struct ethnl_reply_data base;
struct ethtool_mm_state state;
struct ethtool_mm_stats stats;
};
#define MM_REPDATA(__reply_base) \
container_of(__reply_base, struct mm_reply_data, base)
#define ETHTOOL_MM_STAT_CNT \
(__ETHTOOL_A_MM_STAT_CNT - (ETHTOOL_A_MM_STAT_PAD + 1))
const struct nla_policy ethnl_mm_get_policy[ETHTOOL_A_MM_HEADER + 1] = {
[ETHTOOL_A_MM_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy_stats),
};
static int mm_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct mm_reply_data *data = MM_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
const struct ethtool_ops *ops;
int ret;
ops = dev->ethtool_ops;
if (!ops->get_mm)
return -EOPNOTSUPP;
ethtool_stats_init((u64 *)&data->stats,
sizeof(data->stats) / sizeof(u64));
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
ret = ops->get_mm(dev, &data->state);
if (ret)
goto out_complete;
if (ops->get_mm_stats && (req_base->flags & ETHTOOL_FLAG_STATS))
ops->get_mm_stats(dev, &data->stats);
out_complete:
ethnl_ops_complete(dev);
return ret;
}
static int mm_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
int len = 0;
len += nla_total_size(sizeof(u8)); /* _MM_PMAC_ENABLED */
len += nla_total_size(sizeof(u8)); /* _MM_TX_ENABLED */
len += nla_total_size(sizeof(u8)); /* _MM_TX_ACTIVE */
len += nla_total_size(sizeof(u8)); /* _MM_VERIFY_ENABLED */
len += nla_total_size(sizeof(u8)); /* _MM_VERIFY_STATUS */
len += nla_total_size(sizeof(u32)); /* _MM_VERIFY_TIME */
len += nla_total_size(sizeof(u32)); /* _MM_MAX_VERIFY_TIME */
len += nla_total_size(sizeof(u32)); /* _MM_TX_MIN_FRAG_SIZE */
len += nla_total_size(sizeof(u32)); /* _MM_RX_MIN_FRAG_SIZE */
if (req_base->flags & ETHTOOL_FLAG_STATS)
len += nla_total_size(0) + /* _MM_STATS */
nla_total_size_64bit(sizeof(u64)) * ETHTOOL_MM_STAT_CNT;
return len;
}
static int mm_put_stat(struct sk_buff *skb, u64 val, u16 attrtype)
{
if (val == ETHTOOL_STAT_NOT_SET)
return 0;
if (nla_put_u64_64bit(skb, attrtype, val, ETHTOOL_A_MM_STAT_PAD))
return -EMSGSIZE;
return 0;
}
static int mm_put_stats(struct sk_buff *skb,
const struct ethtool_mm_stats *stats)
{
struct nlattr *nest;
nest = nla_nest_start(skb, ETHTOOL_A_MM_STATS);
if (!nest)
return -EMSGSIZE;
if (mm_put_stat(skb, stats->MACMergeFrameAssErrorCount,
ETHTOOL_A_MM_STAT_REASSEMBLY_ERRORS) ||
mm_put_stat(skb, stats->MACMergeFrameSmdErrorCount,
ETHTOOL_A_MM_STAT_SMD_ERRORS) ||
mm_put_stat(skb, stats->MACMergeFrameAssOkCount,
ETHTOOL_A_MM_STAT_REASSEMBLY_OK) ||
mm_put_stat(skb, stats->MACMergeFragCountRx,
ETHTOOL_A_MM_STAT_RX_FRAG_COUNT) ||
mm_put_stat(skb, stats->MACMergeFragCountTx,
ETHTOOL_A_MM_STAT_TX_FRAG_COUNT) ||
mm_put_stat(skb, stats->MACMergeHoldCount,
ETHTOOL_A_MM_STAT_HOLD_COUNT))
goto err_cancel;
nla_nest_end(skb, nest);
return 0;
err_cancel:
nla_nest_cancel(skb, nest);
return -EMSGSIZE;
}
static int mm_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct mm_reply_data *data = MM_REPDATA(reply_base);
const struct ethtool_mm_state *state = &data->state;
if (nla_put_u8(skb, ETHTOOL_A_MM_TX_ENABLED, state->tx_enabled) ||
nla_put_u8(skb, ETHTOOL_A_MM_TX_ACTIVE, state->tx_active) ||
nla_put_u8(skb, ETHTOOL_A_MM_PMAC_ENABLED, state->pmac_enabled) ||
nla_put_u8(skb, ETHTOOL_A_MM_VERIFY_ENABLED, state->verify_enabled) ||
nla_put_u8(skb, ETHTOOL_A_MM_VERIFY_STATUS, state->verify_status) ||
nla_put_u32(skb, ETHTOOL_A_MM_VERIFY_TIME, state->verify_time) ||
nla_put_u32(skb, ETHTOOL_A_MM_MAX_VERIFY_TIME, state->max_verify_time) ||
nla_put_u32(skb, ETHTOOL_A_MM_TX_MIN_FRAG_SIZE, state->tx_min_frag_size) ||
nla_put_u32(skb, ETHTOOL_A_MM_RX_MIN_FRAG_SIZE, state->rx_min_frag_size))
return -EMSGSIZE;
if (req_base->flags & ETHTOOL_FLAG_STATS &&
mm_put_stats(skb, &data->stats))
return -EMSGSIZE;
return 0;
}
const struct nla_policy ethnl_mm_set_policy[ETHTOOL_A_MM_MAX + 1] = {
[ETHTOOL_A_MM_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_MM_VERIFY_ENABLED] = NLA_POLICY_MAX(NLA_U8, 1),
[ETHTOOL_A_MM_VERIFY_TIME] = NLA_POLICY_RANGE(NLA_U32, 1, 128),
[ETHTOOL_A_MM_TX_ENABLED] = NLA_POLICY_MAX(NLA_U8, 1),
[ETHTOOL_A_MM_PMAC_ENABLED] = NLA_POLICY_MAX(NLA_U8, 1),
[ETHTOOL_A_MM_TX_MIN_FRAG_SIZE] = NLA_POLICY_RANGE(NLA_U32, 60, 252),
};
static void mm_state_to_cfg(const struct ethtool_mm_state *state,
struct ethtool_mm_cfg *cfg)
{
/* We could also compare state->verify_status against
* ETHTOOL_MM_VERIFY_STATUS_DISABLED, but state->verify_enabled
* is more like an administrative state which should be seen in
* ETHTOOL_MSG_MM_GET replies. For example, a port with verification
* disabled might be in the ETHTOOL_MM_VERIFY_STATUS_INITIAL
* if it's down.
*/
cfg->verify_enabled = state->verify_enabled;
cfg->verify_time = state->verify_time;
cfg->tx_enabled = state->tx_enabled;
cfg->pmac_enabled = state->pmac_enabled;
cfg->tx_min_frag_size = state->tx_min_frag_size;
}
static int
ethnl_set_mm_validate(struct ethnl_req_info *req_info, struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
return ops->get_mm && ops->set_mm ? 1 : -EOPNOTSUPP;
}
static int ethnl_set_mm(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct netlink_ext_ack *extack = info->extack;
struct net_device *dev = req_info->dev;
struct ethtool_mm_state state = {};
struct nlattr **tb = info->attrs;
struct ethtool_mm_cfg cfg = {};
bool mod = false;
int ret;
ret = dev->ethtool_ops->get_mm(dev, &state);
if (ret)
return ret;
mm_state_to_cfg(&state, &cfg);
ethnl_update_bool(&cfg.verify_enabled, tb[ETHTOOL_A_MM_VERIFY_ENABLED],
&mod);
ethnl_update_u32(&cfg.verify_time, tb[ETHTOOL_A_MM_VERIFY_TIME], &mod);
ethnl_update_bool(&cfg.tx_enabled, tb[ETHTOOL_A_MM_TX_ENABLED], &mod);
ethnl_update_bool(&cfg.pmac_enabled, tb[ETHTOOL_A_MM_PMAC_ENABLED],
&mod);
ethnl_update_u32(&cfg.tx_min_frag_size,
tb[ETHTOOL_A_MM_TX_MIN_FRAG_SIZE], &mod);
if (!mod)
return 0;
if (cfg.verify_time > state.max_verify_time) {
NL_SET_ERR_MSG_ATTR(extack, tb[ETHTOOL_A_MM_VERIFY_TIME],
"verifyTime exceeds device maximum");
return -ERANGE;
}
if (cfg.verify_enabled && !cfg.tx_enabled) {
NL_SET_ERR_MSG(extack, "Verification requires TX enabled");
return -EINVAL;
}
if (cfg.tx_enabled && !cfg.pmac_enabled) {
NL_SET_ERR_MSG(extack, "TX enabled requires pMAC enabled");
return -EINVAL;
}
ret = dev->ethtool_ops->set_mm(dev, &cfg, extack);
return ret < 0 ? ret : 1;
}
const struct ethnl_request_ops ethnl_mm_request_ops = {
.request_cmd = ETHTOOL_MSG_MM_GET,
.reply_cmd = ETHTOOL_MSG_MM_GET_REPLY,
.hdr_attr = ETHTOOL_A_MM_HEADER,
.req_info_size = sizeof(struct mm_req_info),
.reply_data_size = sizeof(struct mm_reply_data),
.prepare_data = mm_prepare_data,
.reply_size = mm_reply_size,
.fill_reply = mm_fill_reply,
.set_validate = ethnl_set_mm_validate,
.set = ethnl_set_mm,
.set_ntf_cmd = ETHTOOL_MSG_MM_NTF,
};
/* Returns whether a given device supports the MAC merge layer
* (has an eMAC and a pMAC). Must be called under rtnl_lock() and
* ethnl_ops_begin().
*/
bool __ethtool_dev_mm_supported(struct net_device *dev)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
struct ethtool_mm_state state = {};
int ret = -EOPNOTSUPP;
if (ops && ops->get_mm)
ret = ops->get_mm(dev, &state);
return !ret;
}
bool ethtool_dev_mm_supported(struct net_device *dev)
{
const struct ethtool_ops *ops = dev->ethtool_ops;
bool supported;
int ret;
ASSERT_RTNL();
if (!ops)
return false;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return false;
supported = __ethtool_dev_mm_supported(dev);
ethnl_ops_complete(dev);
return supported;
}
EXPORT_SYMBOL_GPL(ethtool_dev_mm_supported);
| linux-master | net/ethtool/mm.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/ethtool_netlink.h>
#include <net/udp_tunnel.h>
#include <net/vxlan.h>
#include "bitset.h"
#include "common.h"
#include "netlink.h"
const struct nla_policy ethnl_tunnel_info_get_policy[] = {
[ETHTOOL_A_TUNNEL_INFO_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static_assert(ETHTOOL_UDP_TUNNEL_TYPE_VXLAN == ilog2(UDP_TUNNEL_TYPE_VXLAN));
static_assert(ETHTOOL_UDP_TUNNEL_TYPE_GENEVE == ilog2(UDP_TUNNEL_TYPE_GENEVE));
static_assert(ETHTOOL_UDP_TUNNEL_TYPE_VXLAN_GPE ==
ilog2(UDP_TUNNEL_TYPE_VXLAN_GPE));
static ssize_t ethnl_udp_table_reply_size(unsigned int types, bool compact)
{
ssize_t size;
size = ethnl_bitset32_size(&types, NULL, __ETHTOOL_UDP_TUNNEL_TYPE_CNT,
udp_tunnel_type_names, compact);
if (size < 0)
return size;
return size +
nla_total_size(0) + /* _UDP_TABLE */
nla_total_size(sizeof(u32)); /* _UDP_TABLE_SIZE */
}
static ssize_t
ethnl_tunnel_info_reply_size(const struct ethnl_req_info *req_base,
struct netlink_ext_ack *extack)
{
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const struct udp_tunnel_nic_info *info;
unsigned int i;
ssize_t ret;
size_t size;
info = req_base->dev->udp_tunnel_nic_info;
if (!info) {
NL_SET_ERR_MSG(extack,
"device does not report tunnel offload info");
return -EOPNOTSUPP;
}
size = nla_total_size(0); /* _INFO_UDP_PORTS */
for (i = 0; i < UDP_TUNNEL_NIC_MAX_TABLES; i++) {
if (!info->tables[i].n_entries)
break;
ret = ethnl_udp_table_reply_size(info->tables[i].tunnel_types,
compact);
if (ret < 0)
return ret;
size += ret;
size += udp_tunnel_nic_dump_size(req_base->dev, i);
}
if (info->flags & UDP_TUNNEL_NIC_INFO_STATIC_IANA_VXLAN) {
ret = ethnl_udp_table_reply_size(0, compact);
if (ret < 0)
return ret;
size += ret;
size += nla_total_size(0) + /* _TABLE_ENTRY */
nla_total_size(sizeof(__be16)) + /* _ENTRY_PORT */
nla_total_size(sizeof(u32)); /* _ENTRY_TYPE */
}
return size;
}
static int
ethnl_tunnel_info_fill_reply(const struct ethnl_req_info *req_base,
struct sk_buff *skb)
{
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const struct udp_tunnel_nic_info *info;
struct nlattr *ports, *table, *entry;
unsigned int i;
info = req_base->dev->udp_tunnel_nic_info;
if (!info)
return -EOPNOTSUPP;
ports = nla_nest_start(skb, ETHTOOL_A_TUNNEL_INFO_UDP_PORTS);
if (!ports)
return -EMSGSIZE;
for (i = 0; i < UDP_TUNNEL_NIC_MAX_TABLES; i++) {
if (!info->tables[i].n_entries)
break;
table = nla_nest_start(skb, ETHTOOL_A_TUNNEL_UDP_TABLE);
if (!table)
goto err_cancel_ports;
if (nla_put_u32(skb, ETHTOOL_A_TUNNEL_UDP_TABLE_SIZE,
info->tables[i].n_entries))
goto err_cancel_table;
if (ethnl_put_bitset32(skb, ETHTOOL_A_TUNNEL_UDP_TABLE_TYPES,
&info->tables[i].tunnel_types, NULL,
__ETHTOOL_UDP_TUNNEL_TYPE_CNT,
udp_tunnel_type_names, compact))
goto err_cancel_table;
if (udp_tunnel_nic_dump_write(req_base->dev, i, skb))
goto err_cancel_table;
nla_nest_end(skb, table);
}
if (info->flags & UDP_TUNNEL_NIC_INFO_STATIC_IANA_VXLAN) {
u32 zero = 0;
table = nla_nest_start(skb, ETHTOOL_A_TUNNEL_UDP_TABLE);
if (!table)
goto err_cancel_ports;
if (nla_put_u32(skb, ETHTOOL_A_TUNNEL_UDP_TABLE_SIZE, 1))
goto err_cancel_table;
if (ethnl_put_bitset32(skb, ETHTOOL_A_TUNNEL_UDP_TABLE_TYPES,
&zero, NULL,
__ETHTOOL_UDP_TUNNEL_TYPE_CNT,
udp_tunnel_type_names, compact))
goto err_cancel_table;
entry = nla_nest_start(skb, ETHTOOL_A_TUNNEL_UDP_TABLE_ENTRY);
if (!entry)
goto err_cancel_entry;
if (nla_put_be16(skb, ETHTOOL_A_TUNNEL_UDP_ENTRY_PORT,
htons(IANA_VXLAN_UDP_PORT)) ||
nla_put_u32(skb, ETHTOOL_A_TUNNEL_UDP_ENTRY_TYPE,
ilog2(UDP_TUNNEL_TYPE_VXLAN)))
goto err_cancel_entry;
nla_nest_end(skb, entry);
nla_nest_end(skb, table);
}
nla_nest_end(skb, ports);
return 0;
err_cancel_entry:
nla_nest_cancel(skb, entry);
err_cancel_table:
nla_nest_cancel(skb, table);
err_cancel_ports:
nla_nest_cancel(skb, ports);
return -EMSGSIZE;
}
int ethnl_tunnel_info_doit(struct sk_buff *skb, struct genl_info *info)
{
struct ethnl_req_info req_info = {};
struct nlattr **tb = info->attrs;
struct sk_buff *rskb;
void *reply_payload;
int reply_len;
int ret;
ret = ethnl_parse_header_dev_get(&req_info,
tb[ETHTOOL_A_TUNNEL_INFO_HEADER],
genl_info_net(info), info->extack,
true);
if (ret < 0)
return ret;
rtnl_lock();
ret = ethnl_tunnel_info_reply_size(&req_info, info->extack);
if (ret < 0)
goto err_unlock_rtnl;
reply_len = ret + ethnl_reply_header_size();
rskb = ethnl_reply_init(reply_len, req_info.dev,
ETHTOOL_MSG_TUNNEL_INFO_GET_REPLY,
ETHTOOL_A_TUNNEL_INFO_HEADER,
info, &reply_payload);
if (!rskb) {
ret = -ENOMEM;
goto err_unlock_rtnl;
}
ret = ethnl_tunnel_info_fill_reply(&req_info, rskb);
if (ret)
goto err_free_msg;
rtnl_unlock();
ethnl_parse_header_dev_put(&req_info);
genlmsg_end(rskb, reply_payload);
return genlmsg_reply(rskb, info);
err_free_msg:
nlmsg_free(rskb);
err_unlock_rtnl:
rtnl_unlock();
ethnl_parse_header_dev_put(&req_info);
return ret;
}
struct ethnl_tunnel_info_dump_ctx {
struct ethnl_req_info req_info;
unsigned long ifindex;
};
int ethnl_tunnel_info_start(struct netlink_callback *cb)
{
const struct genl_dumpit_info *info = genl_dumpit_info(cb);
struct ethnl_tunnel_info_dump_ctx *ctx = (void *)cb->ctx;
struct nlattr **tb = info->info.attrs;
int ret;
BUILD_BUG_ON(sizeof(*ctx) > sizeof(cb->ctx));
memset(ctx, 0, sizeof(*ctx));
ret = ethnl_parse_header_dev_get(&ctx->req_info,
tb[ETHTOOL_A_TUNNEL_INFO_HEADER],
sock_net(cb->skb->sk), cb->extack,
false);
if (ctx->req_info.dev) {
ethnl_parse_header_dev_put(&ctx->req_info);
ctx->req_info.dev = NULL;
}
return ret;
}
int ethnl_tunnel_info_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
{
struct ethnl_tunnel_info_dump_ctx *ctx = (void *)cb->ctx;
struct net *net = sock_net(skb->sk);
struct net_device *dev;
int ret = 0;
void *ehdr;
rtnl_lock();
for_each_netdev_dump(net, dev, ctx->ifindex) {
ehdr = ethnl_dump_put(skb, cb,
ETHTOOL_MSG_TUNNEL_INFO_GET_REPLY);
if (!ehdr) {
ret = -EMSGSIZE;
break;
}
ret = ethnl_fill_reply_header(skb, dev,
ETHTOOL_A_TUNNEL_INFO_HEADER);
if (ret < 0) {
genlmsg_cancel(skb, ehdr);
break;
}
ctx->req_info.dev = dev;
ret = ethnl_tunnel_info_fill_reply(&ctx->req_info, skb);
ctx->req_info.dev = NULL;
if (ret < 0) {
genlmsg_cancel(skb, ehdr);
if (ret == -EOPNOTSUPP)
continue;
break;
}
genlmsg_end(skb, ehdr);
}
rtnl_unlock();
if (ret == -EMSGSIZE && skb->len)
return skb->len;
return ret;
}
| linux-master | net/ethtool/tunnels.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright 2021 NXP
*/
#include "netlink.h"
#include "common.h"
struct phc_vclocks_req_info {
struct ethnl_req_info base;
};
struct phc_vclocks_reply_data {
struct ethnl_reply_data base;
int num;
int *index;
};
#define PHC_VCLOCKS_REPDATA(__reply_base) \
container_of(__reply_base, struct phc_vclocks_reply_data, base)
const struct nla_policy ethnl_phc_vclocks_get_policy[] = {
[ETHTOOL_A_PHC_VCLOCKS_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy),
};
static int phc_vclocks_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct phc_vclocks_reply_data *data = PHC_VCLOCKS_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
data->num = ethtool_get_phc_vclocks(dev, &data->index);
ethnl_ops_complete(dev);
return ret;
}
static int phc_vclocks_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct phc_vclocks_reply_data *data =
PHC_VCLOCKS_REPDATA(reply_base);
int len = 0;
if (data->num > 0) {
len += nla_total_size(sizeof(u32));
len += nla_total_size(sizeof(s32) * data->num);
}
return len;
}
static int phc_vclocks_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct phc_vclocks_reply_data *data =
PHC_VCLOCKS_REPDATA(reply_base);
if (data->num <= 0)
return 0;
if (nla_put_u32(skb, ETHTOOL_A_PHC_VCLOCKS_NUM, data->num) ||
nla_put(skb, ETHTOOL_A_PHC_VCLOCKS_INDEX,
sizeof(s32) * data->num, data->index))
return -EMSGSIZE;
return 0;
}
static void phc_vclocks_cleanup_data(struct ethnl_reply_data *reply_base)
{
const struct phc_vclocks_reply_data *data =
PHC_VCLOCKS_REPDATA(reply_base);
kfree(data->index);
}
const struct ethnl_request_ops ethnl_phc_vclocks_request_ops = {
.request_cmd = ETHTOOL_MSG_PHC_VCLOCKS_GET,
.reply_cmd = ETHTOOL_MSG_PHC_VCLOCKS_GET_REPLY,
.hdr_attr = ETHTOOL_A_PHC_VCLOCKS_HEADER,
.req_info_size = sizeof(struct phc_vclocks_req_info),
.reply_data_size = sizeof(struct phc_vclocks_reply_data),
.prepare_data = phc_vclocks_prepare_data,
.reply_size = phc_vclocks_reply_size,
.fill_reply = phc_vclocks_fill_reply,
.cleanup_data = phc_vclocks_cleanup_data,
};
| linux-master | net/ethtool/phc_vclocks.c |
// SPDX-License-Identifier: GPL-2.0-only
//
// ethtool interface for Ethernet PSE (Power Sourcing Equipment)
// and PD (Powered Device)
//
// Copyright (c) 2022 Pengutronix, Oleksij Rempel <[email protected]>
//
#include "common.h"
#include "linux/pse-pd/pse.h"
#include "netlink.h"
#include <linux/ethtool_netlink.h>
#include <linux/ethtool.h>
#include <linux/phy.h>
struct pse_req_info {
struct ethnl_req_info base;
};
struct pse_reply_data {
struct ethnl_reply_data base;
struct pse_control_status status;
};
#define PSE_REPDATA(__reply_base) \
container_of(__reply_base, struct pse_reply_data, base)
/* PSE_GET */
const struct nla_policy ethnl_pse_get_policy[ETHTOOL_A_PSE_HEADER + 1] = {
[ETHTOOL_A_PSE_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy),
};
static int pse_get_pse_attributes(struct net_device *dev,
struct netlink_ext_ack *extack,
struct pse_reply_data *data)
{
struct phy_device *phydev = dev->phydev;
if (!phydev) {
NL_SET_ERR_MSG(extack, "No PHY is attached");
return -EOPNOTSUPP;
}
if (!phydev->psec) {
NL_SET_ERR_MSG(extack, "No PSE is attached");
return -EOPNOTSUPP;
}
memset(&data->status, 0, sizeof(data->status));
return pse_ethtool_get_status(phydev->psec, extack, &data->status);
}
static int pse_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct pse_reply_data *data = PSE_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
int ret;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
ret = pse_get_pse_attributes(dev, info->extack, data);
ethnl_ops_complete(dev);
return ret;
}
static int pse_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct pse_reply_data *data = PSE_REPDATA(reply_base);
const struct pse_control_status *st = &data->status;
int len = 0;
if (st->podl_admin_state > 0)
len += nla_total_size(sizeof(u32)); /* _PODL_PSE_ADMIN_STATE */
if (st->podl_pw_status > 0)
len += nla_total_size(sizeof(u32)); /* _PODL_PSE_PW_D_STATUS */
return len;
}
static int pse_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct pse_reply_data *data = PSE_REPDATA(reply_base);
const struct pse_control_status *st = &data->status;
if (st->podl_admin_state > 0 &&
nla_put_u32(skb, ETHTOOL_A_PODL_PSE_ADMIN_STATE,
st->podl_admin_state))
return -EMSGSIZE;
if (st->podl_pw_status > 0 &&
nla_put_u32(skb, ETHTOOL_A_PODL_PSE_PW_D_STATUS,
st->podl_pw_status))
return -EMSGSIZE;
return 0;
}
/* PSE_SET */
const struct nla_policy ethnl_pse_set_policy[ETHTOOL_A_PSE_MAX + 1] = {
[ETHTOOL_A_PSE_HEADER] = NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_PODL_PSE_ADMIN_CONTROL] =
NLA_POLICY_RANGE(NLA_U32, ETHTOOL_PODL_PSE_ADMIN_STATE_DISABLED,
ETHTOOL_PODL_PSE_ADMIN_STATE_ENABLED),
};
static int
ethnl_set_pse_validate(struct ethnl_req_info *req_info, struct genl_info *info)
{
return !!info->attrs[ETHTOOL_A_PODL_PSE_ADMIN_CONTROL];
}
static int
ethnl_set_pse(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct net_device *dev = req_info->dev;
struct pse_control_config config = {};
struct nlattr **tb = info->attrs;
struct phy_device *phydev;
/* this values are already validated by the ethnl_pse_set_policy */
config.admin_cotrol = nla_get_u32(tb[ETHTOOL_A_PODL_PSE_ADMIN_CONTROL]);
phydev = dev->phydev;
if (!phydev) {
NL_SET_ERR_MSG(info->extack, "No PHY is attached");
return -EOPNOTSUPP;
}
if (!phydev->psec) {
NL_SET_ERR_MSG(info->extack, "No PSE is attached");
return -EOPNOTSUPP;
}
/* Return errno directly - PSE has no notification */
return pse_ethtool_set_config(phydev->psec, info->extack, &config);
}
const struct ethnl_request_ops ethnl_pse_request_ops = {
.request_cmd = ETHTOOL_MSG_PSE_GET,
.reply_cmd = ETHTOOL_MSG_PSE_GET_REPLY,
.hdr_attr = ETHTOOL_A_PSE_HEADER,
.req_info_size = sizeof(struct pse_req_info),
.reply_data_size = sizeof(struct pse_reply_data),
.prepare_data = pse_prepare_data,
.reply_size = pse_reply_size,
.fill_reply = pse_fill_reply,
.set_validate = ethnl_set_pse_validate,
.set = ethnl_set_pse,
/* PSE has no notification */
};
| linux-master | net/ethtool/pse-pd.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <net/sock.h>
#include <linux/ethtool_netlink.h>
#include <linux/pm_runtime.h>
#include "netlink.h"
static struct genl_family ethtool_genl_family;
static bool ethnl_ok __read_mostly;
static u32 ethnl_bcast_seq;
#define ETHTOOL_FLAGS_BASIC (ETHTOOL_FLAG_COMPACT_BITSETS | \
ETHTOOL_FLAG_OMIT_REPLY)
#define ETHTOOL_FLAGS_STATS (ETHTOOL_FLAGS_BASIC | ETHTOOL_FLAG_STATS)
const struct nla_policy ethnl_header_policy[] = {
[ETHTOOL_A_HEADER_DEV_INDEX] = { .type = NLA_U32 },
[ETHTOOL_A_HEADER_DEV_NAME] = { .type = NLA_NUL_STRING,
.len = ALTIFNAMSIZ - 1 },
[ETHTOOL_A_HEADER_FLAGS] = NLA_POLICY_MASK(NLA_U32,
ETHTOOL_FLAGS_BASIC),
};
const struct nla_policy ethnl_header_policy_stats[] = {
[ETHTOOL_A_HEADER_DEV_INDEX] = { .type = NLA_U32 },
[ETHTOOL_A_HEADER_DEV_NAME] = { .type = NLA_NUL_STRING,
.len = ALTIFNAMSIZ - 1 },
[ETHTOOL_A_HEADER_FLAGS] = NLA_POLICY_MASK(NLA_U32,
ETHTOOL_FLAGS_STATS),
};
int ethnl_ops_begin(struct net_device *dev)
{
int ret;
if (!dev)
return -ENODEV;
if (dev->dev.parent)
pm_runtime_get_sync(dev->dev.parent);
if (!netif_device_present(dev) ||
dev->reg_state == NETREG_UNREGISTERING) {
ret = -ENODEV;
goto err;
}
if (dev->ethtool_ops->begin) {
ret = dev->ethtool_ops->begin(dev);
if (ret)
goto err;
}
return 0;
err:
if (dev->dev.parent)
pm_runtime_put(dev->dev.parent);
return ret;
}
void ethnl_ops_complete(struct net_device *dev)
{
if (dev->ethtool_ops->complete)
dev->ethtool_ops->complete(dev);
if (dev->dev.parent)
pm_runtime_put(dev->dev.parent);
}
/**
* ethnl_parse_header_dev_get() - parse request header
* @req_info: structure to put results into
* @header: nest attribute with request header
* @net: request netns
* @extack: netlink extack for error reporting
* @require_dev: fail if no device identified in header
*
* Parse request header in nested attribute @nest and puts results into
* the structure pointed to by @req_info. Extack from @info is used for error
* reporting. If req_info->dev is not null on return, reference to it has
* been taken. If error is returned, *req_info is null initialized and no
* reference is held.
*
* Return: 0 on success or negative error code
*/
int ethnl_parse_header_dev_get(struct ethnl_req_info *req_info,
const struct nlattr *header, struct net *net,
struct netlink_ext_ack *extack, bool require_dev)
{
struct nlattr *tb[ARRAY_SIZE(ethnl_header_policy)];
const struct nlattr *devname_attr;
struct net_device *dev = NULL;
u32 flags = 0;
int ret;
if (!header) {
if (!require_dev)
return 0;
NL_SET_ERR_MSG(extack, "request header missing");
return -EINVAL;
}
/* No validation here, command policy should have a nested policy set
* for the header, therefore validation should have already been done.
*/
ret = nla_parse_nested(tb, ARRAY_SIZE(ethnl_header_policy) - 1, header,
NULL, extack);
if (ret < 0)
return ret;
if (tb[ETHTOOL_A_HEADER_FLAGS])
flags = nla_get_u32(tb[ETHTOOL_A_HEADER_FLAGS]);
devname_attr = tb[ETHTOOL_A_HEADER_DEV_NAME];
if (tb[ETHTOOL_A_HEADER_DEV_INDEX]) {
u32 ifindex = nla_get_u32(tb[ETHTOOL_A_HEADER_DEV_INDEX]);
dev = netdev_get_by_index(net, ifindex, &req_info->dev_tracker,
GFP_KERNEL);
if (!dev) {
NL_SET_ERR_MSG_ATTR(extack,
tb[ETHTOOL_A_HEADER_DEV_INDEX],
"no device matches ifindex");
return -ENODEV;
}
/* if both ifindex and ifname are passed, they must match */
if (devname_attr &&
strncmp(dev->name, nla_data(devname_attr), IFNAMSIZ)) {
netdev_put(dev, &req_info->dev_tracker);
NL_SET_ERR_MSG_ATTR(extack, header,
"ifindex and name do not match");
return -ENODEV;
}
} else if (devname_attr) {
dev = netdev_get_by_name(net, nla_data(devname_attr),
&req_info->dev_tracker, GFP_KERNEL);
if (!dev) {
NL_SET_ERR_MSG_ATTR(extack, devname_attr,
"no device matches name");
return -ENODEV;
}
} else if (require_dev) {
NL_SET_ERR_MSG_ATTR(extack, header,
"neither ifindex nor name specified");
return -EINVAL;
}
req_info->dev = dev;
req_info->flags = flags;
return 0;
}
/**
* ethnl_fill_reply_header() - Put common header into a reply message
* @skb: skb with the message
* @dev: network device to describe in header
* @attrtype: attribute type to use for the nest
*
* Create a nested attribute with attributes describing given network device.
*
* Return: 0 on success, error value (-EMSGSIZE only) on error
*/
int ethnl_fill_reply_header(struct sk_buff *skb, struct net_device *dev,
u16 attrtype)
{
struct nlattr *nest;
if (!dev)
return 0;
nest = nla_nest_start(skb, attrtype);
if (!nest)
return -EMSGSIZE;
if (nla_put_u32(skb, ETHTOOL_A_HEADER_DEV_INDEX, (u32)dev->ifindex) ||
nla_put_string(skb, ETHTOOL_A_HEADER_DEV_NAME, dev->name))
goto nla_put_failure;
/* If more attributes are put into reply header, ethnl_header_size()
* must be updated to account for them.
*/
nla_nest_end(skb, nest);
return 0;
nla_put_failure:
nla_nest_cancel(skb, nest);
return -EMSGSIZE;
}
/**
* ethnl_reply_init() - Create skb for a reply and fill device identification
* @payload: payload length (without netlink and genetlink header)
* @dev: device the reply is about (may be null)
* @cmd: ETHTOOL_MSG_* message type for reply
* @hdr_attrtype: attribute type for common header
* @info: genetlink info of the received packet we respond to
* @ehdrp: place to store payload pointer returned by genlmsg_new()
*
* Return: pointer to allocated skb on success, NULL on error
*/
struct sk_buff *ethnl_reply_init(size_t payload, struct net_device *dev, u8 cmd,
u16 hdr_attrtype, struct genl_info *info,
void **ehdrp)
{
struct sk_buff *skb;
skb = genlmsg_new(payload, GFP_KERNEL);
if (!skb)
goto err;
*ehdrp = genlmsg_put_reply(skb, info, ðtool_genl_family, 0, cmd);
if (!*ehdrp)
goto err_free;
if (dev) {
int ret;
ret = ethnl_fill_reply_header(skb, dev, hdr_attrtype);
if (ret < 0)
goto err_free;
}
return skb;
err_free:
nlmsg_free(skb);
err:
if (info)
GENL_SET_ERR_MSG(info, "failed to setup reply message");
return NULL;
}
void *ethnl_dump_put(struct sk_buff *skb, struct netlink_callback *cb, u8 cmd)
{
return genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
ðtool_genl_family, 0, cmd);
}
void *ethnl_bcastmsg_put(struct sk_buff *skb, u8 cmd)
{
return genlmsg_put(skb, 0, ++ethnl_bcast_seq, ðtool_genl_family, 0,
cmd);
}
int ethnl_multicast(struct sk_buff *skb, struct net_device *dev)
{
return genlmsg_multicast_netns(ðtool_genl_family, dev_net(dev), skb,
0, ETHNL_MCGRP_MONITOR, GFP_KERNEL);
}
/* GET request helpers */
/**
* struct ethnl_dump_ctx - context structure for generic dumpit() callback
* @ops: request ops of currently processed message type
* @req_info: parsed request header of processed request
* @reply_data: data needed to compose the reply
* @pos_ifindex: saved iteration position - ifindex
*
* These parameters are kept in struct netlink_callback as context preserved
* between iterations. They are initialized by ethnl_default_start() and used
* in ethnl_default_dumpit() and ethnl_default_done().
*/
struct ethnl_dump_ctx {
const struct ethnl_request_ops *ops;
struct ethnl_req_info *req_info;
struct ethnl_reply_data *reply_data;
unsigned long pos_ifindex;
};
static const struct ethnl_request_ops *
ethnl_default_requests[__ETHTOOL_MSG_USER_CNT] = {
[ETHTOOL_MSG_STRSET_GET] = ðnl_strset_request_ops,
[ETHTOOL_MSG_LINKINFO_GET] = ðnl_linkinfo_request_ops,
[ETHTOOL_MSG_LINKINFO_SET] = ðnl_linkinfo_request_ops,
[ETHTOOL_MSG_LINKMODES_GET] = ðnl_linkmodes_request_ops,
[ETHTOOL_MSG_LINKMODES_SET] = ðnl_linkmodes_request_ops,
[ETHTOOL_MSG_LINKSTATE_GET] = ðnl_linkstate_request_ops,
[ETHTOOL_MSG_DEBUG_GET] = ðnl_debug_request_ops,
[ETHTOOL_MSG_DEBUG_SET] = ðnl_debug_request_ops,
[ETHTOOL_MSG_WOL_GET] = ðnl_wol_request_ops,
[ETHTOOL_MSG_WOL_SET] = ðnl_wol_request_ops,
[ETHTOOL_MSG_FEATURES_GET] = ðnl_features_request_ops,
[ETHTOOL_MSG_PRIVFLAGS_GET] = ðnl_privflags_request_ops,
[ETHTOOL_MSG_PRIVFLAGS_SET] = ðnl_privflags_request_ops,
[ETHTOOL_MSG_RINGS_GET] = ðnl_rings_request_ops,
[ETHTOOL_MSG_RINGS_SET] = ðnl_rings_request_ops,
[ETHTOOL_MSG_CHANNELS_GET] = ðnl_channels_request_ops,
[ETHTOOL_MSG_CHANNELS_SET] = ðnl_channels_request_ops,
[ETHTOOL_MSG_COALESCE_GET] = ðnl_coalesce_request_ops,
[ETHTOOL_MSG_COALESCE_SET] = ðnl_coalesce_request_ops,
[ETHTOOL_MSG_PAUSE_GET] = ðnl_pause_request_ops,
[ETHTOOL_MSG_PAUSE_SET] = ðnl_pause_request_ops,
[ETHTOOL_MSG_EEE_GET] = ðnl_eee_request_ops,
[ETHTOOL_MSG_EEE_SET] = ðnl_eee_request_ops,
[ETHTOOL_MSG_FEC_GET] = ðnl_fec_request_ops,
[ETHTOOL_MSG_FEC_SET] = ðnl_fec_request_ops,
[ETHTOOL_MSG_TSINFO_GET] = ðnl_tsinfo_request_ops,
[ETHTOOL_MSG_MODULE_EEPROM_GET] = ðnl_module_eeprom_request_ops,
[ETHTOOL_MSG_STATS_GET] = ðnl_stats_request_ops,
[ETHTOOL_MSG_PHC_VCLOCKS_GET] = ðnl_phc_vclocks_request_ops,
[ETHTOOL_MSG_MODULE_GET] = ðnl_module_request_ops,
[ETHTOOL_MSG_MODULE_SET] = ðnl_module_request_ops,
[ETHTOOL_MSG_PSE_GET] = ðnl_pse_request_ops,
[ETHTOOL_MSG_PSE_SET] = ðnl_pse_request_ops,
[ETHTOOL_MSG_RSS_GET] = ðnl_rss_request_ops,
[ETHTOOL_MSG_PLCA_GET_CFG] = ðnl_plca_cfg_request_ops,
[ETHTOOL_MSG_PLCA_SET_CFG] = ðnl_plca_cfg_request_ops,
[ETHTOOL_MSG_PLCA_GET_STATUS] = ðnl_plca_status_request_ops,
[ETHTOOL_MSG_MM_GET] = ðnl_mm_request_ops,
[ETHTOOL_MSG_MM_SET] = ðnl_mm_request_ops,
};
static struct ethnl_dump_ctx *ethnl_dump_context(struct netlink_callback *cb)
{
return (struct ethnl_dump_ctx *)cb->ctx;
}
/**
* ethnl_default_parse() - Parse request message
* @req_info: pointer to structure to put data into
* @info: genl_info from the request
* @request_ops: struct request_ops for request type
* @require_dev: fail if no device identified in header
*
* Parse universal request header and call request specific ->parse_request()
* callback (if defined) to parse the rest of the message.
*
* Return: 0 on success or negative error code
*/
static int ethnl_default_parse(struct ethnl_req_info *req_info,
const struct genl_info *info,
const struct ethnl_request_ops *request_ops,
bool require_dev)
{
struct nlattr **tb = info->attrs;
int ret;
ret = ethnl_parse_header_dev_get(req_info, tb[request_ops->hdr_attr],
genl_info_net(info), info->extack,
require_dev);
if (ret < 0)
return ret;
if (request_ops->parse_request) {
ret = request_ops->parse_request(req_info, tb, info->extack);
if (ret < 0)
return ret;
}
return 0;
}
/**
* ethnl_init_reply_data() - Initialize reply data for GET request
* @reply_data: pointer to embedded struct ethnl_reply_data
* @ops: instance of struct ethnl_request_ops describing the layout
* @dev: network device to initialize the reply for
*
* Fills the reply data part with zeros and sets the dev member. Must be called
* before calling the ->fill_reply() callback (for each iteration when handling
* dump requests).
*/
static void ethnl_init_reply_data(struct ethnl_reply_data *reply_data,
const struct ethnl_request_ops *ops,
struct net_device *dev)
{
memset(reply_data, 0, ops->reply_data_size);
reply_data->dev = dev;
}
/* default ->doit() handler for GET type requests */
static int ethnl_default_doit(struct sk_buff *skb, struct genl_info *info)
{
struct ethnl_reply_data *reply_data = NULL;
struct ethnl_req_info *req_info = NULL;
const u8 cmd = info->genlhdr->cmd;
const struct ethnl_request_ops *ops;
int hdr_len, reply_len;
struct sk_buff *rskb;
void *reply_payload;
int ret;
ops = ethnl_default_requests[cmd];
if (WARN_ONCE(!ops, "cmd %u has no ethnl_request_ops\n", cmd))
return -EOPNOTSUPP;
if (GENL_REQ_ATTR_CHECK(info, ops->hdr_attr))
return -EINVAL;
req_info = kzalloc(ops->req_info_size, GFP_KERNEL);
if (!req_info)
return -ENOMEM;
reply_data = kmalloc(ops->reply_data_size, GFP_KERNEL);
if (!reply_data) {
kfree(req_info);
return -ENOMEM;
}
ret = ethnl_default_parse(req_info, info, ops, !ops->allow_nodev_do);
if (ret < 0)
goto err_dev;
ethnl_init_reply_data(reply_data, ops, req_info->dev);
rtnl_lock();
ret = ops->prepare_data(req_info, reply_data, info);
rtnl_unlock();
if (ret < 0)
goto err_cleanup;
ret = ops->reply_size(req_info, reply_data);
if (ret < 0)
goto err_cleanup;
reply_len = ret;
ret = -ENOMEM;
rskb = ethnl_reply_init(reply_len + ethnl_reply_header_size(),
req_info->dev, ops->reply_cmd,
ops->hdr_attr, info, &reply_payload);
if (!rskb)
goto err_cleanup;
hdr_len = rskb->len;
ret = ops->fill_reply(rskb, req_info, reply_data);
if (ret < 0)
goto err_msg;
WARN_ONCE(rskb->len - hdr_len > reply_len,
"ethnl cmd %d: calculated reply length %d, but consumed %d\n",
cmd, reply_len, rskb->len - hdr_len);
if (ops->cleanup_data)
ops->cleanup_data(reply_data);
genlmsg_end(rskb, reply_payload);
netdev_put(req_info->dev, &req_info->dev_tracker);
kfree(reply_data);
kfree(req_info);
return genlmsg_reply(rskb, info);
err_msg:
WARN_ONCE(ret == -EMSGSIZE, "calculated message payload length (%d) not sufficient\n", reply_len);
nlmsg_free(rskb);
err_cleanup:
if (ops->cleanup_data)
ops->cleanup_data(reply_data);
err_dev:
netdev_put(req_info->dev, &req_info->dev_tracker);
kfree(reply_data);
kfree(req_info);
return ret;
}
static int ethnl_default_dump_one(struct sk_buff *skb, struct net_device *dev,
const struct ethnl_dump_ctx *ctx,
const struct genl_info *info)
{
void *ehdr;
int ret;
ehdr = genlmsg_put(skb, info->snd_portid, info->snd_seq,
ðtool_genl_family, NLM_F_MULTI,
ctx->ops->reply_cmd);
if (!ehdr)
return -EMSGSIZE;
ethnl_init_reply_data(ctx->reply_data, ctx->ops, dev);
rtnl_lock();
ret = ctx->ops->prepare_data(ctx->req_info, ctx->reply_data, info);
rtnl_unlock();
if (ret < 0)
goto out;
ret = ethnl_fill_reply_header(skb, dev, ctx->ops->hdr_attr);
if (ret < 0)
goto out;
ret = ctx->ops->fill_reply(skb, ctx->req_info, ctx->reply_data);
out:
if (ctx->ops->cleanup_data)
ctx->ops->cleanup_data(ctx->reply_data);
ctx->reply_data->dev = NULL;
if (ret < 0)
genlmsg_cancel(skb, ehdr);
else
genlmsg_end(skb, ehdr);
return ret;
}
/* Default ->dumpit() handler for GET requests. Device iteration copied from
* rtnl_dump_ifinfo(); we have to be more careful about device hashtable
* persistence as we cannot guarantee to hold RTNL lock through the whole
* function as rtnetnlink does.
*/
static int ethnl_default_dumpit(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct ethnl_dump_ctx *ctx = ethnl_dump_context(cb);
struct net *net = sock_net(skb->sk);
struct net_device *dev;
int ret = 0;
rtnl_lock();
for_each_netdev_dump(net, dev, ctx->pos_ifindex) {
dev_hold(dev);
rtnl_unlock();
ret = ethnl_default_dump_one(skb, dev, ctx, genl_info_dump(cb));
rtnl_lock();
dev_put(dev);
if (ret < 0 && ret != -EOPNOTSUPP) {
if (likely(skb->len))
ret = skb->len;
break;
}
}
rtnl_unlock();
return ret;
}
/* generic ->start() handler for GET requests */
static int ethnl_default_start(struct netlink_callback *cb)
{
const struct genl_dumpit_info *info = genl_dumpit_info(cb);
struct ethnl_dump_ctx *ctx = ethnl_dump_context(cb);
struct ethnl_reply_data *reply_data;
const struct ethnl_request_ops *ops;
struct ethnl_req_info *req_info;
struct genlmsghdr *ghdr;
int ret;
BUILD_BUG_ON(sizeof(*ctx) > sizeof(cb->ctx));
ghdr = nlmsg_data(cb->nlh);
ops = ethnl_default_requests[ghdr->cmd];
if (WARN_ONCE(!ops, "cmd %u has no ethnl_request_ops\n", ghdr->cmd))
return -EOPNOTSUPP;
req_info = kzalloc(ops->req_info_size, GFP_KERNEL);
if (!req_info)
return -ENOMEM;
reply_data = kmalloc(ops->reply_data_size, GFP_KERNEL);
if (!reply_data) {
ret = -ENOMEM;
goto free_req_info;
}
ret = ethnl_default_parse(req_info, &info->info, ops, false);
if (req_info->dev) {
/* We ignore device specification in dump requests but as the
* same parser as for non-dump (doit) requests is used, it
* would take reference to the device if it finds one
*/
netdev_put(req_info->dev, &req_info->dev_tracker);
req_info->dev = NULL;
}
if (ret < 0)
goto free_reply_data;
ctx->ops = ops;
ctx->req_info = req_info;
ctx->reply_data = reply_data;
ctx->pos_ifindex = 0;
return 0;
free_reply_data:
kfree(reply_data);
free_req_info:
kfree(req_info);
return ret;
}
/* default ->done() handler for GET requests */
static int ethnl_default_done(struct netlink_callback *cb)
{
struct ethnl_dump_ctx *ctx = ethnl_dump_context(cb);
kfree(ctx->reply_data);
kfree(ctx->req_info);
return 0;
}
static int ethnl_default_set_doit(struct sk_buff *skb, struct genl_info *info)
{
const struct ethnl_request_ops *ops;
struct ethnl_req_info req_info = {};
const u8 cmd = info->genlhdr->cmd;
int ret;
ops = ethnl_default_requests[cmd];
if (WARN_ONCE(!ops, "cmd %u has no ethnl_request_ops\n", cmd))
return -EOPNOTSUPP;
if (GENL_REQ_ATTR_CHECK(info, ops->hdr_attr))
return -EINVAL;
ret = ethnl_parse_header_dev_get(&req_info, info->attrs[ops->hdr_attr],
genl_info_net(info), info->extack,
true);
if (ret < 0)
return ret;
if (ops->set_validate) {
ret = ops->set_validate(&req_info, info);
/* 0 means nothing to do */
if (ret <= 0)
goto out_dev;
}
rtnl_lock();
ret = ethnl_ops_begin(req_info.dev);
if (ret < 0)
goto out_rtnl;
ret = ops->set(&req_info, info);
if (ret <= 0)
goto out_ops;
ethtool_notify(req_info.dev, ops->set_ntf_cmd, NULL);
ret = 0;
out_ops:
ethnl_ops_complete(req_info.dev);
out_rtnl:
rtnl_unlock();
out_dev:
ethnl_parse_header_dev_put(&req_info);
return ret;
}
static const struct ethnl_request_ops *
ethnl_default_notify_ops[ETHTOOL_MSG_KERNEL_MAX + 1] = {
[ETHTOOL_MSG_LINKINFO_NTF] = ðnl_linkinfo_request_ops,
[ETHTOOL_MSG_LINKMODES_NTF] = ðnl_linkmodes_request_ops,
[ETHTOOL_MSG_DEBUG_NTF] = ðnl_debug_request_ops,
[ETHTOOL_MSG_WOL_NTF] = ðnl_wol_request_ops,
[ETHTOOL_MSG_FEATURES_NTF] = ðnl_features_request_ops,
[ETHTOOL_MSG_PRIVFLAGS_NTF] = ðnl_privflags_request_ops,
[ETHTOOL_MSG_RINGS_NTF] = ðnl_rings_request_ops,
[ETHTOOL_MSG_CHANNELS_NTF] = ðnl_channels_request_ops,
[ETHTOOL_MSG_COALESCE_NTF] = ðnl_coalesce_request_ops,
[ETHTOOL_MSG_PAUSE_NTF] = ðnl_pause_request_ops,
[ETHTOOL_MSG_EEE_NTF] = ðnl_eee_request_ops,
[ETHTOOL_MSG_FEC_NTF] = ðnl_fec_request_ops,
[ETHTOOL_MSG_MODULE_NTF] = ðnl_module_request_ops,
[ETHTOOL_MSG_PLCA_NTF] = ðnl_plca_cfg_request_ops,
[ETHTOOL_MSG_MM_NTF] = ðnl_mm_request_ops,
};
/* default notification handler */
static void ethnl_default_notify(struct net_device *dev, unsigned int cmd,
const void *data)
{
struct ethnl_reply_data *reply_data;
const struct ethnl_request_ops *ops;
struct ethnl_req_info *req_info;
struct genl_info info;
struct sk_buff *skb;
void *reply_payload;
int reply_len;
int ret;
genl_info_init_ntf(&info, ðtool_genl_family, cmd);
if (WARN_ONCE(cmd > ETHTOOL_MSG_KERNEL_MAX ||
!ethnl_default_notify_ops[cmd],
"unexpected notification type %u\n", cmd))
return;
ops = ethnl_default_notify_ops[cmd];
req_info = kzalloc(ops->req_info_size, GFP_KERNEL);
if (!req_info)
return;
reply_data = kmalloc(ops->reply_data_size, GFP_KERNEL);
if (!reply_data) {
kfree(req_info);
return;
}
req_info->dev = dev;
req_info->flags |= ETHTOOL_FLAG_COMPACT_BITSETS;
ethnl_init_reply_data(reply_data, ops, dev);
ret = ops->prepare_data(req_info, reply_data, &info);
if (ret < 0)
goto err_cleanup;
ret = ops->reply_size(req_info, reply_data);
if (ret < 0)
goto err_cleanup;
reply_len = ret + ethnl_reply_header_size();
skb = genlmsg_new(reply_len, GFP_KERNEL);
if (!skb)
goto err_cleanup;
reply_payload = ethnl_bcastmsg_put(skb, cmd);
if (!reply_payload)
goto err_skb;
ret = ethnl_fill_reply_header(skb, dev, ops->hdr_attr);
if (ret < 0)
goto err_msg;
ret = ops->fill_reply(skb, req_info, reply_data);
if (ret < 0)
goto err_msg;
if (ops->cleanup_data)
ops->cleanup_data(reply_data);
genlmsg_end(skb, reply_payload);
kfree(reply_data);
kfree(req_info);
ethnl_multicast(skb, dev);
return;
err_msg:
WARN_ONCE(ret == -EMSGSIZE,
"calculated message payload length (%d) not sufficient\n",
reply_len);
err_skb:
nlmsg_free(skb);
err_cleanup:
if (ops->cleanup_data)
ops->cleanup_data(reply_data);
kfree(reply_data);
kfree(req_info);
return;
}
/* notifications */
typedef void (*ethnl_notify_handler_t)(struct net_device *dev, unsigned int cmd,
const void *data);
static const ethnl_notify_handler_t ethnl_notify_handlers[] = {
[ETHTOOL_MSG_LINKINFO_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_LINKMODES_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_DEBUG_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_WOL_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_FEATURES_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_PRIVFLAGS_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_RINGS_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_CHANNELS_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_COALESCE_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_PAUSE_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_EEE_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_FEC_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_MODULE_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_PLCA_NTF] = ethnl_default_notify,
[ETHTOOL_MSG_MM_NTF] = ethnl_default_notify,
};
void ethtool_notify(struct net_device *dev, unsigned int cmd, const void *data)
{
if (unlikely(!ethnl_ok))
return;
ASSERT_RTNL();
if (likely(cmd < ARRAY_SIZE(ethnl_notify_handlers) &&
ethnl_notify_handlers[cmd]))
ethnl_notify_handlers[cmd](dev, cmd, data);
else
WARN_ONCE(1, "notification %u not implemented (dev=%s)\n",
cmd, netdev_name(dev));
}
EXPORT_SYMBOL(ethtool_notify);
static void ethnl_notify_features(struct netdev_notifier_info *info)
{
struct net_device *dev = netdev_notifier_info_to_dev(info);
ethtool_notify(dev, ETHTOOL_MSG_FEATURES_NTF, NULL);
}
static int ethnl_netdev_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
switch (event) {
case NETDEV_FEAT_CHANGE:
ethnl_notify_features(ptr);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block ethnl_netdev_notifier = {
.notifier_call = ethnl_netdev_event,
};
/* genetlink setup */
static const struct genl_ops ethtool_genl_ops[] = {
{
.cmd = ETHTOOL_MSG_STRSET_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_strset_get_policy,
.maxattr = ARRAY_SIZE(ethnl_strset_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_LINKINFO_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_linkinfo_get_policy,
.maxattr = ARRAY_SIZE(ethnl_linkinfo_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_LINKINFO_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_linkinfo_set_policy,
.maxattr = ARRAY_SIZE(ethnl_linkinfo_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_LINKMODES_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_linkmodes_get_policy,
.maxattr = ARRAY_SIZE(ethnl_linkmodes_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_LINKMODES_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_linkmodes_set_policy,
.maxattr = ARRAY_SIZE(ethnl_linkmodes_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_LINKSTATE_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_linkstate_get_policy,
.maxattr = ARRAY_SIZE(ethnl_linkstate_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_DEBUG_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_debug_get_policy,
.maxattr = ARRAY_SIZE(ethnl_debug_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_DEBUG_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_debug_set_policy,
.maxattr = ARRAY_SIZE(ethnl_debug_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_WOL_GET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_wol_get_policy,
.maxattr = ARRAY_SIZE(ethnl_wol_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_WOL_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_wol_set_policy,
.maxattr = ARRAY_SIZE(ethnl_wol_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_FEATURES_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_features_get_policy,
.maxattr = ARRAY_SIZE(ethnl_features_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_FEATURES_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_set_features,
.policy = ethnl_features_set_policy,
.maxattr = ARRAY_SIZE(ethnl_features_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_PRIVFLAGS_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_privflags_get_policy,
.maxattr = ARRAY_SIZE(ethnl_privflags_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_PRIVFLAGS_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_privflags_set_policy,
.maxattr = ARRAY_SIZE(ethnl_privflags_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_RINGS_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_rings_get_policy,
.maxattr = ARRAY_SIZE(ethnl_rings_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_RINGS_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_rings_set_policy,
.maxattr = ARRAY_SIZE(ethnl_rings_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_CHANNELS_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_channels_get_policy,
.maxattr = ARRAY_SIZE(ethnl_channels_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_CHANNELS_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_channels_set_policy,
.maxattr = ARRAY_SIZE(ethnl_channels_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_COALESCE_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_coalesce_get_policy,
.maxattr = ARRAY_SIZE(ethnl_coalesce_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_COALESCE_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_coalesce_set_policy,
.maxattr = ARRAY_SIZE(ethnl_coalesce_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_PAUSE_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_pause_get_policy,
.maxattr = ARRAY_SIZE(ethnl_pause_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_PAUSE_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_pause_set_policy,
.maxattr = ARRAY_SIZE(ethnl_pause_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_EEE_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_eee_get_policy,
.maxattr = ARRAY_SIZE(ethnl_eee_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_EEE_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_eee_set_policy,
.maxattr = ARRAY_SIZE(ethnl_eee_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_TSINFO_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_tsinfo_get_policy,
.maxattr = ARRAY_SIZE(ethnl_tsinfo_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_CABLE_TEST_ACT,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_act_cable_test,
.policy = ethnl_cable_test_act_policy,
.maxattr = ARRAY_SIZE(ethnl_cable_test_act_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_CABLE_TEST_TDR_ACT,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_act_cable_test_tdr,
.policy = ethnl_cable_test_tdr_act_policy,
.maxattr = ARRAY_SIZE(ethnl_cable_test_tdr_act_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_TUNNEL_INFO_GET,
.doit = ethnl_tunnel_info_doit,
.start = ethnl_tunnel_info_start,
.dumpit = ethnl_tunnel_info_dumpit,
.policy = ethnl_tunnel_info_get_policy,
.maxattr = ARRAY_SIZE(ethnl_tunnel_info_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_FEC_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_fec_get_policy,
.maxattr = ARRAY_SIZE(ethnl_fec_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_FEC_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_fec_set_policy,
.maxattr = ARRAY_SIZE(ethnl_fec_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_MODULE_EEPROM_GET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_module_eeprom_get_policy,
.maxattr = ARRAY_SIZE(ethnl_module_eeprom_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_STATS_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_stats_get_policy,
.maxattr = ARRAY_SIZE(ethnl_stats_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_PHC_VCLOCKS_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_phc_vclocks_get_policy,
.maxattr = ARRAY_SIZE(ethnl_phc_vclocks_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_MODULE_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_module_get_policy,
.maxattr = ARRAY_SIZE(ethnl_module_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_MODULE_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_module_set_policy,
.maxattr = ARRAY_SIZE(ethnl_module_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_PSE_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_pse_get_policy,
.maxattr = ARRAY_SIZE(ethnl_pse_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_PSE_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_pse_set_policy,
.maxattr = ARRAY_SIZE(ethnl_pse_set_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_RSS_GET,
.doit = ethnl_default_doit,
.policy = ethnl_rss_get_policy,
.maxattr = ARRAY_SIZE(ethnl_rss_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_PLCA_GET_CFG,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_plca_get_cfg_policy,
.maxattr = ARRAY_SIZE(ethnl_plca_get_cfg_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_PLCA_SET_CFG,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_plca_set_cfg_policy,
.maxattr = ARRAY_SIZE(ethnl_plca_set_cfg_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_PLCA_GET_STATUS,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_plca_get_status_policy,
.maxattr = ARRAY_SIZE(ethnl_plca_get_status_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_MM_GET,
.doit = ethnl_default_doit,
.start = ethnl_default_start,
.dumpit = ethnl_default_dumpit,
.done = ethnl_default_done,
.policy = ethnl_mm_get_policy,
.maxattr = ARRAY_SIZE(ethnl_mm_get_policy) - 1,
},
{
.cmd = ETHTOOL_MSG_MM_SET,
.flags = GENL_UNS_ADMIN_PERM,
.doit = ethnl_default_set_doit,
.policy = ethnl_mm_set_policy,
.maxattr = ARRAY_SIZE(ethnl_mm_set_policy) - 1,
},
};
static const struct genl_multicast_group ethtool_nl_mcgrps[] = {
[ETHNL_MCGRP_MONITOR] = { .name = ETHTOOL_MCGRP_MONITOR_NAME },
};
static struct genl_family ethtool_genl_family __ro_after_init = {
.name = ETHTOOL_GENL_NAME,
.version = ETHTOOL_GENL_VERSION,
.netnsok = true,
.parallel_ops = true,
.ops = ethtool_genl_ops,
.n_ops = ARRAY_SIZE(ethtool_genl_ops),
.resv_start_op = ETHTOOL_MSG_MODULE_GET + 1,
.mcgrps = ethtool_nl_mcgrps,
.n_mcgrps = ARRAY_SIZE(ethtool_nl_mcgrps),
};
/* module setup */
static int __init ethnl_init(void)
{
int ret;
ret = genl_register_family(ðtool_genl_family);
if (WARN(ret < 0, "ethtool: genetlink family registration failed"))
return ret;
ethnl_ok = true;
ret = register_netdevice_notifier(ðnl_netdev_notifier);
WARN(ret < 0, "ethtool: net device notifier registration failed");
return ret;
}
subsys_initcall(ethnl_init);
| linux-master | net/ethtool/netlink.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
struct pause_req_info {
struct ethnl_req_info base;
enum ethtool_mac_stats_src src;
};
#define PAUSE_REQINFO(__req_base) \
container_of(__req_base, struct pause_req_info, base)
struct pause_reply_data {
struct ethnl_reply_data base;
struct ethtool_pauseparam pauseparam;
struct ethtool_pause_stats pausestat;
};
#define PAUSE_REPDATA(__reply_base) \
container_of(__reply_base, struct pause_reply_data, base)
const struct nla_policy ethnl_pause_get_policy[] = {
[ETHTOOL_A_PAUSE_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy_stats),
[ETHTOOL_A_PAUSE_STATS_SRC] =
NLA_POLICY_MAX(NLA_U32, ETHTOOL_MAC_STATS_SRC_PMAC),
};
static int pause_parse_request(struct ethnl_req_info *req_base,
struct nlattr **tb,
struct netlink_ext_ack *extack)
{
enum ethtool_mac_stats_src src = ETHTOOL_MAC_STATS_SRC_AGGREGATE;
struct pause_req_info *req_info = PAUSE_REQINFO(req_base);
if (tb[ETHTOOL_A_PAUSE_STATS_SRC]) {
if (!(req_base->flags & ETHTOOL_FLAG_STATS)) {
NL_SET_ERR_MSG_MOD(extack,
"ETHTOOL_FLAG_STATS must be set when requesting a source of stats");
return -EINVAL;
}
src = nla_get_u32(tb[ETHTOOL_A_PAUSE_STATS_SRC]);
}
req_info->src = src;
return 0;
}
static int pause_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
const struct pause_req_info *req_info = PAUSE_REQINFO(req_base);
struct pause_reply_data *data = PAUSE_REPDATA(reply_base);
enum ethtool_mac_stats_src src = req_info->src;
struct net_device *dev = reply_base->dev;
int ret;
if (!dev->ethtool_ops->get_pauseparam)
return -EOPNOTSUPP;
ethtool_stats_init((u64 *)&data->pausestat,
sizeof(data->pausestat) / 8);
data->pausestat.src = src;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
if ((src == ETHTOOL_MAC_STATS_SRC_EMAC ||
src == ETHTOOL_MAC_STATS_SRC_PMAC) &&
!__ethtool_dev_mm_supported(dev)) {
NL_SET_ERR_MSG_MOD(info->extack,
"Device does not support MAC merge layer");
ethnl_ops_complete(dev);
return -EOPNOTSUPP;
}
dev->ethtool_ops->get_pauseparam(dev, &data->pauseparam);
if (req_base->flags & ETHTOOL_FLAG_STATS &&
dev->ethtool_ops->get_pause_stats)
dev->ethtool_ops->get_pause_stats(dev, &data->pausestat);
ethnl_ops_complete(dev);
return 0;
}
static int pause_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
int n = nla_total_size(sizeof(u8)) + /* _PAUSE_AUTONEG */
nla_total_size(sizeof(u8)) + /* _PAUSE_RX */
nla_total_size(sizeof(u8)); /* _PAUSE_TX */
if (req_base->flags & ETHTOOL_FLAG_STATS)
n += nla_total_size(0) + /* _PAUSE_STATS */
nla_total_size(sizeof(u32)) + /* _PAUSE_STATS_SRC */
nla_total_size_64bit(sizeof(u64)) * ETHTOOL_PAUSE_STAT_CNT;
return n;
}
static int ethtool_put_stat(struct sk_buff *skb, u64 val, u16 attrtype,
u16 padtype)
{
if (val == ETHTOOL_STAT_NOT_SET)
return 0;
if (nla_put_u64_64bit(skb, attrtype, val, padtype))
return -EMSGSIZE;
return 0;
}
static int pause_put_stats(struct sk_buff *skb,
const struct ethtool_pause_stats *pause_stats)
{
const u16 pad = ETHTOOL_A_PAUSE_STAT_PAD;
struct nlattr *nest;
if (nla_put_u32(skb, ETHTOOL_A_PAUSE_STATS_SRC, pause_stats->src))
return -EMSGSIZE;
nest = nla_nest_start(skb, ETHTOOL_A_PAUSE_STATS);
if (!nest)
return -EMSGSIZE;
if (ethtool_put_stat(skb, pause_stats->tx_pause_frames,
ETHTOOL_A_PAUSE_STAT_TX_FRAMES, pad) ||
ethtool_put_stat(skb, pause_stats->rx_pause_frames,
ETHTOOL_A_PAUSE_STAT_RX_FRAMES, pad))
goto err_cancel;
nla_nest_end(skb, nest);
return 0;
err_cancel:
nla_nest_cancel(skb, nest);
return -EMSGSIZE;
}
static int pause_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct pause_reply_data *data = PAUSE_REPDATA(reply_base);
const struct ethtool_pauseparam *pauseparam = &data->pauseparam;
if (nla_put_u8(skb, ETHTOOL_A_PAUSE_AUTONEG, !!pauseparam->autoneg) ||
nla_put_u8(skb, ETHTOOL_A_PAUSE_RX, !!pauseparam->rx_pause) ||
nla_put_u8(skb, ETHTOOL_A_PAUSE_TX, !!pauseparam->tx_pause))
return -EMSGSIZE;
if (req_base->flags & ETHTOOL_FLAG_STATS &&
pause_put_stats(skb, &data->pausestat))
return -EMSGSIZE;
return 0;
}
/* PAUSE_SET */
const struct nla_policy ethnl_pause_set_policy[] = {
[ETHTOOL_A_PAUSE_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_PAUSE_AUTONEG] = { .type = NLA_U8 },
[ETHTOOL_A_PAUSE_RX] = { .type = NLA_U8 },
[ETHTOOL_A_PAUSE_TX] = { .type = NLA_U8 },
};
static int
ethnl_set_pause_validate(struct ethnl_req_info *req_info,
struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
return ops->get_pauseparam && ops->set_pauseparam ? 1 : -EOPNOTSUPP;
}
static int
ethnl_set_pause(struct ethnl_req_info *req_info, struct genl_info *info)
{
struct net_device *dev = req_info->dev;
struct ethtool_pauseparam params = {};
struct nlattr **tb = info->attrs;
bool mod = false;
int ret;
dev->ethtool_ops->get_pauseparam(dev, ¶ms);
ethnl_update_bool32(¶ms.autoneg, tb[ETHTOOL_A_PAUSE_AUTONEG], &mod);
ethnl_update_bool32(¶ms.rx_pause, tb[ETHTOOL_A_PAUSE_RX], &mod);
ethnl_update_bool32(¶ms.tx_pause, tb[ETHTOOL_A_PAUSE_TX], &mod);
if (!mod)
return 0;
ret = dev->ethtool_ops->set_pauseparam(dev, ¶ms);
return ret < 0 ? ret : 1;
}
const struct ethnl_request_ops ethnl_pause_request_ops = {
.request_cmd = ETHTOOL_MSG_PAUSE_GET,
.reply_cmd = ETHTOOL_MSG_PAUSE_GET_REPLY,
.hdr_attr = ETHTOOL_A_PAUSE_HEADER,
.req_info_size = sizeof(struct pause_req_info),
.reply_data_size = sizeof(struct pause_reply_data),
.parse_request = pause_parse_request,
.prepare_data = pause_prepare_data,
.reply_size = pause_reply_size,
.fill_reply = pause_fill_reply,
.set_validate = ethnl_set_pause_validate,
.set = ethnl_set_pause,
.set_ntf_cmd = ETHTOOL_MSG_PAUSE_NTF,
};
| linux-master | net/ethtool/pause.c |
// SPDX-License-Identifier: GPL-2.0-only
#include "netlink.h"
#include "common.h"
#include "bitset.h"
struct privflags_req_info {
struct ethnl_req_info base;
};
struct privflags_reply_data {
struct ethnl_reply_data base;
const char (*priv_flag_names)[ETH_GSTRING_LEN];
unsigned int n_priv_flags;
u32 priv_flags;
};
#define PRIVFLAGS_REPDATA(__reply_base) \
container_of(__reply_base, struct privflags_reply_data, base)
const struct nla_policy ethnl_privflags_get_policy[] = {
[ETHTOOL_A_PRIVFLAGS_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
};
static int ethnl_get_priv_flags_info(struct net_device *dev,
unsigned int *count,
const char (**names)[ETH_GSTRING_LEN])
{
const struct ethtool_ops *ops = dev->ethtool_ops;
int nflags;
nflags = ops->get_sset_count(dev, ETH_SS_PRIV_FLAGS);
if (nflags < 0)
return nflags;
if (names) {
*names = kcalloc(nflags, ETH_GSTRING_LEN, GFP_KERNEL);
if (!*names)
return -ENOMEM;
ops->get_strings(dev, ETH_SS_PRIV_FLAGS, (u8 *)*names);
}
/* We can pass more than 32 private flags to userspace via netlink but
* we cannot get more with ethtool_ops::get_priv_flags(). Note that we
* must not adjust nflags before allocating the space for flag names
* as the buffer must be large enough for all flags.
*/
if (WARN_ONCE(nflags > 32,
"device %s reports more than 32 private flags (%d)\n",
netdev_name(dev), nflags))
nflags = 32;
*count = nflags;
return 0;
}
static int privflags_prepare_data(const struct ethnl_req_info *req_base,
struct ethnl_reply_data *reply_base,
const struct genl_info *info)
{
struct privflags_reply_data *data = PRIVFLAGS_REPDATA(reply_base);
struct net_device *dev = reply_base->dev;
const char (*names)[ETH_GSTRING_LEN];
const struct ethtool_ops *ops;
unsigned int nflags;
int ret;
ops = dev->ethtool_ops;
if (!ops->get_priv_flags || !ops->get_sset_count || !ops->get_strings)
return -EOPNOTSUPP;
ret = ethnl_ops_begin(dev);
if (ret < 0)
return ret;
ret = ethnl_get_priv_flags_info(dev, &nflags, &names);
if (ret < 0)
goto out_ops;
data->priv_flags = ops->get_priv_flags(dev);
data->priv_flag_names = names;
data->n_priv_flags = nflags;
out_ops:
ethnl_ops_complete(dev);
return ret;
}
static int privflags_reply_size(const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct privflags_reply_data *data = PRIVFLAGS_REPDATA(reply_base);
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const u32 all_flags = ~(u32)0 >> (32 - data->n_priv_flags);
return ethnl_bitset32_size(&data->priv_flags, &all_flags,
data->n_priv_flags,
data->priv_flag_names, compact);
}
static int privflags_fill_reply(struct sk_buff *skb,
const struct ethnl_req_info *req_base,
const struct ethnl_reply_data *reply_base)
{
const struct privflags_reply_data *data = PRIVFLAGS_REPDATA(reply_base);
bool compact = req_base->flags & ETHTOOL_FLAG_COMPACT_BITSETS;
const u32 all_flags = ~(u32)0 >> (32 - data->n_priv_flags);
return ethnl_put_bitset32(skb, ETHTOOL_A_PRIVFLAGS_FLAGS,
&data->priv_flags, &all_flags,
data->n_priv_flags, data->priv_flag_names,
compact);
}
static void privflags_cleanup_data(struct ethnl_reply_data *reply_data)
{
struct privflags_reply_data *data = PRIVFLAGS_REPDATA(reply_data);
kfree(data->priv_flag_names);
}
/* PRIVFLAGS_SET */
const struct nla_policy ethnl_privflags_set_policy[] = {
[ETHTOOL_A_PRIVFLAGS_HEADER] =
NLA_POLICY_NESTED(ethnl_header_policy),
[ETHTOOL_A_PRIVFLAGS_FLAGS] = { .type = NLA_NESTED },
};
static int
ethnl_set_privflags_validate(struct ethnl_req_info *req_info,
struct genl_info *info)
{
const struct ethtool_ops *ops = req_info->dev->ethtool_ops;
if (!info->attrs[ETHTOOL_A_PRIVFLAGS_FLAGS])
return -EINVAL;
if (!ops->get_priv_flags || !ops->set_priv_flags ||
!ops->get_sset_count || !ops->get_strings)
return -EOPNOTSUPP;
return 1;
}
static int
ethnl_set_privflags(struct ethnl_req_info *req_info, struct genl_info *info)
{
const char (*names)[ETH_GSTRING_LEN] = NULL;
struct net_device *dev = req_info->dev;
struct nlattr **tb = info->attrs;
unsigned int nflags;
bool mod = false;
bool compact;
u32 flags;
int ret;
ret = ethnl_bitset_is_compact(tb[ETHTOOL_A_PRIVFLAGS_FLAGS], &compact);
if (ret < 0)
return ret;
ret = ethnl_get_priv_flags_info(dev, &nflags, compact ? NULL : &names);
if (ret < 0)
return ret;
flags = dev->ethtool_ops->get_priv_flags(dev);
ret = ethnl_update_bitset32(&flags, nflags,
tb[ETHTOOL_A_PRIVFLAGS_FLAGS], names,
info->extack, &mod);
if (ret < 0 || !mod)
goto out_free;
ret = dev->ethtool_ops->set_priv_flags(dev, flags);
if (ret < 0)
goto out_free;
ret = 1;
out_free:
kfree(names);
return ret;
}
const struct ethnl_request_ops ethnl_privflags_request_ops = {
.request_cmd = ETHTOOL_MSG_PRIVFLAGS_GET,
.reply_cmd = ETHTOOL_MSG_PRIVFLAGS_GET_REPLY,
.hdr_attr = ETHTOOL_A_PRIVFLAGS_HEADER,
.req_info_size = sizeof(struct privflags_req_info),
.reply_data_size = sizeof(struct privflags_reply_data),
.prepare_data = privflags_prepare_data,
.reply_size = privflags_reply_size,
.fill_reply = privflags_fill_reply,
.cleanup_data = privflags_cleanup_data,
.set_validate = ethnl_set_privflags_validate,
.set = ethnl_set_privflags,
.set_ntf_cmd = ETHTOOL_MSG_PRIVFLAGS_NTF,
};
| linux-master | net/ethtool/privflags.c |
// SPDX-License-Identifier: GPL-2.0
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/init.h>
#include <linux/module.h>
#include <linux/umh.h>
#include <linux/bpfilter.h>
#include <linux/sched.h>
#include <linux/sched/signal.h>
#include <linux/fs.h>
#include <linux/file.h>
#include "msgfmt.h"
extern char bpfilter_umh_start;
extern char bpfilter_umh_end;
static void shutdown_umh(void)
{
struct umd_info *info = &bpfilter_ops.info;
struct pid *tgid = info->tgid;
if (tgid) {
kill_pid(tgid, SIGKILL, 1);
wait_event(tgid->wait_pidfd, thread_group_exited(tgid));
umd_cleanup_helper(info);
}
}
static void __stop_umh(void)
{
if (IS_ENABLED(CONFIG_INET))
shutdown_umh();
}
static int bpfilter_send_req(struct mbox_request *req)
{
struct mbox_reply reply;
loff_t pos = 0;
ssize_t n;
if (!bpfilter_ops.info.tgid)
return -EFAULT;
pos = 0;
n = kernel_write(bpfilter_ops.info.pipe_to_umh, req, sizeof(*req),
&pos);
if (n != sizeof(*req)) {
pr_err("write fail %zd\n", n);
goto stop;
}
pos = 0;
n = kernel_read(bpfilter_ops.info.pipe_from_umh, &reply, sizeof(reply),
&pos);
if (n != sizeof(reply)) {
pr_err("read fail %zd\n", n);
goto stop;
}
return reply.status;
stop:
__stop_umh();
return -EFAULT;
}
static int bpfilter_process_sockopt(struct sock *sk, int optname,
sockptr_t optval, unsigned int optlen,
bool is_set)
{
struct mbox_request req = {
.is_set = is_set,
.pid = current->pid,
.cmd = optname,
.addr = (uintptr_t)optval.user,
.len = optlen,
};
if (sockptr_is_kernel(optval)) {
pr_err("kernel access not supported\n");
return -EFAULT;
}
return bpfilter_send_req(&req);
}
static int start_umh(void)
{
struct mbox_request req = { .pid = current->pid };
int err;
/* fork usermode process */
err = fork_usermode_driver(&bpfilter_ops.info);
if (err)
return err;
pr_info("Loaded bpfilter_umh pid %d\n", pid_nr(bpfilter_ops.info.tgid));
/* health check that usermode process started correctly */
if (bpfilter_send_req(&req) != 0) {
shutdown_umh();
return -EFAULT;
}
return 0;
}
static int __init load_umh(void)
{
int err;
err = umd_load_blob(&bpfilter_ops.info,
&bpfilter_umh_start,
&bpfilter_umh_end - &bpfilter_umh_start);
if (err)
return err;
mutex_lock(&bpfilter_ops.lock);
err = start_umh();
if (!err && IS_ENABLED(CONFIG_INET)) {
bpfilter_ops.sockopt = &bpfilter_process_sockopt;
bpfilter_ops.start = &start_umh;
}
mutex_unlock(&bpfilter_ops.lock);
if (err)
umd_unload_blob(&bpfilter_ops.info);
return err;
}
static void __exit fini_umh(void)
{
mutex_lock(&bpfilter_ops.lock);
if (IS_ENABLED(CONFIG_INET)) {
shutdown_umh();
bpfilter_ops.start = NULL;
bpfilter_ops.sockopt = NULL;
}
mutex_unlock(&bpfilter_ops.lock);
umd_unload_blob(&bpfilter_ops.info);
}
module_init(load_umh);
module_exit(fini_umh);
MODULE_LICENSE("GPL");
| linux-master | net/bpfilter/bpfilter_kern.c |
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <sys/uio.h>
#include <errno.h>
#include <stdio.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
#include "../../include/uapi/linux/bpf.h"
#include <asm/unistd.h>
#include "msgfmt.h"
FILE *debug_f;
static int handle_get_cmd(struct mbox_request *cmd)
{
switch (cmd->cmd) {
case 0:
return 0;
default:
break;
}
return -ENOPROTOOPT;
}
static int handle_set_cmd(struct mbox_request *cmd)
{
return -ENOPROTOOPT;
}
static void loop(void)
{
while (1) {
struct mbox_request req;
struct mbox_reply reply;
int n;
n = read(0, &req, sizeof(req));
if (n != sizeof(req)) {
fprintf(debug_f, "invalid request %d\n", n);
return;
}
reply.status = req.is_set ?
handle_set_cmd(&req) :
handle_get_cmd(&req);
n = write(1, &reply, sizeof(reply));
if (n != sizeof(reply)) {
fprintf(debug_f, "reply failed %d\n", n);
return;
}
}
}
int main(void)
{
debug_f = fopen("/dev/kmsg", "w");
setvbuf(debug_f, 0, _IOLBF, 0);
fprintf(debug_f, "<5>Started bpfilter\n");
loop();
fclose(debug_f);
return 0;
}
| linux-master | net/bpfilter/main.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* net/psample/psample.c - Netlink channel for packet sampling
* Copyright (c) 2017 Yotam Gigi <[email protected]>
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/module.h>
#include <linux/timekeeping.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/netlink.h>
#include <net/genetlink.h>
#include <net/psample.h>
#include <linux/spinlock.h>
#include <net/ip_tunnels.h>
#include <net/dst_metadata.h>
#define PSAMPLE_MAX_PACKET_SIZE 0xffff
static LIST_HEAD(psample_groups_list);
static DEFINE_SPINLOCK(psample_groups_lock);
/* multicast groups */
enum psample_nl_multicast_groups {
PSAMPLE_NL_MCGRP_CONFIG,
PSAMPLE_NL_MCGRP_SAMPLE,
};
static const struct genl_multicast_group psample_nl_mcgrps[] = {
[PSAMPLE_NL_MCGRP_CONFIG] = { .name = PSAMPLE_NL_MCGRP_CONFIG_NAME },
[PSAMPLE_NL_MCGRP_SAMPLE] = { .name = PSAMPLE_NL_MCGRP_SAMPLE_NAME },
};
static struct genl_family psample_nl_family __ro_after_init;
static int psample_group_nl_fill(struct sk_buff *msg,
struct psample_group *group,
enum psample_command cmd, u32 portid, u32 seq,
int flags)
{
void *hdr;
int ret;
hdr = genlmsg_put(msg, portid, seq, &psample_nl_family, flags, cmd);
if (!hdr)
return -EMSGSIZE;
ret = nla_put_u32(msg, PSAMPLE_ATTR_SAMPLE_GROUP, group->group_num);
if (ret < 0)
goto error;
ret = nla_put_u32(msg, PSAMPLE_ATTR_GROUP_REFCOUNT, group->refcount);
if (ret < 0)
goto error;
ret = nla_put_u32(msg, PSAMPLE_ATTR_GROUP_SEQ, group->seq);
if (ret < 0)
goto error;
genlmsg_end(msg, hdr);
return 0;
error:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int psample_nl_cmd_get_group_dumpit(struct sk_buff *msg,
struct netlink_callback *cb)
{
struct psample_group *group;
int start = cb->args[0];
int idx = 0;
int err;
spin_lock_bh(&psample_groups_lock);
list_for_each_entry(group, &psample_groups_list, list) {
if (!net_eq(group->net, sock_net(msg->sk)))
continue;
if (idx < start) {
idx++;
continue;
}
err = psample_group_nl_fill(msg, group, PSAMPLE_CMD_NEW_GROUP,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI);
if (err)
break;
idx++;
}
spin_unlock_bh(&psample_groups_lock);
cb->args[0] = idx;
return msg->len;
}
static const struct genl_small_ops psample_nl_ops[] = {
{
.cmd = PSAMPLE_CMD_GET_GROUP,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.dumpit = psample_nl_cmd_get_group_dumpit,
/* can be retrieved by unprivileged users */
}
};
static struct genl_family psample_nl_family __ro_after_init = {
.name = PSAMPLE_GENL_NAME,
.version = PSAMPLE_GENL_VERSION,
.maxattr = PSAMPLE_ATTR_MAX,
.netnsok = true,
.module = THIS_MODULE,
.mcgrps = psample_nl_mcgrps,
.small_ops = psample_nl_ops,
.n_small_ops = ARRAY_SIZE(psample_nl_ops),
.resv_start_op = PSAMPLE_CMD_GET_GROUP + 1,
.n_mcgrps = ARRAY_SIZE(psample_nl_mcgrps),
};
static void psample_group_notify(struct psample_group *group,
enum psample_command cmd)
{
struct sk_buff *msg;
int err;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!msg)
return;
err = psample_group_nl_fill(msg, group, cmd, 0, 0, NLM_F_MULTI);
if (!err)
genlmsg_multicast_netns(&psample_nl_family, group->net, msg, 0,
PSAMPLE_NL_MCGRP_CONFIG, GFP_ATOMIC);
else
nlmsg_free(msg);
}
static struct psample_group *psample_group_create(struct net *net,
u32 group_num)
{
struct psample_group *group;
group = kzalloc(sizeof(*group), GFP_ATOMIC);
if (!group)
return NULL;
group->net = net;
group->group_num = group_num;
list_add_tail(&group->list, &psample_groups_list);
psample_group_notify(group, PSAMPLE_CMD_NEW_GROUP);
return group;
}
static void psample_group_destroy(struct psample_group *group)
{
psample_group_notify(group, PSAMPLE_CMD_DEL_GROUP);
list_del(&group->list);
kfree_rcu(group, rcu);
}
static struct psample_group *
psample_group_lookup(struct net *net, u32 group_num)
{
struct psample_group *group;
list_for_each_entry(group, &psample_groups_list, list)
if ((group->group_num == group_num) && (group->net == net))
return group;
return NULL;
}
struct psample_group *psample_group_get(struct net *net, u32 group_num)
{
struct psample_group *group;
spin_lock_bh(&psample_groups_lock);
group = psample_group_lookup(net, group_num);
if (!group) {
group = psample_group_create(net, group_num);
if (!group)
goto out;
}
group->refcount++;
out:
spin_unlock_bh(&psample_groups_lock);
return group;
}
EXPORT_SYMBOL_GPL(psample_group_get);
void psample_group_take(struct psample_group *group)
{
spin_lock_bh(&psample_groups_lock);
group->refcount++;
spin_unlock_bh(&psample_groups_lock);
}
EXPORT_SYMBOL_GPL(psample_group_take);
void psample_group_put(struct psample_group *group)
{
spin_lock_bh(&psample_groups_lock);
if (--group->refcount == 0)
psample_group_destroy(group);
spin_unlock_bh(&psample_groups_lock);
}
EXPORT_SYMBOL_GPL(psample_group_put);
#ifdef CONFIG_INET
static int __psample_ip_tun_to_nlattr(struct sk_buff *skb,
struct ip_tunnel_info *tun_info)
{
unsigned short tun_proto = ip_tunnel_info_af(tun_info);
const void *tun_opts = ip_tunnel_info_opts(tun_info);
const struct ip_tunnel_key *tun_key = &tun_info->key;
int tun_opts_len = tun_info->options_len;
if (tun_key->tun_flags & TUNNEL_KEY &&
nla_put_be64(skb, PSAMPLE_TUNNEL_KEY_ATTR_ID, tun_key->tun_id,
PSAMPLE_TUNNEL_KEY_ATTR_PAD))
return -EMSGSIZE;
if (tun_info->mode & IP_TUNNEL_INFO_BRIDGE &&
nla_put_flag(skb, PSAMPLE_TUNNEL_KEY_ATTR_IPV4_INFO_BRIDGE))
return -EMSGSIZE;
switch (tun_proto) {
case AF_INET:
if (tun_key->u.ipv4.src &&
nla_put_in_addr(skb, PSAMPLE_TUNNEL_KEY_ATTR_IPV4_SRC,
tun_key->u.ipv4.src))
return -EMSGSIZE;
if (tun_key->u.ipv4.dst &&
nla_put_in_addr(skb, PSAMPLE_TUNNEL_KEY_ATTR_IPV4_DST,
tun_key->u.ipv4.dst))
return -EMSGSIZE;
break;
case AF_INET6:
if (!ipv6_addr_any(&tun_key->u.ipv6.src) &&
nla_put_in6_addr(skb, PSAMPLE_TUNNEL_KEY_ATTR_IPV6_SRC,
&tun_key->u.ipv6.src))
return -EMSGSIZE;
if (!ipv6_addr_any(&tun_key->u.ipv6.dst) &&
nla_put_in6_addr(skb, PSAMPLE_TUNNEL_KEY_ATTR_IPV6_DST,
&tun_key->u.ipv6.dst))
return -EMSGSIZE;
break;
}
if (tun_key->tos &&
nla_put_u8(skb, PSAMPLE_TUNNEL_KEY_ATTR_TOS, tun_key->tos))
return -EMSGSIZE;
if (nla_put_u8(skb, PSAMPLE_TUNNEL_KEY_ATTR_TTL, tun_key->ttl))
return -EMSGSIZE;
if ((tun_key->tun_flags & TUNNEL_DONT_FRAGMENT) &&
nla_put_flag(skb, PSAMPLE_TUNNEL_KEY_ATTR_DONT_FRAGMENT))
return -EMSGSIZE;
if ((tun_key->tun_flags & TUNNEL_CSUM) &&
nla_put_flag(skb, PSAMPLE_TUNNEL_KEY_ATTR_CSUM))
return -EMSGSIZE;
if (tun_key->tp_src &&
nla_put_be16(skb, PSAMPLE_TUNNEL_KEY_ATTR_TP_SRC, tun_key->tp_src))
return -EMSGSIZE;
if (tun_key->tp_dst &&
nla_put_be16(skb, PSAMPLE_TUNNEL_KEY_ATTR_TP_DST, tun_key->tp_dst))
return -EMSGSIZE;
if ((tun_key->tun_flags & TUNNEL_OAM) &&
nla_put_flag(skb, PSAMPLE_TUNNEL_KEY_ATTR_OAM))
return -EMSGSIZE;
if (tun_opts_len) {
if (tun_key->tun_flags & TUNNEL_GENEVE_OPT &&
nla_put(skb, PSAMPLE_TUNNEL_KEY_ATTR_GENEVE_OPTS,
tun_opts_len, tun_opts))
return -EMSGSIZE;
else if (tun_key->tun_flags & TUNNEL_ERSPAN_OPT &&
nla_put(skb, PSAMPLE_TUNNEL_KEY_ATTR_ERSPAN_OPTS,
tun_opts_len, tun_opts))
return -EMSGSIZE;
}
return 0;
}
static int psample_ip_tun_to_nlattr(struct sk_buff *skb,
struct ip_tunnel_info *tun_info)
{
struct nlattr *nla;
int err;
nla = nla_nest_start_noflag(skb, PSAMPLE_ATTR_TUNNEL);
if (!nla)
return -EMSGSIZE;
err = __psample_ip_tun_to_nlattr(skb, tun_info);
if (err) {
nla_nest_cancel(skb, nla);
return err;
}
nla_nest_end(skb, nla);
return 0;
}
static int psample_tunnel_meta_len(struct ip_tunnel_info *tun_info)
{
unsigned short tun_proto = ip_tunnel_info_af(tun_info);
const struct ip_tunnel_key *tun_key = &tun_info->key;
int tun_opts_len = tun_info->options_len;
int sum = nla_total_size(0); /* PSAMPLE_ATTR_TUNNEL */
if (tun_key->tun_flags & TUNNEL_KEY)
sum += nla_total_size_64bit(sizeof(u64));
if (tun_info->mode & IP_TUNNEL_INFO_BRIDGE)
sum += nla_total_size(0);
switch (tun_proto) {
case AF_INET:
if (tun_key->u.ipv4.src)
sum += nla_total_size(sizeof(u32));
if (tun_key->u.ipv4.dst)
sum += nla_total_size(sizeof(u32));
break;
case AF_INET6:
if (!ipv6_addr_any(&tun_key->u.ipv6.src))
sum += nla_total_size(sizeof(struct in6_addr));
if (!ipv6_addr_any(&tun_key->u.ipv6.dst))
sum += nla_total_size(sizeof(struct in6_addr));
break;
}
if (tun_key->tos)
sum += nla_total_size(sizeof(u8));
sum += nla_total_size(sizeof(u8)); /* TTL */
if (tun_key->tun_flags & TUNNEL_DONT_FRAGMENT)
sum += nla_total_size(0);
if (tun_key->tun_flags & TUNNEL_CSUM)
sum += nla_total_size(0);
if (tun_key->tp_src)
sum += nla_total_size(sizeof(u16));
if (tun_key->tp_dst)
sum += nla_total_size(sizeof(u16));
if (tun_key->tun_flags & TUNNEL_OAM)
sum += nla_total_size(0);
if (tun_opts_len) {
if (tun_key->tun_flags & TUNNEL_GENEVE_OPT)
sum += nla_total_size(tun_opts_len);
else if (tun_key->tun_flags & TUNNEL_ERSPAN_OPT)
sum += nla_total_size(tun_opts_len);
}
return sum;
}
#endif
void psample_sample_packet(struct psample_group *group, struct sk_buff *skb,
u32 sample_rate, const struct psample_metadata *md)
{
ktime_t tstamp = ktime_get_real();
int out_ifindex = md->out_ifindex;
int in_ifindex = md->in_ifindex;
u32 trunc_size = md->trunc_size;
#ifdef CONFIG_INET
struct ip_tunnel_info *tun_info;
#endif
struct sk_buff *nl_skb;
int data_len;
int meta_len;
void *data;
int ret;
meta_len = (in_ifindex ? nla_total_size(sizeof(u16)) : 0) +
(out_ifindex ? nla_total_size(sizeof(u16)) : 0) +
(md->out_tc_valid ? nla_total_size(sizeof(u16)) : 0) +
(md->out_tc_occ_valid ? nla_total_size_64bit(sizeof(u64)) : 0) +
(md->latency_valid ? nla_total_size_64bit(sizeof(u64)) : 0) +
nla_total_size(sizeof(u32)) + /* sample_rate */
nla_total_size(sizeof(u32)) + /* orig_size */
nla_total_size(sizeof(u32)) + /* group_num */
nla_total_size(sizeof(u32)) + /* seq */
nla_total_size_64bit(sizeof(u64)) + /* timestamp */
nla_total_size(sizeof(u16)); /* protocol */
#ifdef CONFIG_INET
tun_info = skb_tunnel_info(skb);
if (tun_info)
meta_len += psample_tunnel_meta_len(tun_info);
#endif
data_len = min(skb->len, trunc_size);
if (meta_len + nla_total_size(data_len) > PSAMPLE_MAX_PACKET_SIZE)
data_len = PSAMPLE_MAX_PACKET_SIZE - meta_len - NLA_HDRLEN
- NLA_ALIGNTO;
nl_skb = genlmsg_new(meta_len + nla_total_size(data_len), GFP_ATOMIC);
if (unlikely(!nl_skb))
return;
data = genlmsg_put(nl_skb, 0, 0, &psample_nl_family, 0,
PSAMPLE_CMD_SAMPLE);
if (unlikely(!data))
goto error;
if (in_ifindex) {
ret = nla_put_u16(nl_skb, PSAMPLE_ATTR_IIFINDEX, in_ifindex);
if (unlikely(ret < 0))
goto error;
}
if (out_ifindex) {
ret = nla_put_u16(nl_skb, PSAMPLE_ATTR_OIFINDEX, out_ifindex);
if (unlikely(ret < 0))
goto error;
}
ret = nla_put_u32(nl_skb, PSAMPLE_ATTR_SAMPLE_RATE, sample_rate);
if (unlikely(ret < 0))
goto error;
ret = nla_put_u32(nl_skb, PSAMPLE_ATTR_ORIGSIZE, skb->len);
if (unlikely(ret < 0))
goto error;
ret = nla_put_u32(nl_skb, PSAMPLE_ATTR_SAMPLE_GROUP, group->group_num);
if (unlikely(ret < 0))
goto error;
ret = nla_put_u32(nl_skb, PSAMPLE_ATTR_GROUP_SEQ, group->seq++);
if (unlikely(ret < 0))
goto error;
if (md->out_tc_valid) {
ret = nla_put_u16(nl_skb, PSAMPLE_ATTR_OUT_TC, md->out_tc);
if (unlikely(ret < 0))
goto error;
}
if (md->out_tc_occ_valid) {
ret = nla_put_u64_64bit(nl_skb, PSAMPLE_ATTR_OUT_TC_OCC,
md->out_tc_occ, PSAMPLE_ATTR_PAD);
if (unlikely(ret < 0))
goto error;
}
if (md->latency_valid) {
ret = nla_put_u64_64bit(nl_skb, PSAMPLE_ATTR_LATENCY,
md->latency, PSAMPLE_ATTR_PAD);
if (unlikely(ret < 0))
goto error;
}
ret = nla_put_u64_64bit(nl_skb, PSAMPLE_ATTR_TIMESTAMP,
ktime_to_ns(tstamp), PSAMPLE_ATTR_PAD);
if (unlikely(ret < 0))
goto error;
ret = nla_put_u16(nl_skb, PSAMPLE_ATTR_PROTO,
be16_to_cpu(skb->protocol));
if (unlikely(ret < 0))
goto error;
if (data_len) {
int nla_len = nla_total_size(data_len);
struct nlattr *nla;
nla = skb_put(nl_skb, nla_len);
nla->nla_type = PSAMPLE_ATTR_DATA;
nla->nla_len = nla_attr_size(data_len);
if (skb_copy_bits(skb, 0, nla_data(nla), data_len))
goto error;
}
#ifdef CONFIG_INET
if (tun_info) {
ret = psample_ip_tun_to_nlattr(nl_skb, tun_info);
if (unlikely(ret < 0))
goto error;
}
#endif
genlmsg_end(nl_skb, data);
genlmsg_multicast_netns(&psample_nl_family, group->net, nl_skb, 0,
PSAMPLE_NL_MCGRP_SAMPLE, GFP_ATOMIC);
return;
error:
pr_err_ratelimited("Could not create psample log message\n");
nlmsg_free(nl_skb);
}
EXPORT_SYMBOL_GPL(psample_sample_packet);
static int __init psample_module_init(void)
{
return genl_register_family(&psample_nl_family);
}
static void __exit psample_module_exit(void)
{
genl_unregister_family(&psample_nl_family);
}
module_init(psample_module_init);
module_exit(psample_module_exit);
MODULE_AUTHOR("Yotam Gigi <[email protected]>");
MODULE_DESCRIPTION("netlink channel for packet sampling");
MODULE_LICENSE("GPL v2");
| linux-master | net/psample/psample.c |
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2017 Facebook
*/
#include <linux/bpf.h>
#include <linux/btf.h>
#include <linux/btf_ids.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/vmalloc.h>
#include <linux/etherdevice.h>
#include <linux/filter.h>
#include <linux/rcupdate_trace.h>
#include <linux/sched/signal.h>
#include <net/bpf_sk_storage.h>
#include <net/sock.h>
#include <net/tcp.h>
#include <net/net_namespace.h>
#include <net/page_pool/helpers.h>
#include <linux/error-injection.h>
#include <linux/smp.h>
#include <linux/sock_diag.h>
#include <linux/netfilter.h>
#include <net/netdev_rx_queue.h>
#include <net/xdp.h>
#include <net/netfilter/nf_bpf_link.h>
#define CREATE_TRACE_POINTS
#include <trace/events/bpf_test_run.h>
struct bpf_test_timer {
enum { NO_PREEMPT, NO_MIGRATE } mode;
u32 i;
u64 time_start, time_spent;
};
static void bpf_test_timer_enter(struct bpf_test_timer *t)
__acquires(rcu)
{
rcu_read_lock();
if (t->mode == NO_PREEMPT)
preempt_disable();
else
migrate_disable();
t->time_start = ktime_get_ns();
}
static void bpf_test_timer_leave(struct bpf_test_timer *t)
__releases(rcu)
{
t->time_start = 0;
if (t->mode == NO_PREEMPT)
preempt_enable();
else
migrate_enable();
rcu_read_unlock();
}
static bool bpf_test_timer_continue(struct bpf_test_timer *t, int iterations,
u32 repeat, int *err, u32 *duration)
__must_hold(rcu)
{
t->i += iterations;
if (t->i >= repeat) {
/* We're done. */
t->time_spent += ktime_get_ns() - t->time_start;
do_div(t->time_spent, t->i);
*duration = t->time_spent > U32_MAX ? U32_MAX : (u32)t->time_spent;
*err = 0;
goto reset;
}
if (signal_pending(current)) {
/* During iteration: we've been cancelled, abort. */
*err = -EINTR;
goto reset;
}
if (need_resched()) {
/* During iteration: we need to reschedule between runs. */
t->time_spent += ktime_get_ns() - t->time_start;
bpf_test_timer_leave(t);
cond_resched();
bpf_test_timer_enter(t);
}
/* Do another round. */
return true;
reset:
t->i = 0;
return false;
}
/* We put this struct at the head of each page with a context and frame
* initialised when the page is allocated, so we don't have to do this on each
* repetition of the test run.
*/
struct xdp_page_head {
struct xdp_buff orig_ctx;
struct xdp_buff ctx;
union {
/* ::data_hard_start starts here */
DECLARE_FLEX_ARRAY(struct xdp_frame, frame);
DECLARE_FLEX_ARRAY(u8, data);
};
};
struct xdp_test_data {
struct xdp_buff *orig_ctx;
struct xdp_rxq_info rxq;
struct net_device *dev;
struct page_pool *pp;
struct xdp_frame **frames;
struct sk_buff **skbs;
struct xdp_mem_info mem;
u32 batch_size;
u32 frame_cnt;
};
/* tools/testing/selftests/bpf/prog_tests/xdp_do_redirect.c:%MAX_PKT_SIZE
* must be updated accordingly this gets changed, otherwise BPF selftests
* will fail.
*/
#define TEST_XDP_FRAME_SIZE (PAGE_SIZE - sizeof(struct xdp_page_head))
#define TEST_XDP_MAX_BATCH 256
static void xdp_test_run_init_page(struct page *page, void *arg)
{
struct xdp_page_head *head = phys_to_virt(page_to_phys(page));
struct xdp_buff *new_ctx, *orig_ctx;
u32 headroom = XDP_PACKET_HEADROOM;
struct xdp_test_data *xdp = arg;
size_t frm_len, meta_len;
struct xdp_frame *frm;
void *data;
orig_ctx = xdp->orig_ctx;
frm_len = orig_ctx->data_end - orig_ctx->data_meta;
meta_len = orig_ctx->data - orig_ctx->data_meta;
headroom -= meta_len;
new_ctx = &head->ctx;
frm = head->frame;
data = head->data;
memcpy(data + headroom, orig_ctx->data_meta, frm_len);
xdp_init_buff(new_ctx, TEST_XDP_FRAME_SIZE, &xdp->rxq);
xdp_prepare_buff(new_ctx, data, headroom, frm_len, true);
new_ctx->data = new_ctx->data_meta + meta_len;
xdp_update_frame_from_buff(new_ctx, frm);
frm->mem = new_ctx->rxq->mem;
memcpy(&head->orig_ctx, new_ctx, sizeof(head->orig_ctx));
}
static int xdp_test_run_setup(struct xdp_test_data *xdp, struct xdp_buff *orig_ctx)
{
struct page_pool *pp;
int err = -ENOMEM;
struct page_pool_params pp_params = {
.order = 0,
.flags = 0,
.pool_size = xdp->batch_size,
.nid = NUMA_NO_NODE,
.init_callback = xdp_test_run_init_page,
.init_arg = xdp,
};
xdp->frames = kvmalloc_array(xdp->batch_size, sizeof(void *), GFP_KERNEL);
if (!xdp->frames)
return -ENOMEM;
xdp->skbs = kvmalloc_array(xdp->batch_size, sizeof(void *), GFP_KERNEL);
if (!xdp->skbs)
goto err_skbs;
pp = page_pool_create(&pp_params);
if (IS_ERR(pp)) {
err = PTR_ERR(pp);
goto err_pp;
}
/* will copy 'mem.id' into pp->xdp_mem_id */
err = xdp_reg_mem_model(&xdp->mem, MEM_TYPE_PAGE_POOL, pp);
if (err)
goto err_mmodel;
xdp->pp = pp;
/* We create a 'fake' RXQ referencing the original dev, but with an
* xdp_mem_info pointing to our page_pool
*/
xdp_rxq_info_reg(&xdp->rxq, orig_ctx->rxq->dev, 0, 0);
xdp->rxq.mem.type = MEM_TYPE_PAGE_POOL;
xdp->rxq.mem.id = pp->xdp_mem_id;
xdp->dev = orig_ctx->rxq->dev;
xdp->orig_ctx = orig_ctx;
return 0;
err_mmodel:
page_pool_destroy(pp);
err_pp:
kvfree(xdp->skbs);
err_skbs:
kvfree(xdp->frames);
return err;
}
static void xdp_test_run_teardown(struct xdp_test_data *xdp)
{
xdp_unreg_mem_model(&xdp->mem);
page_pool_destroy(xdp->pp);
kfree(xdp->frames);
kfree(xdp->skbs);
}
static bool frame_was_changed(const struct xdp_page_head *head)
{
/* xdp_scrub_frame() zeroes the data pointer, flags is the last field,
* i.e. has the highest chances to be overwritten. If those two are
* untouched, it's most likely safe to skip the context reset.
*/
return head->frame->data != head->orig_ctx.data ||
head->frame->flags != head->orig_ctx.flags;
}
static bool ctx_was_changed(struct xdp_page_head *head)
{
return head->orig_ctx.data != head->ctx.data ||
head->orig_ctx.data_meta != head->ctx.data_meta ||
head->orig_ctx.data_end != head->ctx.data_end;
}
static void reset_ctx(struct xdp_page_head *head)
{
if (likely(!frame_was_changed(head) && !ctx_was_changed(head)))
return;
head->ctx.data = head->orig_ctx.data;
head->ctx.data_meta = head->orig_ctx.data_meta;
head->ctx.data_end = head->orig_ctx.data_end;
xdp_update_frame_from_buff(&head->ctx, head->frame);
}
static int xdp_recv_frames(struct xdp_frame **frames, int nframes,
struct sk_buff **skbs,
struct net_device *dev)
{
gfp_t gfp = __GFP_ZERO | GFP_ATOMIC;
int i, n;
LIST_HEAD(list);
n = kmem_cache_alloc_bulk(skbuff_cache, gfp, nframes, (void **)skbs);
if (unlikely(n == 0)) {
for (i = 0; i < nframes; i++)
xdp_return_frame(frames[i]);
return -ENOMEM;
}
for (i = 0; i < nframes; i++) {
struct xdp_frame *xdpf = frames[i];
struct sk_buff *skb = skbs[i];
skb = __xdp_build_skb_from_frame(xdpf, skb, dev);
if (!skb) {
xdp_return_frame(xdpf);
continue;
}
list_add_tail(&skb->list, &list);
}
netif_receive_skb_list(&list);
return 0;
}
static int xdp_test_run_batch(struct xdp_test_data *xdp, struct bpf_prog *prog,
u32 repeat)
{
struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
int err = 0, act, ret, i, nframes = 0, batch_sz;
struct xdp_frame **frames = xdp->frames;
struct xdp_page_head *head;
struct xdp_frame *frm;
bool redirect = false;
struct xdp_buff *ctx;
struct page *page;
batch_sz = min_t(u32, repeat, xdp->batch_size);
local_bh_disable();
xdp_set_return_frame_no_direct();
for (i = 0; i < batch_sz; i++) {
page = page_pool_dev_alloc_pages(xdp->pp);
if (!page) {
err = -ENOMEM;
goto out;
}
head = phys_to_virt(page_to_phys(page));
reset_ctx(head);
ctx = &head->ctx;
frm = head->frame;
xdp->frame_cnt++;
act = bpf_prog_run_xdp(prog, ctx);
/* if program changed pkt bounds we need to update the xdp_frame */
if (unlikely(ctx_was_changed(head))) {
ret = xdp_update_frame_from_buff(ctx, frm);
if (ret) {
xdp_return_buff(ctx);
continue;
}
}
switch (act) {
case XDP_TX:
/* we can't do a real XDP_TX since we're not in the
* driver, so turn it into a REDIRECT back to the same
* index
*/
ri->tgt_index = xdp->dev->ifindex;
ri->map_id = INT_MAX;
ri->map_type = BPF_MAP_TYPE_UNSPEC;
fallthrough;
case XDP_REDIRECT:
redirect = true;
ret = xdp_do_redirect_frame(xdp->dev, ctx, frm, prog);
if (ret)
xdp_return_buff(ctx);
break;
case XDP_PASS:
frames[nframes++] = frm;
break;
default:
bpf_warn_invalid_xdp_action(NULL, prog, act);
fallthrough;
case XDP_DROP:
xdp_return_buff(ctx);
break;
}
}
out:
if (redirect)
xdp_do_flush();
if (nframes) {
ret = xdp_recv_frames(frames, nframes, xdp->skbs, xdp->dev);
if (ret)
err = ret;
}
xdp_clear_return_frame_no_direct();
local_bh_enable();
return err;
}
static int bpf_test_run_xdp_live(struct bpf_prog *prog, struct xdp_buff *ctx,
u32 repeat, u32 batch_size, u32 *time)
{
struct xdp_test_data xdp = { .batch_size = batch_size };
struct bpf_test_timer t = { .mode = NO_MIGRATE };
int ret;
if (!repeat)
repeat = 1;
ret = xdp_test_run_setup(&xdp, ctx);
if (ret)
return ret;
bpf_test_timer_enter(&t);
do {
xdp.frame_cnt = 0;
ret = xdp_test_run_batch(&xdp, prog, repeat - t.i);
if (unlikely(ret < 0))
break;
} while (bpf_test_timer_continue(&t, xdp.frame_cnt, repeat, &ret, time));
bpf_test_timer_leave(&t);
xdp_test_run_teardown(&xdp);
return ret;
}
static int bpf_test_run(struct bpf_prog *prog, void *ctx, u32 repeat,
u32 *retval, u32 *time, bool xdp)
{
struct bpf_prog_array_item item = {.prog = prog};
struct bpf_run_ctx *old_ctx;
struct bpf_cg_run_ctx run_ctx;
struct bpf_test_timer t = { NO_MIGRATE };
enum bpf_cgroup_storage_type stype;
int ret;
for_each_cgroup_storage_type(stype) {
item.cgroup_storage[stype] = bpf_cgroup_storage_alloc(prog, stype);
if (IS_ERR(item.cgroup_storage[stype])) {
item.cgroup_storage[stype] = NULL;
for_each_cgroup_storage_type(stype)
bpf_cgroup_storage_free(item.cgroup_storage[stype]);
return -ENOMEM;
}
}
if (!repeat)
repeat = 1;
bpf_test_timer_enter(&t);
old_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
do {
run_ctx.prog_item = &item;
local_bh_disable();
if (xdp)
*retval = bpf_prog_run_xdp(prog, ctx);
else
*retval = bpf_prog_run(prog, ctx);
local_bh_enable();
} while (bpf_test_timer_continue(&t, 1, repeat, &ret, time));
bpf_reset_run_ctx(old_ctx);
bpf_test_timer_leave(&t);
for_each_cgroup_storage_type(stype)
bpf_cgroup_storage_free(item.cgroup_storage[stype]);
return ret;
}
static int bpf_test_finish(const union bpf_attr *kattr,
union bpf_attr __user *uattr, const void *data,
struct skb_shared_info *sinfo, u32 size,
u32 retval, u32 duration)
{
void __user *data_out = u64_to_user_ptr(kattr->test.data_out);
int err = -EFAULT;
u32 copy_size = size;
/* Clamp copy if the user has provided a size hint, but copy the full
* buffer if not to retain old behaviour.
*/
if (kattr->test.data_size_out &&
copy_size > kattr->test.data_size_out) {
copy_size = kattr->test.data_size_out;
err = -ENOSPC;
}
if (data_out) {
int len = sinfo ? copy_size - sinfo->xdp_frags_size : copy_size;
if (len < 0) {
err = -ENOSPC;
goto out;
}
if (copy_to_user(data_out, data, len))
goto out;
if (sinfo) {
int i, offset = len;
u32 data_len;
for (i = 0; i < sinfo->nr_frags; i++) {
skb_frag_t *frag = &sinfo->frags[i];
if (offset >= copy_size) {
err = -ENOSPC;
break;
}
data_len = min_t(u32, copy_size - offset,
skb_frag_size(frag));
if (copy_to_user(data_out + offset,
skb_frag_address(frag),
data_len))
goto out;
offset += data_len;
}
}
}
if (copy_to_user(&uattr->test.data_size_out, &size, sizeof(size)))
goto out;
if (copy_to_user(&uattr->test.retval, &retval, sizeof(retval)))
goto out;
if (copy_to_user(&uattr->test.duration, &duration, sizeof(duration)))
goto out;
if (err != -ENOSPC)
err = 0;
out:
trace_bpf_test_finish(&err);
return err;
}
/* Integer types of various sizes and pointer combinations cover variety of
* architecture dependent calling conventions. 7+ can be supported in the
* future.
*/
__diag_push();
__diag_ignore_all("-Wmissing-prototypes",
"Global functions as their definitions will be in vmlinux BTF");
__bpf_kfunc int bpf_fentry_test1(int a)
{
return a + 1;
}
EXPORT_SYMBOL_GPL(bpf_fentry_test1);
int noinline bpf_fentry_test2(int a, u64 b)
{
return a + b;
}
int noinline bpf_fentry_test3(char a, int b, u64 c)
{
return a + b + c;
}
int noinline bpf_fentry_test4(void *a, char b, int c, u64 d)
{
return (long)a + b + c + d;
}
int noinline bpf_fentry_test5(u64 a, void *b, short c, int d, u64 e)
{
return a + (long)b + c + d + e;
}
int noinline bpf_fentry_test6(u64 a, void *b, short c, int d, void *e, u64 f)
{
return a + (long)b + c + d + (long)e + f;
}
struct bpf_fentry_test_t {
struct bpf_fentry_test_t *a;
};
int noinline bpf_fentry_test7(struct bpf_fentry_test_t *arg)
{
asm volatile ("");
return (long)arg;
}
int noinline bpf_fentry_test8(struct bpf_fentry_test_t *arg)
{
return (long)arg->a;
}
__bpf_kfunc u32 bpf_fentry_test9(u32 *a)
{
return *a;
}
void noinline bpf_fentry_test_sinfo(struct skb_shared_info *sinfo)
{
}
__bpf_kfunc int bpf_modify_return_test(int a, int *b)
{
*b += 1;
return a + *b;
}
__bpf_kfunc int bpf_modify_return_test2(int a, int *b, short c, int d,
void *e, char f, int g)
{
*b += 1;
return a + *b + c + d + (long)e + f + g;
}
int noinline bpf_fentry_shadow_test(int a)
{
return a + 1;
}
struct prog_test_member1 {
int a;
};
struct prog_test_member {
struct prog_test_member1 m;
int c;
};
struct prog_test_ref_kfunc {
int a;
int b;
struct prog_test_member memb;
struct prog_test_ref_kfunc *next;
refcount_t cnt;
};
__bpf_kfunc void bpf_kfunc_call_test_release(struct prog_test_ref_kfunc *p)
{
refcount_dec(&p->cnt);
}
__bpf_kfunc void bpf_kfunc_call_memb_release(struct prog_test_member *p)
{
}
__diag_pop();
BTF_SET8_START(bpf_test_modify_return_ids)
BTF_ID_FLAGS(func, bpf_modify_return_test)
BTF_ID_FLAGS(func, bpf_modify_return_test2)
BTF_ID_FLAGS(func, bpf_fentry_test1, KF_SLEEPABLE)
BTF_SET8_END(bpf_test_modify_return_ids)
static const struct btf_kfunc_id_set bpf_test_modify_return_set = {
.owner = THIS_MODULE,
.set = &bpf_test_modify_return_ids,
};
BTF_SET8_START(test_sk_check_kfunc_ids)
BTF_ID_FLAGS(func, bpf_kfunc_call_test_release, KF_RELEASE)
BTF_ID_FLAGS(func, bpf_kfunc_call_memb_release, KF_RELEASE)
BTF_SET8_END(test_sk_check_kfunc_ids)
static void *bpf_test_init(const union bpf_attr *kattr, u32 user_size,
u32 size, u32 headroom, u32 tailroom)
{
void __user *data_in = u64_to_user_ptr(kattr->test.data_in);
void *data;
if (size < ETH_HLEN || size > PAGE_SIZE - headroom - tailroom)
return ERR_PTR(-EINVAL);
if (user_size > size)
return ERR_PTR(-EMSGSIZE);
size = SKB_DATA_ALIGN(size);
data = kzalloc(size + headroom + tailroom, GFP_USER);
if (!data)
return ERR_PTR(-ENOMEM);
if (copy_from_user(data + headroom, data_in, user_size)) {
kfree(data);
return ERR_PTR(-EFAULT);
}
return data;
}
int bpf_prog_test_run_tracing(struct bpf_prog *prog,
const union bpf_attr *kattr,
union bpf_attr __user *uattr)
{
struct bpf_fentry_test_t arg = {};
u16 side_effect = 0, ret = 0;
int b = 2, err = -EFAULT;
u32 retval = 0;
if (kattr->test.flags || kattr->test.cpu || kattr->test.batch_size)
return -EINVAL;
switch (prog->expected_attach_type) {
case BPF_TRACE_FENTRY:
case BPF_TRACE_FEXIT:
if (bpf_fentry_test1(1) != 2 ||
bpf_fentry_test2(2, 3) != 5 ||
bpf_fentry_test3(4, 5, 6) != 15 ||
bpf_fentry_test4((void *)7, 8, 9, 10) != 34 ||
bpf_fentry_test5(11, (void *)12, 13, 14, 15) != 65 ||
bpf_fentry_test6(16, (void *)17, 18, 19, (void *)20, 21) != 111 ||
bpf_fentry_test7((struct bpf_fentry_test_t *)0) != 0 ||
bpf_fentry_test8(&arg) != 0 ||
bpf_fentry_test9(&retval) != 0)
goto out;
break;
case BPF_MODIFY_RETURN:
ret = bpf_modify_return_test(1, &b);
if (b != 2)
side_effect++;
b = 2;
ret += bpf_modify_return_test2(1, &b, 3, 4, (void *)5, 6, 7);
if (b != 2)
side_effect++;
break;
default:
goto out;
}
retval = ((u32)side_effect << 16) | ret;
if (copy_to_user(&uattr->test.retval, &retval, sizeof(retval)))
goto out;
err = 0;
out:
trace_bpf_test_finish(&err);
return err;
}
struct bpf_raw_tp_test_run_info {
struct bpf_prog *prog;
void *ctx;
u32 retval;
};
static void
__bpf_prog_test_run_raw_tp(void *data)
{
struct bpf_raw_tp_test_run_info *info = data;
rcu_read_lock();
info->retval = bpf_prog_run(info->prog, info->ctx);
rcu_read_unlock();
}
int bpf_prog_test_run_raw_tp(struct bpf_prog *prog,
const union bpf_attr *kattr,
union bpf_attr __user *uattr)
{
void __user *ctx_in = u64_to_user_ptr(kattr->test.ctx_in);
__u32 ctx_size_in = kattr->test.ctx_size_in;
struct bpf_raw_tp_test_run_info info;
int cpu = kattr->test.cpu, err = 0;
int current_cpu;
/* doesn't support data_in/out, ctx_out, duration, or repeat */
if (kattr->test.data_in || kattr->test.data_out ||
kattr->test.ctx_out || kattr->test.duration ||
kattr->test.repeat || kattr->test.batch_size)
return -EINVAL;
if (ctx_size_in < prog->aux->max_ctx_offset ||
ctx_size_in > MAX_BPF_FUNC_ARGS * sizeof(u64))
return -EINVAL;
if ((kattr->test.flags & BPF_F_TEST_RUN_ON_CPU) == 0 && cpu != 0)
return -EINVAL;
if (ctx_size_in) {
info.ctx = memdup_user(ctx_in, ctx_size_in);
if (IS_ERR(info.ctx))
return PTR_ERR(info.ctx);
} else {
info.ctx = NULL;
}
info.prog = prog;
current_cpu = get_cpu();
if ((kattr->test.flags & BPF_F_TEST_RUN_ON_CPU) == 0 ||
cpu == current_cpu) {
__bpf_prog_test_run_raw_tp(&info);
} else if (cpu >= nr_cpu_ids || !cpu_online(cpu)) {
/* smp_call_function_single() also checks cpu_online()
* after csd_lock(). However, since cpu is from user
* space, let's do an extra quick check to filter out
* invalid value before smp_call_function_single().
*/
err = -ENXIO;
} else {
err = smp_call_function_single(cpu, __bpf_prog_test_run_raw_tp,
&info, 1);
}
put_cpu();
if (!err &&
copy_to_user(&uattr->test.retval, &info.retval, sizeof(u32)))
err = -EFAULT;
kfree(info.ctx);
return err;
}
static void *bpf_ctx_init(const union bpf_attr *kattr, u32 max_size)
{
void __user *data_in = u64_to_user_ptr(kattr->test.ctx_in);
void __user *data_out = u64_to_user_ptr(kattr->test.ctx_out);
u32 size = kattr->test.ctx_size_in;
void *data;
int err;
if (!data_in && !data_out)
return NULL;
data = kzalloc(max_size, GFP_USER);
if (!data)
return ERR_PTR(-ENOMEM);
if (data_in) {
err = bpf_check_uarg_tail_zero(USER_BPFPTR(data_in), max_size, size);
if (err) {
kfree(data);
return ERR_PTR(err);
}
size = min_t(u32, max_size, size);
if (copy_from_user(data, data_in, size)) {
kfree(data);
return ERR_PTR(-EFAULT);
}
}
return data;
}
static int bpf_ctx_finish(const union bpf_attr *kattr,
union bpf_attr __user *uattr, const void *data,
u32 size)
{
void __user *data_out = u64_to_user_ptr(kattr->test.ctx_out);
int err = -EFAULT;
u32 copy_size = size;
if (!data || !data_out)
return 0;
if (copy_size > kattr->test.ctx_size_out) {
copy_size = kattr->test.ctx_size_out;
err = -ENOSPC;
}
if (copy_to_user(data_out, data, copy_size))
goto out;
if (copy_to_user(&uattr->test.ctx_size_out, &size, sizeof(size)))
goto out;
if (err != -ENOSPC)
err = 0;
out:
return err;
}
/**
* range_is_zero - test whether buffer is initialized
* @buf: buffer to check
* @from: check from this position
* @to: check up until (excluding) this position
*
* This function returns true if the there is a non-zero byte
* in the buf in the range [from,to).
*/
static inline bool range_is_zero(void *buf, size_t from, size_t to)
{
return !memchr_inv((u8 *)buf + from, 0, to - from);
}
static int convert___skb_to_skb(struct sk_buff *skb, struct __sk_buff *__skb)
{
struct qdisc_skb_cb *cb = (struct qdisc_skb_cb *)skb->cb;
if (!__skb)
return 0;
/* make sure the fields we don't use are zeroed */
if (!range_is_zero(__skb, 0, offsetof(struct __sk_buff, mark)))
return -EINVAL;
/* mark is allowed */
if (!range_is_zero(__skb, offsetofend(struct __sk_buff, mark),
offsetof(struct __sk_buff, priority)))
return -EINVAL;
/* priority is allowed */
/* ingress_ifindex is allowed */
/* ifindex is allowed */
if (!range_is_zero(__skb, offsetofend(struct __sk_buff, ifindex),
offsetof(struct __sk_buff, cb)))
return -EINVAL;
/* cb is allowed */
if (!range_is_zero(__skb, offsetofend(struct __sk_buff, cb),
offsetof(struct __sk_buff, tstamp)))
return -EINVAL;
/* tstamp is allowed */
/* wire_len is allowed */
/* gso_segs is allowed */
if (!range_is_zero(__skb, offsetofend(struct __sk_buff, gso_segs),
offsetof(struct __sk_buff, gso_size)))
return -EINVAL;
/* gso_size is allowed */
if (!range_is_zero(__skb, offsetofend(struct __sk_buff, gso_size),
offsetof(struct __sk_buff, hwtstamp)))
return -EINVAL;
/* hwtstamp is allowed */
if (!range_is_zero(__skb, offsetofend(struct __sk_buff, hwtstamp),
sizeof(struct __sk_buff)))
return -EINVAL;
skb->mark = __skb->mark;
skb->priority = __skb->priority;
skb->skb_iif = __skb->ingress_ifindex;
skb->tstamp = __skb->tstamp;
memcpy(&cb->data, __skb->cb, QDISC_CB_PRIV_LEN);
if (__skb->wire_len == 0) {
cb->pkt_len = skb->len;
} else {
if (__skb->wire_len < skb->len ||
__skb->wire_len > GSO_LEGACY_MAX_SIZE)
return -EINVAL;
cb->pkt_len = __skb->wire_len;
}
if (__skb->gso_segs > GSO_MAX_SEGS)
return -EINVAL;
skb_shinfo(skb)->gso_segs = __skb->gso_segs;
skb_shinfo(skb)->gso_size = __skb->gso_size;
skb_shinfo(skb)->hwtstamps.hwtstamp = __skb->hwtstamp;
return 0;
}
static void convert_skb_to___skb(struct sk_buff *skb, struct __sk_buff *__skb)
{
struct qdisc_skb_cb *cb = (struct qdisc_skb_cb *)skb->cb;
if (!__skb)
return;
__skb->mark = skb->mark;
__skb->priority = skb->priority;
__skb->ingress_ifindex = skb->skb_iif;
__skb->ifindex = skb->dev->ifindex;
__skb->tstamp = skb->tstamp;
memcpy(__skb->cb, &cb->data, QDISC_CB_PRIV_LEN);
__skb->wire_len = cb->pkt_len;
__skb->gso_segs = skb_shinfo(skb)->gso_segs;
__skb->hwtstamp = skb_shinfo(skb)->hwtstamps.hwtstamp;
}
static struct proto bpf_dummy_proto = {
.name = "bpf_dummy",
.owner = THIS_MODULE,
.obj_size = sizeof(struct sock),
};
int bpf_prog_test_run_skb(struct bpf_prog *prog, const union bpf_attr *kattr,
union bpf_attr __user *uattr)
{
bool is_l2 = false, is_direct_pkt_access = false;
struct net *net = current->nsproxy->net_ns;
struct net_device *dev = net->loopback_dev;
u32 size = kattr->test.data_size_in;
u32 repeat = kattr->test.repeat;
struct __sk_buff *ctx = NULL;
u32 retval, duration;
int hh_len = ETH_HLEN;
struct sk_buff *skb;
struct sock *sk;
void *data;
int ret;
if (kattr->test.flags || kattr->test.cpu || kattr->test.batch_size)
return -EINVAL;
data = bpf_test_init(kattr, kattr->test.data_size_in,
size, NET_SKB_PAD + NET_IP_ALIGN,
SKB_DATA_ALIGN(sizeof(struct skb_shared_info)));
if (IS_ERR(data))
return PTR_ERR(data);
ctx = bpf_ctx_init(kattr, sizeof(struct __sk_buff));
if (IS_ERR(ctx)) {
kfree(data);
return PTR_ERR(ctx);
}
switch (prog->type) {
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
is_l2 = true;
fallthrough;
case BPF_PROG_TYPE_LWT_IN:
case BPF_PROG_TYPE_LWT_OUT:
case BPF_PROG_TYPE_LWT_XMIT:
is_direct_pkt_access = true;
break;
default:
break;
}
sk = sk_alloc(net, AF_UNSPEC, GFP_USER, &bpf_dummy_proto, 1);
if (!sk) {
kfree(data);
kfree(ctx);
return -ENOMEM;
}
sock_init_data(NULL, sk);
skb = slab_build_skb(data);
if (!skb) {
kfree(data);
kfree(ctx);
sk_free(sk);
return -ENOMEM;
}
skb->sk = sk;
skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
__skb_put(skb, size);
if (ctx && ctx->ifindex > 1) {
dev = dev_get_by_index(net, ctx->ifindex);
if (!dev) {
ret = -ENODEV;
goto out;
}
}
skb->protocol = eth_type_trans(skb, dev);
skb_reset_network_header(skb);
switch (skb->protocol) {
case htons(ETH_P_IP):
sk->sk_family = AF_INET;
if (sizeof(struct iphdr) <= skb_headlen(skb)) {
sk->sk_rcv_saddr = ip_hdr(skb)->saddr;
sk->sk_daddr = ip_hdr(skb)->daddr;
}
break;
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
sk->sk_family = AF_INET6;
if (sizeof(struct ipv6hdr) <= skb_headlen(skb)) {
sk->sk_v6_rcv_saddr = ipv6_hdr(skb)->saddr;
sk->sk_v6_daddr = ipv6_hdr(skb)->daddr;
}
break;
#endif
default:
break;
}
if (is_l2)
__skb_push(skb, hh_len);
if (is_direct_pkt_access)
bpf_compute_data_pointers(skb);
ret = convert___skb_to_skb(skb, ctx);
if (ret)
goto out;
ret = bpf_test_run(prog, skb, repeat, &retval, &duration, false);
if (ret)
goto out;
if (!is_l2) {
if (skb_headroom(skb) < hh_len) {
int nhead = HH_DATA_ALIGN(hh_len - skb_headroom(skb));
if (pskb_expand_head(skb, nhead, 0, GFP_USER)) {
ret = -ENOMEM;
goto out;
}
}
memset(__skb_push(skb, hh_len), 0, hh_len);
}
convert_skb_to___skb(skb, ctx);
size = skb->len;
/* bpf program can never convert linear skb to non-linear */
if (WARN_ON_ONCE(skb_is_nonlinear(skb)))
size = skb_headlen(skb);
ret = bpf_test_finish(kattr, uattr, skb->data, NULL, size, retval,
duration);
if (!ret)
ret = bpf_ctx_finish(kattr, uattr, ctx,
sizeof(struct __sk_buff));
out:
if (dev && dev != net->loopback_dev)
dev_put(dev);
kfree_skb(skb);
sk_free(sk);
kfree(ctx);
return ret;
}
static int xdp_convert_md_to_buff(struct xdp_md *xdp_md, struct xdp_buff *xdp)
{
unsigned int ingress_ifindex, rx_queue_index;
struct netdev_rx_queue *rxqueue;
struct net_device *device;
if (!xdp_md)
return 0;
if (xdp_md->egress_ifindex != 0)
return -EINVAL;
ingress_ifindex = xdp_md->ingress_ifindex;
rx_queue_index = xdp_md->rx_queue_index;
if (!ingress_ifindex && rx_queue_index)
return -EINVAL;
if (ingress_ifindex) {
device = dev_get_by_index(current->nsproxy->net_ns,
ingress_ifindex);
if (!device)
return -ENODEV;
if (rx_queue_index >= device->real_num_rx_queues)
goto free_dev;
rxqueue = __netif_get_rx_queue(device, rx_queue_index);
if (!xdp_rxq_info_is_reg(&rxqueue->xdp_rxq))
goto free_dev;
xdp->rxq = &rxqueue->xdp_rxq;
/* The device is now tracked in the xdp->rxq for later
* dev_put()
*/
}
xdp->data = xdp->data_meta + xdp_md->data;
return 0;
free_dev:
dev_put(device);
return -EINVAL;
}
static void xdp_convert_buff_to_md(struct xdp_buff *xdp, struct xdp_md *xdp_md)
{
if (!xdp_md)
return;
xdp_md->data = xdp->data - xdp->data_meta;
xdp_md->data_end = xdp->data_end - xdp->data_meta;
if (xdp_md->ingress_ifindex)
dev_put(xdp->rxq->dev);
}
int bpf_prog_test_run_xdp(struct bpf_prog *prog, const union bpf_attr *kattr,
union bpf_attr __user *uattr)
{
bool do_live = (kattr->test.flags & BPF_F_TEST_XDP_LIVE_FRAMES);
u32 tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
u32 batch_size = kattr->test.batch_size;
u32 retval = 0, duration, max_data_sz;
u32 size = kattr->test.data_size_in;
u32 headroom = XDP_PACKET_HEADROOM;
u32 repeat = kattr->test.repeat;
struct netdev_rx_queue *rxqueue;
struct skb_shared_info *sinfo;
struct xdp_buff xdp = {};
int i, ret = -EINVAL;
struct xdp_md *ctx;
void *data;
if (prog->expected_attach_type == BPF_XDP_DEVMAP ||
prog->expected_attach_type == BPF_XDP_CPUMAP)
return -EINVAL;
if (kattr->test.flags & ~BPF_F_TEST_XDP_LIVE_FRAMES)
return -EINVAL;
if (bpf_prog_is_dev_bound(prog->aux))
return -EINVAL;
if (do_live) {
if (!batch_size)
batch_size = NAPI_POLL_WEIGHT;
else if (batch_size > TEST_XDP_MAX_BATCH)
return -E2BIG;
headroom += sizeof(struct xdp_page_head);
} else if (batch_size) {
return -EINVAL;
}
ctx = bpf_ctx_init(kattr, sizeof(struct xdp_md));
if (IS_ERR(ctx))
return PTR_ERR(ctx);
if (ctx) {
/* There can't be user provided data before the meta data */
if (ctx->data_meta || ctx->data_end != size ||
ctx->data > ctx->data_end ||
unlikely(xdp_metalen_invalid(ctx->data)) ||
(do_live && (kattr->test.data_out || kattr->test.ctx_out)))
goto free_ctx;
/* Meta data is allocated from the headroom */
headroom -= ctx->data;
}
max_data_sz = 4096 - headroom - tailroom;
if (size > max_data_sz) {
/* disallow live data mode for jumbo frames */
if (do_live)
goto free_ctx;
size = max_data_sz;
}
data = bpf_test_init(kattr, size, max_data_sz, headroom, tailroom);
if (IS_ERR(data)) {
ret = PTR_ERR(data);
goto free_ctx;
}
rxqueue = __netif_get_rx_queue(current->nsproxy->net_ns->loopback_dev, 0);
rxqueue->xdp_rxq.frag_size = headroom + max_data_sz + tailroom;
xdp_init_buff(&xdp, rxqueue->xdp_rxq.frag_size, &rxqueue->xdp_rxq);
xdp_prepare_buff(&xdp, data, headroom, size, true);
sinfo = xdp_get_shared_info_from_buff(&xdp);
ret = xdp_convert_md_to_buff(ctx, &xdp);
if (ret)
goto free_data;
if (unlikely(kattr->test.data_size_in > size)) {
void __user *data_in = u64_to_user_ptr(kattr->test.data_in);
while (size < kattr->test.data_size_in) {
struct page *page;
skb_frag_t *frag;
u32 data_len;
if (sinfo->nr_frags == MAX_SKB_FRAGS) {
ret = -ENOMEM;
goto out;
}
page = alloc_page(GFP_KERNEL);
if (!page) {
ret = -ENOMEM;
goto out;
}
frag = &sinfo->frags[sinfo->nr_frags++];
data_len = min_t(u32, kattr->test.data_size_in - size,
PAGE_SIZE);
skb_frag_fill_page_desc(frag, page, 0, data_len);
if (copy_from_user(page_address(page), data_in + size,
data_len)) {
ret = -EFAULT;
goto out;
}
sinfo->xdp_frags_size += data_len;
size += data_len;
}
xdp_buff_set_frags_flag(&xdp);
}
if (repeat > 1)
bpf_prog_change_xdp(NULL, prog);
if (do_live)
ret = bpf_test_run_xdp_live(prog, &xdp, repeat, batch_size, &duration);
else
ret = bpf_test_run(prog, &xdp, repeat, &retval, &duration, true);
/* We convert the xdp_buff back to an xdp_md before checking the return
* code so the reference count of any held netdevice will be decremented
* even if the test run failed.
*/
xdp_convert_buff_to_md(&xdp, ctx);
if (ret)
goto out;
size = xdp.data_end - xdp.data_meta + sinfo->xdp_frags_size;
ret = bpf_test_finish(kattr, uattr, xdp.data_meta, sinfo, size,
retval, duration);
if (!ret)
ret = bpf_ctx_finish(kattr, uattr, ctx,
sizeof(struct xdp_md));
out:
if (repeat > 1)
bpf_prog_change_xdp(prog, NULL);
free_data:
for (i = 0; i < sinfo->nr_frags; i++)
__free_page(skb_frag_page(&sinfo->frags[i]));
kfree(data);
free_ctx:
kfree(ctx);
return ret;
}
static int verify_user_bpf_flow_keys(struct bpf_flow_keys *ctx)
{
/* make sure the fields we don't use are zeroed */
if (!range_is_zero(ctx, 0, offsetof(struct bpf_flow_keys, flags)))
return -EINVAL;
/* flags is allowed */
if (!range_is_zero(ctx, offsetofend(struct bpf_flow_keys, flags),
sizeof(struct bpf_flow_keys)))
return -EINVAL;
return 0;
}
int bpf_prog_test_run_flow_dissector(struct bpf_prog *prog,
const union bpf_attr *kattr,
union bpf_attr __user *uattr)
{
struct bpf_test_timer t = { NO_PREEMPT };
u32 size = kattr->test.data_size_in;
struct bpf_flow_dissector ctx = {};
u32 repeat = kattr->test.repeat;
struct bpf_flow_keys *user_ctx;
struct bpf_flow_keys flow_keys;
const struct ethhdr *eth;
unsigned int flags = 0;
u32 retval, duration;
void *data;
int ret;
if (kattr->test.flags || kattr->test.cpu || kattr->test.batch_size)
return -EINVAL;
if (size < ETH_HLEN)
return -EINVAL;
data = bpf_test_init(kattr, kattr->test.data_size_in, size, 0, 0);
if (IS_ERR(data))
return PTR_ERR(data);
eth = (struct ethhdr *)data;
if (!repeat)
repeat = 1;
user_ctx = bpf_ctx_init(kattr, sizeof(struct bpf_flow_keys));
if (IS_ERR(user_ctx)) {
kfree(data);
return PTR_ERR(user_ctx);
}
if (user_ctx) {
ret = verify_user_bpf_flow_keys(user_ctx);
if (ret)
goto out;
flags = user_ctx->flags;
}
ctx.flow_keys = &flow_keys;
ctx.data = data;
ctx.data_end = (__u8 *)data + size;
bpf_test_timer_enter(&t);
do {
retval = bpf_flow_dissect(prog, &ctx, eth->h_proto, ETH_HLEN,
size, flags);
} while (bpf_test_timer_continue(&t, 1, repeat, &ret, &duration));
bpf_test_timer_leave(&t);
if (ret < 0)
goto out;
ret = bpf_test_finish(kattr, uattr, &flow_keys, NULL,
sizeof(flow_keys), retval, duration);
if (!ret)
ret = bpf_ctx_finish(kattr, uattr, user_ctx,
sizeof(struct bpf_flow_keys));
out:
kfree(user_ctx);
kfree(data);
return ret;
}
int bpf_prog_test_run_sk_lookup(struct bpf_prog *prog, const union bpf_attr *kattr,
union bpf_attr __user *uattr)
{
struct bpf_test_timer t = { NO_PREEMPT };
struct bpf_prog_array *progs = NULL;
struct bpf_sk_lookup_kern ctx = {};
u32 repeat = kattr->test.repeat;
struct bpf_sk_lookup *user_ctx;
u32 retval, duration;
int ret = -EINVAL;
if (kattr->test.flags || kattr->test.cpu || kattr->test.batch_size)
return -EINVAL;
if (kattr->test.data_in || kattr->test.data_size_in || kattr->test.data_out ||
kattr->test.data_size_out)
return -EINVAL;
if (!repeat)
repeat = 1;
user_ctx = bpf_ctx_init(kattr, sizeof(*user_ctx));
if (IS_ERR(user_ctx))
return PTR_ERR(user_ctx);
if (!user_ctx)
return -EINVAL;
if (user_ctx->sk)
goto out;
if (!range_is_zero(user_ctx, offsetofend(typeof(*user_ctx), local_port), sizeof(*user_ctx)))
goto out;
if (user_ctx->local_port > U16_MAX) {
ret = -ERANGE;
goto out;
}
ctx.family = (u16)user_ctx->family;
ctx.protocol = (u16)user_ctx->protocol;
ctx.dport = (u16)user_ctx->local_port;
ctx.sport = user_ctx->remote_port;
switch (ctx.family) {
case AF_INET:
ctx.v4.daddr = (__force __be32)user_ctx->local_ip4;
ctx.v4.saddr = (__force __be32)user_ctx->remote_ip4;
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
ctx.v6.daddr = (struct in6_addr *)user_ctx->local_ip6;
ctx.v6.saddr = (struct in6_addr *)user_ctx->remote_ip6;
break;
#endif
default:
ret = -EAFNOSUPPORT;
goto out;
}
progs = bpf_prog_array_alloc(1, GFP_KERNEL);
if (!progs) {
ret = -ENOMEM;
goto out;
}
progs->items[0].prog = prog;
bpf_test_timer_enter(&t);
do {
ctx.selected_sk = NULL;
retval = BPF_PROG_SK_LOOKUP_RUN_ARRAY(progs, ctx, bpf_prog_run);
} while (bpf_test_timer_continue(&t, 1, repeat, &ret, &duration));
bpf_test_timer_leave(&t);
if (ret < 0)
goto out;
user_ctx->cookie = 0;
if (ctx.selected_sk) {
if (ctx.selected_sk->sk_reuseport && !ctx.no_reuseport) {
ret = -EOPNOTSUPP;
goto out;
}
user_ctx->cookie = sock_gen_cookie(ctx.selected_sk);
}
ret = bpf_test_finish(kattr, uattr, NULL, NULL, 0, retval, duration);
if (!ret)
ret = bpf_ctx_finish(kattr, uattr, user_ctx, sizeof(*user_ctx));
out:
bpf_prog_array_free(progs);
kfree(user_ctx);
return ret;
}
int bpf_prog_test_run_syscall(struct bpf_prog *prog,
const union bpf_attr *kattr,
union bpf_attr __user *uattr)
{
void __user *ctx_in = u64_to_user_ptr(kattr->test.ctx_in);
__u32 ctx_size_in = kattr->test.ctx_size_in;
void *ctx = NULL;
u32 retval;
int err = 0;
/* doesn't support data_in/out, ctx_out, duration, or repeat or flags */
if (kattr->test.data_in || kattr->test.data_out ||
kattr->test.ctx_out || kattr->test.duration ||
kattr->test.repeat || kattr->test.flags ||
kattr->test.batch_size)
return -EINVAL;
if (ctx_size_in < prog->aux->max_ctx_offset ||
ctx_size_in > U16_MAX)
return -EINVAL;
if (ctx_size_in) {
ctx = memdup_user(ctx_in, ctx_size_in);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
}
rcu_read_lock_trace();
retval = bpf_prog_run_pin_on_cpu(prog, ctx);
rcu_read_unlock_trace();
if (copy_to_user(&uattr->test.retval, &retval, sizeof(u32))) {
err = -EFAULT;
goto out;
}
if (ctx_size_in)
if (copy_to_user(ctx_in, ctx, ctx_size_in))
err = -EFAULT;
out:
kfree(ctx);
return err;
}
static int verify_and_copy_hook_state(struct nf_hook_state *state,
const struct nf_hook_state *user,
struct net_device *dev)
{
if (user->in || user->out)
return -EINVAL;
if (user->net || user->sk || user->okfn)
return -EINVAL;
switch (user->pf) {
case NFPROTO_IPV4:
case NFPROTO_IPV6:
switch (state->hook) {
case NF_INET_PRE_ROUTING:
state->in = dev;
break;
case NF_INET_LOCAL_IN:
state->in = dev;
break;
case NF_INET_FORWARD:
state->in = dev;
state->out = dev;
break;
case NF_INET_LOCAL_OUT:
state->out = dev;
break;
case NF_INET_POST_ROUTING:
state->out = dev;
break;
}
break;
default:
return -EINVAL;
}
state->pf = user->pf;
state->hook = user->hook;
return 0;
}
static __be16 nfproto_eth(int nfproto)
{
switch (nfproto) {
case NFPROTO_IPV4:
return htons(ETH_P_IP);
case NFPROTO_IPV6:
break;
}
return htons(ETH_P_IPV6);
}
int bpf_prog_test_run_nf(struct bpf_prog *prog,
const union bpf_attr *kattr,
union bpf_attr __user *uattr)
{
struct net *net = current->nsproxy->net_ns;
struct net_device *dev = net->loopback_dev;
struct nf_hook_state *user_ctx, hook_state = {
.pf = NFPROTO_IPV4,
.hook = NF_INET_LOCAL_OUT,
};
u32 size = kattr->test.data_size_in;
u32 repeat = kattr->test.repeat;
struct bpf_nf_ctx ctx = {
.state = &hook_state,
};
struct sk_buff *skb = NULL;
u32 retval, duration;
void *data;
int ret;
if (kattr->test.flags || kattr->test.cpu || kattr->test.batch_size)
return -EINVAL;
if (size < sizeof(struct iphdr))
return -EINVAL;
data = bpf_test_init(kattr, kattr->test.data_size_in, size,
NET_SKB_PAD + NET_IP_ALIGN,
SKB_DATA_ALIGN(sizeof(struct skb_shared_info)));
if (IS_ERR(data))
return PTR_ERR(data);
if (!repeat)
repeat = 1;
user_ctx = bpf_ctx_init(kattr, sizeof(struct nf_hook_state));
if (IS_ERR(user_ctx)) {
kfree(data);
return PTR_ERR(user_ctx);
}
if (user_ctx) {
ret = verify_and_copy_hook_state(&hook_state, user_ctx, dev);
if (ret)
goto out;
}
skb = slab_build_skb(data);
if (!skb) {
ret = -ENOMEM;
goto out;
}
data = NULL; /* data released via kfree_skb */
skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
__skb_put(skb, size);
ret = -EINVAL;
if (hook_state.hook != NF_INET_LOCAL_OUT) {
if (size < ETH_HLEN + sizeof(struct iphdr))
goto out;
skb->protocol = eth_type_trans(skb, dev);
switch (skb->protocol) {
case htons(ETH_P_IP):
if (hook_state.pf == NFPROTO_IPV4)
break;
goto out;
case htons(ETH_P_IPV6):
if (size < ETH_HLEN + sizeof(struct ipv6hdr))
goto out;
if (hook_state.pf == NFPROTO_IPV6)
break;
goto out;
default:
ret = -EPROTO;
goto out;
}
skb_reset_network_header(skb);
} else {
skb->protocol = nfproto_eth(hook_state.pf);
}
ctx.skb = skb;
ret = bpf_test_run(prog, &ctx, repeat, &retval, &duration, false);
if (ret)
goto out;
ret = bpf_test_finish(kattr, uattr, NULL, NULL, 0, retval, duration);
out:
kfree(user_ctx);
kfree_skb(skb);
kfree(data);
return ret;
}
static const struct btf_kfunc_id_set bpf_prog_test_kfunc_set = {
.owner = THIS_MODULE,
.set = &test_sk_check_kfunc_ids,
};
BTF_ID_LIST(bpf_prog_test_dtor_kfunc_ids)
BTF_ID(struct, prog_test_ref_kfunc)
BTF_ID(func, bpf_kfunc_call_test_release)
BTF_ID(struct, prog_test_member)
BTF_ID(func, bpf_kfunc_call_memb_release)
static int __init bpf_prog_test_run_init(void)
{
const struct btf_id_dtor_kfunc bpf_prog_test_dtor_kfunc[] = {
{
.btf_id = bpf_prog_test_dtor_kfunc_ids[0],
.kfunc_btf_id = bpf_prog_test_dtor_kfunc_ids[1]
},
{
.btf_id = bpf_prog_test_dtor_kfunc_ids[2],
.kfunc_btf_id = bpf_prog_test_dtor_kfunc_ids[3],
},
};
int ret;
ret = register_btf_fmodret_id_set(&bpf_test_modify_return_set);
ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &bpf_prog_test_kfunc_set);
ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_prog_test_kfunc_set);
ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &bpf_prog_test_kfunc_set);
return ret ?: register_btf_id_dtor_kfuncs(bpf_prog_test_dtor_kfunc,
ARRAY_SIZE(bpf_prog_test_dtor_kfunc),
THIS_MODULE);
}
late_initcall(bpf_prog_test_run_init);
| linux-master | net/bpf/test_run.c |
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (C) 2021. Huawei Technologies Co., Ltd
*/
#include <linux/kernel.h>
#include <linux/bpf_verifier.h>
#include <linux/bpf.h>
#include <linux/btf.h>
extern struct bpf_struct_ops bpf_bpf_dummy_ops;
/* A common type for test_N with return value in bpf_dummy_ops */
typedef int (*dummy_ops_test_ret_fn)(struct bpf_dummy_ops_state *state, ...);
struct bpf_dummy_ops_test_args {
u64 args[MAX_BPF_FUNC_ARGS];
struct bpf_dummy_ops_state state;
};
static struct bpf_dummy_ops_test_args *
dummy_ops_init_args(const union bpf_attr *kattr, unsigned int nr)
{
__u32 size_in;
struct bpf_dummy_ops_test_args *args;
void __user *ctx_in;
void __user *u_state;
size_in = kattr->test.ctx_size_in;
if (size_in != sizeof(u64) * nr)
return ERR_PTR(-EINVAL);
args = kzalloc(sizeof(*args), GFP_KERNEL);
if (!args)
return ERR_PTR(-ENOMEM);
ctx_in = u64_to_user_ptr(kattr->test.ctx_in);
if (copy_from_user(args->args, ctx_in, size_in))
goto out;
/* args[0] is 0 means state argument of test_N will be NULL */
u_state = u64_to_user_ptr(args->args[0]);
if (u_state && copy_from_user(&args->state, u_state,
sizeof(args->state)))
goto out;
return args;
out:
kfree(args);
return ERR_PTR(-EFAULT);
}
static int dummy_ops_copy_args(struct bpf_dummy_ops_test_args *args)
{
void __user *u_state;
u_state = u64_to_user_ptr(args->args[0]);
if (u_state && copy_to_user(u_state, &args->state, sizeof(args->state)))
return -EFAULT;
return 0;
}
static int dummy_ops_call_op(void *image, struct bpf_dummy_ops_test_args *args)
{
dummy_ops_test_ret_fn test = (void *)image;
struct bpf_dummy_ops_state *state = NULL;
/* state needs to be NULL if args[0] is 0 */
if (args->args[0])
state = &args->state;
return test(state, args->args[1], args->args[2],
args->args[3], args->args[4]);
}
extern const struct bpf_link_ops bpf_struct_ops_link_lops;
int bpf_struct_ops_test_run(struct bpf_prog *prog, const union bpf_attr *kattr,
union bpf_attr __user *uattr)
{
const struct bpf_struct_ops *st_ops = &bpf_bpf_dummy_ops;
const struct btf_type *func_proto;
struct bpf_dummy_ops_test_args *args;
struct bpf_tramp_links *tlinks;
struct bpf_tramp_link *link = NULL;
void *image = NULL;
unsigned int op_idx;
int prog_ret;
int err;
if (prog->aux->attach_btf_id != st_ops->type_id)
return -EOPNOTSUPP;
func_proto = prog->aux->attach_func_proto;
args = dummy_ops_init_args(kattr, btf_type_vlen(func_proto));
if (IS_ERR(args))
return PTR_ERR(args);
tlinks = kcalloc(BPF_TRAMP_MAX, sizeof(*tlinks), GFP_KERNEL);
if (!tlinks) {
err = -ENOMEM;
goto out;
}
image = bpf_jit_alloc_exec(PAGE_SIZE);
if (!image) {
err = -ENOMEM;
goto out;
}
set_vm_flush_reset_perms(image);
link = kzalloc(sizeof(*link), GFP_USER);
if (!link) {
err = -ENOMEM;
goto out;
}
/* prog doesn't take the ownership of the reference from caller */
bpf_prog_inc(prog);
bpf_link_init(&link->link, BPF_LINK_TYPE_STRUCT_OPS, &bpf_struct_ops_link_lops, prog);
op_idx = prog->expected_attach_type;
err = bpf_struct_ops_prepare_trampoline(tlinks, link,
&st_ops->func_models[op_idx],
image, image + PAGE_SIZE);
if (err < 0)
goto out;
set_memory_rox((long)image, 1);
prog_ret = dummy_ops_call_op(image, args);
err = dummy_ops_copy_args(args);
if (err)
goto out;
if (put_user(prog_ret, &uattr->test.retval))
err = -EFAULT;
out:
kfree(args);
bpf_jit_free_exec(image);
if (link)
bpf_link_put(&link->link);
kfree(tlinks);
return err;
}
static int bpf_dummy_init(struct btf *btf)
{
return 0;
}
static bool bpf_dummy_ops_is_valid_access(int off, int size,
enum bpf_access_type type,
const struct bpf_prog *prog,
struct bpf_insn_access_aux *info)
{
return bpf_tracing_btf_ctx_access(off, size, type, prog, info);
}
static int bpf_dummy_ops_check_member(const struct btf_type *t,
const struct btf_member *member,
const struct bpf_prog *prog)
{
u32 moff = __btf_member_bit_offset(t, member) / 8;
switch (moff) {
case offsetof(struct bpf_dummy_ops, test_sleepable):
break;
default:
if (prog->aux->sleepable)
return -EINVAL;
}
return 0;
}
static int bpf_dummy_ops_btf_struct_access(struct bpf_verifier_log *log,
const struct bpf_reg_state *reg,
int off, int size)
{
const struct btf_type *state;
const struct btf_type *t;
s32 type_id;
type_id = btf_find_by_name_kind(reg->btf, "bpf_dummy_ops_state",
BTF_KIND_STRUCT);
if (type_id < 0)
return -EINVAL;
t = btf_type_by_id(reg->btf, reg->btf_id);
state = btf_type_by_id(reg->btf, type_id);
if (t != state) {
bpf_log(log, "only access to bpf_dummy_ops_state is supported\n");
return -EACCES;
}
if (off + size > sizeof(struct bpf_dummy_ops_state)) {
bpf_log(log, "write access at off %d with size %d\n", off, size);
return -EACCES;
}
return NOT_INIT;
}
static const struct bpf_verifier_ops bpf_dummy_verifier_ops = {
.is_valid_access = bpf_dummy_ops_is_valid_access,
.btf_struct_access = bpf_dummy_ops_btf_struct_access,
};
static int bpf_dummy_init_member(const struct btf_type *t,
const struct btf_member *member,
void *kdata, const void *udata)
{
return -EOPNOTSUPP;
}
static int bpf_dummy_reg(void *kdata)
{
return -EOPNOTSUPP;
}
static void bpf_dummy_unreg(void *kdata)
{
}
struct bpf_struct_ops bpf_bpf_dummy_ops = {
.verifier_ops = &bpf_dummy_verifier_ops,
.init = bpf_dummy_init,
.check_member = bpf_dummy_ops_check_member,
.init_member = bpf_dummy_init_member,
.reg = bpf_dummy_reg,
.unreg = bpf_dummy_unreg,
.name = "bpf_dummy_ops",
};
| linux-master | net/bpf/bpf_dummy_struct_ops.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* IPv6 Address [auto]configuration
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <[email protected]>
* Alexey Kuznetsov <[email protected]>
*/
/*
* Changes:
*
* Janos Farkas : delete timer on ifdown
* <[email protected]>
* Andi Kleen : kill double kfree on module
* unload.
* Maciej W. Rozycki : FDDI support
* sekiya@USAGI : Don't send too many RS
* packets.
* yoshfuji@USAGI : Fixed interval between DAD
* packets.
* YOSHIFUJI Hideaki @USAGI : improved accuracy of
* address validation timer.
* YOSHIFUJI Hideaki @USAGI : Privacy Extensions (RFC3041)
* support.
* Yuji SEKIYA @USAGI : Don't assign a same IPv6
* address on a same interface.
* YOSHIFUJI Hideaki @USAGI : ARCnet support
* YOSHIFUJI Hideaki @USAGI : convert /proc/net/if_inet6 to
* seq_file.
* YOSHIFUJI Hideaki @USAGI : improved source address
* selection; consider scope,
* status etc.
*/
#define pr_fmt(fmt) "IPv6: " fmt
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/sched/signal.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/in6.h>
#include <linux/netdevice.h>
#include <linux/if_addr.h>
#include <linux/if_arp.h>
#include <linux/if_arcnet.h>
#include <linux/if_infiniband.h>
#include <linux/route.h>
#include <linux/inetdevice.h>
#include <linux/init.h>
#include <linux/slab.h>
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
#endif
#include <linux/capability.h>
#include <linux/delay.h>
#include <linux/notifier.h>
#include <linux/string.h>
#include <linux/hash.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/6lowpan.h>
#include <net/firewire.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <net/ndisc.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/tcp.h>
#include <net/ip.h>
#include <net/netlink.h>
#include <net/pkt_sched.h>
#include <net/l3mdev.h>
#include <linux/if_tunnel.h>
#include <linux/rtnetlink.h>
#include <linux/netconf.h>
#include <linux/random.h>
#include <linux/uaccess.h>
#include <asm/unaligned.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/export.h>
#include <linux/ioam6.h>
#define INFINITY_LIFE_TIME 0xFFFFFFFF
#define IPV6_MAX_STRLEN \
sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")
static inline u32 cstamp_delta(unsigned long cstamp)
{
return (cstamp - INITIAL_JIFFIES) * 100UL / HZ;
}
static inline s32 rfc3315_s14_backoff_init(s32 irt)
{
/* multiply 'initial retransmission time' by 0.9 .. 1.1 */
u64 tmp = get_random_u32_inclusive(900000, 1100000) * (u64)irt;
do_div(tmp, 1000000);
return (s32)tmp;
}
static inline s32 rfc3315_s14_backoff_update(s32 rt, s32 mrt)
{
/* multiply 'retransmission timeout' by 1.9 .. 2.1 */
u64 tmp = get_random_u32_inclusive(1900000, 2100000) * (u64)rt;
do_div(tmp, 1000000);
if ((s32)tmp > mrt) {
/* multiply 'maximum retransmission time' by 0.9 .. 1.1 */
tmp = get_random_u32_inclusive(900000, 1100000) * (u64)mrt;
do_div(tmp, 1000000);
}
return (s32)tmp;
}
#ifdef CONFIG_SYSCTL
static int addrconf_sysctl_register(struct inet6_dev *idev);
static void addrconf_sysctl_unregister(struct inet6_dev *idev);
#else
static inline int addrconf_sysctl_register(struct inet6_dev *idev)
{
return 0;
}
static inline void addrconf_sysctl_unregister(struct inet6_dev *idev)
{
}
#endif
static void ipv6_gen_rnd_iid(struct in6_addr *addr);
static int ipv6_generate_eui64(u8 *eui, struct net_device *dev);
static int ipv6_count_addresses(const struct inet6_dev *idev);
static int ipv6_generate_stable_address(struct in6_addr *addr,
u8 dad_count,
const struct inet6_dev *idev);
#define IN6_ADDR_HSIZE_SHIFT 8
#define IN6_ADDR_HSIZE (1 << IN6_ADDR_HSIZE_SHIFT)
static void addrconf_verify(struct net *net);
static void addrconf_verify_rtnl(struct net *net);
static struct workqueue_struct *addrconf_wq;
static void addrconf_join_anycast(struct inet6_ifaddr *ifp);
static void addrconf_leave_anycast(struct inet6_ifaddr *ifp);
static void addrconf_type_change(struct net_device *dev,
unsigned long event);
static int addrconf_ifdown(struct net_device *dev, bool unregister);
static struct fib6_info *addrconf_get_prefix_route(const struct in6_addr *pfx,
int plen,
const struct net_device *dev,
u32 flags, u32 noflags,
bool no_gw);
static void addrconf_dad_start(struct inet6_ifaddr *ifp);
static void addrconf_dad_work(struct work_struct *w);
static void addrconf_dad_completed(struct inet6_ifaddr *ifp, bool bump_id,
bool send_na);
static void addrconf_dad_run(struct inet6_dev *idev, bool restart);
static void addrconf_rs_timer(struct timer_list *t);
static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa);
static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa);
static void inet6_prefix_notify(int event, struct inet6_dev *idev,
struct prefix_info *pinfo);
static struct ipv6_devconf ipv6_devconf __read_mostly = {
.forwarding = 0,
.hop_limit = IPV6_DEFAULT_HOPLIMIT,
.mtu6 = IPV6_MIN_MTU,
.accept_ra = 1,
.accept_redirects = 1,
.autoconf = 1,
.force_mld_version = 0,
.mldv1_unsolicited_report_interval = 10 * HZ,
.mldv2_unsolicited_report_interval = HZ,
.dad_transmits = 1,
.rtr_solicits = MAX_RTR_SOLICITATIONS,
.rtr_solicit_interval = RTR_SOLICITATION_INTERVAL,
.rtr_solicit_max_interval = RTR_SOLICITATION_MAX_INTERVAL,
.rtr_solicit_delay = MAX_RTR_SOLICITATION_DELAY,
.use_tempaddr = 0,
.temp_valid_lft = TEMP_VALID_LIFETIME,
.temp_prefered_lft = TEMP_PREFERRED_LIFETIME,
.regen_max_retry = REGEN_MAX_RETRY,
.max_desync_factor = MAX_DESYNC_FACTOR,
.max_addresses = IPV6_MAX_ADDRESSES,
.accept_ra_defrtr = 1,
.ra_defrtr_metric = IP6_RT_PRIO_USER,
.accept_ra_from_local = 0,
.accept_ra_min_hop_limit= 1,
.accept_ra_min_lft = 0,
.accept_ra_pinfo = 1,
#ifdef CONFIG_IPV6_ROUTER_PREF
.accept_ra_rtr_pref = 1,
.rtr_probe_interval = 60 * HZ,
#ifdef CONFIG_IPV6_ROUTE_INFO
.accept_ra_rt_info_min_plen = 0,
.accept_ra_rt_info_max_plen = 0,
#endif
#endif
.proxy_ndp = 0,
.accept_source_route = 0, /* we do not accept RH0 by default. */
.disable_ipv6 = 0,
.accept_dad = 0,
.suppress_frag_ndisc = 1,
.accept_ra_mtu = 1,
.stable_secret = {
.initialized = false,
},
.use_oif_addrs_only = 0,
.ignore_routes_with_linkdown = 0,
.keep_addr_on_down = 0,
.seg6_enabled = 0,
#ifdef CONFIG_IPV6_SEG6_HMAC
.seg6_require_hmac = 0,
#endif
.enhanced_dad = 1,
.addr_gen_mode = IN6_ADDR_GEN_MODE_EUI64,
.disable_policy = 0,
.rpl_seg_enabled = 0,
.ioam6_enabled = 0,
.ioam6_id = IOAM6_DEFAULT_IF_ID,
.ioam6_id_wide = IOAM6_DEFAULT_IF_ID_WIDE,
.ndisc_evict_nocarrier = 1,
};
static struct ipv6_devconf ipv6_devconf_dflt __read_mostly = {
.forwarding = 0,
.hop_limit = IPV6_DEFAULT_HOPLIMIT,
.mtu6 = IPV6_MIN_MTU,
.accept_ra = 1,
.accept_redirects = 1,
.autoconf = 1,
.force_mld_version = 0,
.mldv1_unsolicited_report_interval = 10 * HZ,
.mldv2_unsolicited_report_interval = HZ,
.dad_transmits = 1,
.rtr_solicits = MAX_RTR_SOLICITATIONS,
.rtr_solicit_interval = RTR_SOLICITATION_INTERVAL,
.rtr_solicit_max_interval = RTR_SOLICITATION_MAX_INTERVAL,
.rtr_solicit_delay = MAX_RTR_SOLICITATION_DELAY,
.use_tempaddr = 0,
.temp_valid_lft = TEMP_VALID_LIFETIME,
.temp_prefered_lft = TEMP_PREFERRED_LIFETIME,
.regen_max_retry = REGEN_MAX_RETRY,
.max_desync_factor = MAX_DESYNC_FACTOR,
.max_addresses = IPV6_MAX_ADDRESSES,
.accept_ra_defrtr = 1,
.ra_defrtr_metric = IP6_RT_PRIO_USER,
.accept_ra_from_local = 0,
.accept_ra_min_hop_limit= 1,
.accept_ra_min_lft = 0,
.accept_ra_pinfo = 1,
#ifdef CONFIG_IPV6_ROUTER_PREF
.accept_ra_rtr_pref = 1,
.rtr_probe_interval = 60 * HZ,
#ifdef CONFIG_IPV6_ROUTE_INFO
.accept_ra_rt_info_min_plen = 0,
.accept_ra_rt_info_max_plen = 0,
#endif
#endif
.proxy_ndp = 0,
.accept_source_route = 0, /* we do not accept RH0 by default. */
.disable_ipv6 = 0,
.accept_dad = 1,
.suppress_frag_ndisc = 1,
.accept_ra_mtu = 1,
.stable_secret = {
.initialized = false,
},
.use_oif_addrs_only = 0,
.ignore_routes_with_linkdown = 0,
.keep_addr_on_down = 0,
.seg6_enabled = 0,
#ifdef CONFIG_IPV6_SEG6_HMAC
.seg6_require_hmac = 0,
#endif
.enhanced_dad = 1,
.addr_gen_mode = IN6_ADDR_GEN_MODE_EUI64,
.disable_policy = 0,
.rpl_seg_enabled = 0,
.ioam6_enabled = 0,
.ioam6_id = IOAM6_DEFAULT_IF_ID,
.ioam6_id_wide = IOAM6_DEFAULT_IF_ID_WIDE,
.ndisc_evict_nocarrier = 1,
};
/* Check if link is ready: is it up and is a valid qdisc available */
static inline bool addrconf_link_ready(const struct net_device *dev)
{
return netif_oper_up(dev) && !qdisc_tx_is_noop(dev);
}
static void addrconf_del_rs_timer(struct inet6_dev *idev)
{
if (del_timer(&idev->rs_timer))
__in6_dev_put(idev);
}
static void addrconf_del_dad_work(struct inet6_ifaddr *ifp)
{
if (cancel_delayed_work(&ifp->dad_work))
__in6_ifa_put(ifp);
}
static void addrconf_mod_rs_timer(struct inet6_dev *idev,
unsigned long when)
{
if (!mod_timer(&idev->rs_timer, jiffies + when))
in6_dev_hold(idev);
}
static void addrconf_mod_dad_work(struct inet6_ifaddr *ifp,
unsigned long delay)
{
in6_ifa_hold(ifp);
if (mod_delayed_work(addrconf_wq, &ifp->dad_work, delay))
in6_ifa_put(ifp);
}
static int snmp6_alloc_dev(struct inet6_dev *idev)
{
int i;
idev->stats.ipv6 = alloc_percpu_gfp(struct ipstats_mib, GFP_KERNEL_ACCOUNT);
if (!idev->stats.ipv6)
goto err_ip;
for_each_possible_cpu(i) {
struct ipstats_mib *addrconf_stats;
addrconf_stats = per_cpu_ptr(idev->stats.ipv6, i);
u64_stats_init(&addrconf_stats->syncp);
}
idev->stats.icmpv6dev = kzalloc(sizeof(struct icmpv6_mib_device),
GFP_KERNEL);
if (!idev->stats.icmpv6dev)
goto err_icmp;
idev->stats.icmpv6msgdev = kzalloc(sizeof(struct icmpv6msg_mib_device),
GFP_KERNEL_ACCOUNT);
if (!idev->stats.icmpv6msgdev)
goto err_icmpmsg;
return 0;
err_icmpmsg:
kfree(idev->stats.icmpv6dev);
err_icmp:
free_percpu(idev->stats.ipv6);
err_ip:
return -ENOMEM;
}
static struct inet6_dev *ipv6_add_dev(struct net_device *dev)
{
struct inet6_dev *ndev;
int err = -ENOMEM;
ASSERT_RTNL();
if (dev->mtu < IPV6_MIN_MTU && dev != blackhole_netdev)
return ERR_PTR(-EINVAL);
ndev = kzalloc(sizeof(*ndev), GFP_KERNEL_ACCOUNT);
if (!ndev)
return ERR_PTR(err);
rwlock_init(&ndev->lock);
ndev->dev = dev;
INIT_LIST_HEAD(&ndev->addr_list);
timer_setup(&ndev->rs_timer, addrconf_rs_timer, 0);
memcpy(&ndev->cnf, dev_net(dev)->ipv6.devconf_dflt, sizeof(ndev->cnf));
if (ndev->cnf.stable_secret.initialized)
ndev->cnf.addr_gen_mode = IN6_ADDR_GEN_MODE_STABLE_PRIVACY;
ndev->cnf.mtu6 = dev->mtu;
ndev->ra_mtu = 0;
ndev->nd_parms = neigh_parms_alloc(dev, &nd_tbl);
if (!ndev->nd_parms) {
kfree(ndev);
return ERR_PTR(err);
}
if (ndev->cnf.forwarding)
dev_disable_lro(dev);
/* We refer to the device */
netdev_hold(dev, &ndev->dev_tracker, GFP_KERNEL);
if (snmp6_alloc_dev(ndev) < 0) {
netdev_dbg(dev, "%s: cannot allocate memory for statistics\n",
__func__);
neigh_parms_release(&nd_tbl, ndev->nd_parms);
netdev_put(dev, &ndev->dev_tracker);
kfree(ndev);
return ERR_PTR(err);
}
if (dev != blackhole_netdev) {
if (snmp6_register_dev(ndev) < 0) {
netdev_dbg(dev, "%s: cannot create /proc/net/dev_snmp6/%s\n",
__func__, dev->name);
goto err_release;
}
}
/* One reference from device. */
refcount_set(&ndev->refcnt, 1);
if (dev->flags & (IFF_NOARP | IFF_LOOPBACK))
ndev->cnf.accept_dad = -1;
#if IS_ENABLED(CONFIG_IPV6_SIT)
if (dev->type == ARPHRD_SIT && (dev->priv_flags & IFF_ISATAP)) {
pr_info("%s: Disabled Multicast RS\n", dev->name);
ndev->cnf.rtr_solicits = 0;
}
#endif
INIT_LIST_HEAD(&ndev->tempaddr_list);
ndev->desync_factor = U32_MAX;
if ((dev->flags&IFF_LOOPBACK) ||
dev->type == ARPHRD_TUNNEL ||
dev->type == ARPHRD_TUNNEL6 ||
dev->type == ARPHRD_SIT ||
dev->type == ARPHRD_NONE) {
ndev->cnf.use_tempaddr = -1;
}
ndev->token = in6addr_any;
if (netif_running(dev) && addrconf_link_ready(dev))
ndev->if_flags |= IF_READY;
ipv6_mc_init_dev(ndev);
ndev->tstamp = jiffies;
if (dev != blackhole_netdev) {
err = addrconf_sysctl_register(ndev);
if (err) {
ipv6_mc_destroy_dev(ndev);
snmp6_unregister_dev(ndev);
goto err_release;
}
}
/* protected by rtnl_lock */
rcu_assign_pointer(dev->ip6_ptr, ndev);
if (dev != blackhole_netdev) {
/* Join interface-local all-node multicast group */
ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allnodes);
/* Join all-node multicast group */
ipv6_dev_mc_inc(dev, &in6addr_linklocal_allnodes);
/* Join all-router multicast group if forwarding is set */
if (ndev->cnf.forwarding && (dev->flags & IFF_MULTICAST))
ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters);
}
return ndev;
err_release:
neigh_parms_release(&nd_tbl, ndev->nd_parms);
ndev->dead = 1;
in6_dev_finish_destroy(ndev);
return ERR_PTR(err);
}
static struct inet6_dev *ipv6_find_idev(struct net_device *dev)
{
struct inet6_dev *idev;
ASSERT_RTNL();
idev = __in6_dev_get(dev);
if (!idev) {
idev = ipv6_add_dev(dev);
if (IS_ERR(idev))
return idev;
}
if (dev->flags&IFF_UP)
ipv6_mc_up(idev);
return idev;
}
static int inet6_netconf_msgsize_devconf(int type)
{
int size = NLMSG_ALIGN(sizeof(struct netconfmsg))
+ nla_total_size(4); /* NETCONFA_IFINDEX */
bool all = false;
if (type == NETCONFA_ALL)
all = true;
if (all || type == NETCONFA_FORWARDING)
size += nla_total_size(4);
#ifdef CONFIG_IPV6_MROUTE
if (all || type == NETCONFA_MC_FORWARDING)
size += nla_total_size(4);
#endif
if (all || type == NETCONFA_PROXY_NEIGH)
size += nla_total_size(4);
if (all || type == NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN)
size += nla_total_size(4);
return size;
}
static int inet6_netconf_fill_devconf(struct sk_buff *skb, int ifindex,
struct ipv6_devconf *devconf, u32 portid,
u32 seq, int event, unsigned int flags,
int type)
{
struct nlmsghdr *nlh;
struct netconfmsg *ncm;
bool all = false;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct netconfmsg),
flags);
if (!nlh)
return -EMSGSIZE;
if (type == NETCONFA_ALL)
all = true;
ncm = nlmsg_data(nlh);
ncm->ncm_family = AF_INET6;
if (nla_put_s32(skb, NETCONFA_IFINDEX, ifindex) < 0)
goto nla_put_failure;
if (!devconf)
goto out;
if ((all || type == NETCONFA_FORWARDING) &&
nla_put_s32(skb, NETCONFA_FORWARDING, devconf->forwarding) < 0)
goto nla_put_failure;
#ifdef CONFIG_IPV6_MROUTE
if ((all || type == NETCONFA_MC_FORWARDING) &&
nla_put_s32(skb, NETCONFA_MC_FORWARDING,
atomic_read(&devconf->mc_forwarding)) < 0)
goto nla_put_failure;
#endif
if ((all || type == NETCONFA_PROXY_NEIGH) &&
nla_put_s32(skb, NETCONFA_PROXY_NEIGH, devconf->proxy_ndp) < 0)
goto nla_put_failure;
if ((all || type == NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN) &&
nla_put_s32(skb, NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
devconf->ignore_routes_with_linkdown) < 0)
goto nla_put_failure;
out:
nlmsg_end(skb, nlh);
return 0;
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
void inet6_netconf_notify_devconf(struct net *net, int event, int type,
int ifindex, struct ipv6_devconf *devconf)
{
struct sk_buff *skb;
int err = -ENOBUFS;
skb = nlmsg_new(inet6_netconf_msgsize_devconf(type), GFP_KERNEL);
if (!skb)
goto errout;
err = inet6_netconf_fill_devconf(skb, ifindex, devconf, 0, 0,
event, 0, type);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_IPV6_NETCONF, NULL, GFP_KERNEL);
return;
errout:
rtnl_set_sk_err(net, RTNLGRP_IPV6_NETCONF, err);
}
static const struct nla_policy devconf_ipv6_policy[NETCONFA_MAX+1] = {
[NETCONFA_IFINDEX] = { .len = sizeof(int) },
[NETCONFA_FORWARDING] = { .len = sizeof(int) },
[NETCONFA_PROXY_NEIGH] = { .len = sizeof(int) },
[NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN] = { .len = sizeof(int) },
};
static int inet6_netconf_valid_get_req(struct sk_buff *skb,
const struct nlmsghdr *nlh,
struct nlattr **tb,
struct netlink_ext_ack *extack)
{
int i, err;
if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(struct netconfmsg))) {
NL_SET_ERR_MSG_MOD(extack, "Invalid header for netconf get request");
return -EINVAL;
}
if (!netlink_strict_get_check(skb))
return nlmsg_parse_deprecated(nlh, sizeof(struct netconfmsg),
tb, NETCONFA_MAX,
devconf_ipv6_policy, extack);
err = nlmsg_parse_deprecated_strict(nlh, sizeof(struct netconfmsg),
tb, NETCONFA_MAX,
devconf_ipv6_policy, extack);
if (err)
return err;
for (i = 0; i <= NETCONFA_MAX; i++) {
if (!tb[i])
continue;
switch (i) {
case NETCONFA_IFINDEX:
break;
default:
NL_SET_ERR_MSG_MOD(extack, "Unsupported attribute in netconf get request");
return -EINVAL;
}
}
return 0;
}
static int inet6_netconf_get_devconf(struct sk_buff *in_skb,
struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(in_skb->sk);
struct nlattr *tb[NETCONFA_MAX+1];
struct inet6_dev *in6_dev = NULL;
struct net_device *dev = NULL;
struct sk_buff *skb;
struct ipv6_devconf *devconf;
int ifindex;
int err;
err = inet6_netconf_valid_get_req(in_skb, nlh, tb, extack);
if (err < 0)
return err;
if (!tb[NETCONFA_IFINDEX])
return -EINVAL;
err = -EINVAL;
ifindex = nla_get_s32(tb[NETCONFA_IFINDEX]);
switch (ifindex) {
case NETCONFA_IFINDEX_ALL:
devconf = net->ipv6.devconf_all;
break;
case NETCONFA_IFINDEX_DEFAULT:
devconf = net->ipv6.devconf_dflt;
break;
default:
dev = dev_get_by_index(net, ifindex);
if (!dev)
return -EINVAL;
in6_dev = in6_dev_get(dev);
if (!in6_dev)
goto errout;
devconf = &in6_dev->cnf;
break;
}
err = -ENOBUFS;
skb = nlmsg_new(inet6_netconf_msgsize_devconf(NETCONFA_ALL), GFP_KERNEL);
if (!skb)
goto errout;
err = inet6_netconf_fill_devconf(skb, ifindex, devconf,
NETLINK_CB(in_skb).portid,
nlh->nlmsg_seq, RTM_NEWNETCONF, 0,
NETCONFA_ALL);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
errout:
if (in6_dev)
in6_dev_put(in6_dev);
dev_put(dev);
return err;
}
static int inet6_netconf_dump_devconf(struct sk_buff *skb,
struct netlink_callback *cb)
{
const struct nlmsghdr *nlh = cb->nlh;
struct net *net = sock_net(skb->sk);
int h, s_h;
int idx, s_idx;
struct net_device *dev;
struct inet6_dev *idev;
struct hlist_head *head;
if (cb->strict_check) {
struct netlink_ext_ack *extack = cb->extack;
struct netconfmsg *ncm;
if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*ncm))) {
NL_SET_ERR_MSG_MOD(extack, "Invalid header for netconf dump request");
return -EINVAL;
}
if (nlmsg_attrlen(nlh, sizeof(*ncm))) {
NL_SET_ERR_MSG_MOD(extack, "Invalid data after header in netconf dump request");
return -EINVAL;
}
}
s_h = cb->args[0];
s_idx = idx = cb->args[1];
for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
idx = 0;
head = &net->dev_index_head[h];
rcu_read_lock();
cb->seq = atomic_read(&net->ipv6.dev_addr_genid) ^
net->dev_base_seq;
hlist_for_each_entry_rcu(dev, head, index_hlist) {
if (idx < s_idx)
goto cont;
idev = __in6_dev_get(dev);
if (!idev)
goto cont;
if (inet6_netconf_fill_devconf(skb, dev->ifindex,
&idev->cnf,
NETLINK_CB(cb->skb).portid,
nlh->nlmsg_seq,
RTM_NEWNETCONF,
NLM_F_MULTI,
NETCONFA_ALL) < 0) {
rcu_read_unlock();
goto done;
}
nl_dump_check_consistent(cb, nlmsg_hdr(skb));
cont:
idx++;
}
rcu_read_unlock();
}
if (h == NETDEV_HASHENTRIES) {
if (inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_ALL,
net->ipv6.devconf_all,
NETLINK_CB(cb->skb).portid,
nlh->nlmsg_seq,
RTM_NEWNETCONF, NLM_F_MULTI,
NETCONFA_ALL) < 0)
goto done;
else
h++;
}
if (h == NETDEV_HASHENTRIES + 1) {
if (inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_DEFAULT,
net->ipv6.devconf_dflt,
NETLINK_CB(cb->skb).portid,
nlh->nlmsg_seq,
RTM_NEWNETCONF, NLM_F_MULTI,
NETCONFA_ALL) < 0)
goto done;
else
h++;
}
done:
cb->args[0] = h;
cb->args[1] = idx;
return skb->len;
}
#ifdef CONFIG_SYSCTL
static void dev_forward_change(struct inet6_dev *idev)
{
struct net_device *dev;
struct inet6_ifaddr *ifa;
LIST_HEAD(tmp_addr_list);
if (!idev)
return;
dev = idev->dev;
if (idev->cnf.forwarding)
dev_disable_lro(dev);
if (dev->flags & IFF_MULTICAST) {
if (idev->cnf.forwarding) {
ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters);
ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allrouters);
ipv6_dev_mc_inc(dev, &in6addr_sitelocal_allrouters);
} else {
ipv6_dev_mc_dec(dev, &in6addr_linklocal_allrouters);
ipv6_dev_mc_dec(dev, &in6addr_interfacelocal_allrouters);
ipv6_dev_mc_dec(dev, &in6addr_sitelocal_allrouters);
}
}
read_lock_bh(&idev->lock);
list_for_each_entry(ifa, &idev->addr_list, if_list) {
if (ifa->flags&IFA_F_TENTATIVE)
continue;
list_add_tail(&ifa->if_list_aux, &tmp_addr_list);
}
read_unlock_bh(&idev->lock);
while (!list_empty(&tmp_addr_list)) {
ifa = list_first_entry(&tmp_addr_list,
struct inet6_ifaddr, if_list_aux);
list_del(&ifa->if_list_aux);
if (idev->cnf.forwarding)
addrconf_join_anycast(ifa);
else
addrconf_leave_anycast(ifa);
}
inet6_netconf_notify_devconf(dev_net(dev), RTM_NEWNETCONF,
NETCONFA_FORWARDING,
dev->ifindex, &idev->cnf);
}
static void addrconf_forward_change(struct net *net, __s32 newf)
{
struct net_device *dev;
struct inet6_dev *idev;
for_each_netdev(net, dev) {
idev = __in6_dev_get(dev);
if (idev) {
int changed = (!idev->cnf.forwarding) ^ (!newf);
idev->cnf.forwarding = newf;
if (changed)
dev_forward_change(idev);
}
}
}
static int addrconf_fixup_forwarding(struct ctl_table *table, int *p, int newf)
{
struct net *net;
int old;
if (!rtnl_trylock())
return restart_syscall();
net = (struct net *)table->extra2;
old = *p;
*p = newf;
if (p == &net->ipv6.devconf_dflt->forwarding) {
if ((!newf) ^ (!old))
inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
NETCONFA_FORWARDING,
NETCONFA_IFINDEX_DEFAULT,
net->ipv6.devconf_dflt);
rtnl_unlock();
return 0;
}
if (p == &net->ipv6.devconf_all->forwarding) {
int old_dflt = net->ipv6.devconf_dflt->forwarding;
net->ipv6.devconf_dflt->forwarding = newf;
if ((!newf) ^ (!old_dflt))
inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
NETCONFA_FORWARDING,
NETCONFA_IFINDEX_DEFAULT,
net->ipv6.devconf_dflt);
addrconf_forward_change(net, newf);
if ((!newf) ^ (!old))
inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
NETCONFA_FORWARDING,
NETCONFA_IFINDEX_ALL,
net->ipv6.devconf_all);
} else if ((!newf) ^ (!old))
dev_forward_change((struct inet6_dev *)table->extra1);
rtnl_unlock();
if (newf)
rt6_purge_dflt_routers(net);
return 1;
}
static void addrconf_linkdown_change(struct net *net, __s32 newf)
{
struct net_device *dev;
struct inet6_dev *idev;
for_each_netdev(net, dev) {
idev = __in6_dev_get(dev);
if (idev) {
int changed = (!idev->cnf.ignore_routes_with_linkdown) ^ (!newf);
idev->cnf.ignore_routes_with_linkdown = newf;
if (changed)
inet6_netconf_notify_devconf(dev_net(dev),
RTM_NEWNETCONF,
NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
dev->ifindex,
&idev->cnf);
}
}
}
static int addrconf_fixup_linkdown(struct ctl_table *table, int *p, int newf)
{
struct net *net;
int old;
if (!rtnl_trylock())
return restart_syscall();
net = (struct net *)table->extra2;
old = *p;
*p = newf;
if (p == &net->ipv6.devconf_dflt->ignore_routes_with_linkdown) {
if ((!newf) ^ (!old))
inet6_netconf_notify_devconf(net,
RTM_NEWNETCONF,
NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
NETCONFA_IFINDEX_DEFAULT,
net->ipv6.devconf_dflt);
rtnl_unlock();
return 0;
}
if (p == &net->ipv6.devconf_all->ignore_routes_with_linkdown) {
net->ipv6.devconf_dflt->ignore_routes_with_linkdown = newf;
addrconf_linkdown_change(net, newf);
if ((!newf) ^ (!old))
inet6_netconf_notify_devconf(net,
RTM_NEWNETCONF,
NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
NETCONFA_IFINDEX_ALL,
net->ipv6.devconf_all);
}
rtnl_unlock();
return 1;
}
#endif
/* Nobody refers to this ifaddr, destroy it */
void inet6_ifa_finish_destroy(struct inet6_ifaddr *ifp)
{
WARN_ON(!hlist_unhashed(&ifp->addr_lst));
#ifdef NET_REFCNT_DEBUG
pr_debug("%s\n", __func__);
#endif
in6_dev_put(ifp->idev);
if (cancel_delayed_work(&ifp->dad_work))
pr_notice("delayed DAD work was pending while freeing ifa=%p\n",
ifp);
if (ifp->state != INET6_IFADDR_STATE_DEAD) {
pr_warn("Freeing alive inet6 address %p\n", ifp);
return;
}
kfree_rcu(ifp, rcu);
}
static void
ipv6_link_dev_addr(struct inet6_dev *idev, struct inet6_ifaddr *ifp)
{
struct list_head *p;
int ifp_scope = ipv6_addr_src_scope(&ifp->addr);
/*
* Each device address list is sorted in order of scope -
* global before linklocal.
*/
list_for_each(p, &idev->addr_list) {
struct inet6_ifaddr *ifa
= list_entry(p, struct inet6_ifaddr, if_list);
if (ifp_scope >= ipv6_addr_src_scope(&ifa->addr))
break;
}
list_add_tail_rcu(&ifp->if_list, p);
}
static u32 inet6_addr_hash(const struct net *net, const struct in6_addr *addr)
{
u32 val = ipv6_addr_hash(addr) ^ net_hash_mix(net);
return hash_32(val, IN6_ADDR_HSIZE_SHIFT);
}
static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr,
struct net_device *dev, unsigned int hash)
{
struct inet6_ifaddr *ifp;
hlist_for_each_entry(ifp, &net->ipv6.inet6_addr_lst[hash], addr_lst) {
if (ipv6_addr_equal(&ifp->addr, addr)) {
if (!dev || ifp->idev->dev == dev)
return true;
}
}
return false;
}
static int ipv6_add_addr_hash(struct net_device *dev, struct inet6_ifaddr *ifa)
{
struct net *net = dev_net(dev);
unsigned int hash = inet6_addr_hash(net, &ifa->addr);
int err = 0;
spin_lock_bh(&net->ipv6.addrconf_hash_lock);
/* Ignore adding duplicate addresses on an interface */
if (ipv6_chk_same_addr(net, &ifa->addr, dev, hash)) {
netdev_dbg(dev, "ipv6_add_addr: already assigned\n");
err = -EEXIST;
} else {
hlist_add_head_rcu(&ifa->addr_lst, &net->ipv6.inet6_addr_lst[hash]);
}
spin_unlock_bh(&net->ipv6.addrconf_hash_lock);
return err;
}
/* On success it returns ifp with increased reference count */
static struct inet6_ifaddr *
ipv6_add_addr(struct inet6_dev *idev, struct ifa6_config *cfg,
bool can_block, struct netlink_ext_ack *extack)
{
gfp_t gfp_flags = can_block ? GFP_KERNEL : GFP_ATOMIC;
int addr_type = ipv6_addr_type(cfg->pfx);
struct net *net = dev_net(idev->dev);
struct inet6_ifaddr *ifa = NULL;
struct fib6_info *f6i = NULL;
int err = 0;
if (addr_type == IPV6_ADDR_ANY) {
NL_SET_ERR_MSG_MOD(extack, "Invalid address");
return ERR_PTR(-EADDRNOTAVAIL);
} else if (addr_type & IPV6_ADDR_MULTICAST &&
!(cfg->ifa_flags & IFA_F_MCAUTOJOIN)) {
NL_SET_ERR_MSG_MOD(extack, "Cannot assign multicast address without \"IFA_F_MCAUTOJOIN\" flag");
return ERR_PTR(-EADDRNOTAVAIL);
} else if (!(idev->dev->flags & IFF_LOOPBACK) &&
!netif_is_l3_master(idev->dev) &&
addr_type & IPV6_ADDR_LOOPBACK) {
NL_SET_ERR_MSG_MOD(extack, "Cannot assign loopback address on this device");
return ERR_PTR(-EADDRNOTAVAIL);
}
if (idev->dead) {
NL_SET_ERR_MSG_MOD(extack, "device is going away");
err = -ENODEV;
goto out;
}
if (idev->cnf.disable_ipv6) {
NL_SET_ERR_MSG_MOD(extack, "IPv6 is disabled on this device");
err = -EACCES;
goto out;
}
/* validator notifier needs to be blocking;
* do not call in atomic context
*/
if (can_block) {
struct in6_validator_info i6vi = {
.i6vi_addr = *cfg->pfx,
.i6vi_dev = idev,
.extack = extack,
};
err = inet6addr_validator_notifier_call_chain(NETDEV_UP, &i6vi);
err = notifier_to_errno(err);
if (err < 0)
goto out;
}
ifa = kzalloc(sizeof(*ifa), gfp_flags | __GFP_ACCOUNT);
if (!ifa) {
err = -ENOBUFS;
goto out;
}
f6i = addrconf_f6i_alloc(net, idev, cfg->pfx, false, gfp_flags, extack);
if (IS_ERR(f6i)) {
err = PTR_ERR(f6i);
f6i = NULL;
goto out;
}
neigh_parms_data_state_setall(idev->nd_parms);
ifa->addr = *cfg->pfx;
if (cfg->peer_pfx)
ifa->peer_addr = *cfg->peer_pfx;
spin_lock_init(&ifa->lock);
INIT_DELAYED_WORK(&ifa->dad_work, addrconf_dad_work);
INIT_HLIST_NODE(&ifa->addr_lst);
ifa->scope = cfg->scope;
ifa->prefix_len = cfg->plen;
ifa->rt_priority = cfg->rt_priority;
ifa->flags = cfg->ifa_flags;
ifa->ifa_proto = cfg->ifa_proto;
/* No need to add the TENTATIVE flag for addresses with NODAD */
if (!(cfg->ifa_flags & IFA_F_NODAD))
ifa->flags |= IFA_F_TENTATIVE;
ifa->valid_lft = cfg->valid_lft;
ifa->prefered_lft = cfg->preferred_lft;
ifa->cstamp = ifa->tstamp = jiffies;
ifa->tokenized = false;
ifa->rt = f6i;
ifa->idev = idev;
in6_dev_hold(idev);
/* For caller */
refcount_set(&ifa->refcnt, 1);
rcu_read_lock();
err = ipv6_add_addr_hash(idev->dev, ifa);
if (err < 0) {
rcu_read_unlock();
goto out;
}
write_lock_bh(&idev->lock);
/* Add to inet6_dev unicast addr list. */
ipv6_link_dev_addr(idev, ifa);
if (ifa->flags&IFA_F_TEMPORARY) {
list_add(&ifa->tmp_list, &idev->tempaddr_list);
in6_ifa_hold(ifa);
}
in6_ifa_hold(ifa);
write_unlock_bh(&idev->lock);
rcu_read_unlock();
inet6addr_notifier_call_chain(NETDEV_UP, ifa);
out:
if (unlikely(err < 0)) {
fib6_info_release(f6i);
if (ifa) {
if (ifa->idev)
in6_dev_put(ifa->idev);
kfree(ifa);
}
ifa = ERR_PTR(err);
}
return ifa;
}
enum cleanup_prefix_rt_t {
CLEANUP_PREFIX_RT_NOP, /* no cleanup action for prefix route */
CLEANUP_PREFIX_RT_DEL, /* delete the prefix route */
CLEANUP_PREFIX_RT_EXPIRE, /* update the lifetime of the prefix route */
};
/*
* Check, whether the prefix for ifp would still need a prefix route
* after deleting ifp. The function returns one of the CLEANUP_PREFIX_RT_*
* constants.
*
* 1) we don't purge prefix if address was not permanent.
* prefix is managed by its own lifetime.
* 2) we also don't purge, if the address was IFA_F_NOPREFIXROUTE.
* 3) if there are no addresses, delete prefix.
* 4) if there are still other permanent address(es),
* corresponding prefix is still permanent.
* 5) if there are still other addresses with IFA_F_NOPREFIXROUTE,
* don't purge the prefix, assume user space is managing it.
* 6) otherwise, update prefix lifetime to the
* longest valid lifetime among the corresponding
* addresses on the device.
* Note: subsequent RA will update lifetime.
**/
static enum cleanup_prefix_rt_t
check_cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long *expires)
{
struct inet6_ifaddr *ifa;
struct inet6_dev *idev = ifp->idev;
unsigned long lifetime;
enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_DEL;
*expires = jiffies;
list_for_each_entry(ifa, &idev->addr_list, if_list) {
if (ifa == ifp)
continue;
if (ifa->prefix_len != ifp->prefix_len ||
!ipv6_prefix_equal(&ifa->addr, &ifp->addr,
ifp->prefix_len))
continue;
if (ifa->flags & (IFA_F_PERMANENT | IFA_F_NOPREFIXROUTE))
return CLEANUP_PREFIX_RT_NOP;
action = CLEANUP_PREFIX_RT_EXPIRE;
spin_lock(&ifa->lock);
lifetime = addrconf_timeout_fixup(ifa->valid_lft, HZ);
/*
* Note: Because this address is
* not permanent, lifetime <
* LONG_MAX / HZ here.
*/
if (time_before(*expires, ifa->tstamp + lifetime * HZ))
*expires = ifa->tstamp + lifetime * HZ;
spin_unlock(&ifa->lock);
}
return action;
}
static void
cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long expires,
bool del_rt, bool del_peer)
{
struct fib6_info *f6i;
f6i = addrconf_get_prefix_route(del_peer ? &ifp->peer_addr : &ifp->addr,
ifp->prefix_len,
ifp->idev->dev, 0, RTF_DEFAULT, true);
if (f6i) {
if (del_rt)
ip6_del_rt(dev_net(ifp->idev->dev), f6i, false);
else {
if (!(f6i->fib6_flags & RTF_EXPIRES))
fib6_set_expires(f6i, expires);
fib6_info_release(f6i);
}
}
}
/* This function wants to get referenced ifp and releases it before return */
static void ipv6_del_addr(struct inet6_ifaddr *ifp)
{
enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_NOP;
struct net *net = dev_net(ifp->idev->dev);
unsigned long expires;
int state;
ASSERT_RTNL();
spin_lock_bh(&ifp->lock);
state = ifp->state;
ifp->state = INET6_IFADDR_STATE_DEAD;
spin_unlock_bh(&ifp->lock);
if (state == INET6_IFADDR_STATE_DEAD)
goto out;
spin_lock_bh(&net->ipv6.addrconf_hash_lock);
hlist_del_init_rcu(&ifp->addr_lst);
spin_unlock_bh(&net->ipv6.addrconf_hash_lock);
write_lock_bh(&ifp->idev->lock);
if (ifp->flags&IFA_F_TEMPORARY) {
list_del(&ifp->tmp_list);
if (ifp->ifpub) {
in6_ifa_put(ifp->ifpub);
ifp->ifpub = NULL;
}
__in6_ifa_put(ifp);
}
if (ifp->flags & IFA_F_PERMANENT && !(ifp->flags & IFA_F_NOPREFIXROUTE))
action = check_cleanup_prefix_route(ifp, &expires);
list_del_rcu(&ifp->if_list);
__in6_ifa_put(ifp);
write_unlock_bh(&ifp->idev->lock);
addrconf_del_dad_work(ifp);
ipv6_ifa_notify(RTM_DELADDR, ifp);
inet6addr_notifier_call_chain(NETDEV_DOWN, ifp);
if (action != CLEANUP_PREFIX_RT_NOP) {
cleanup_prefix_route(ifp, expires,
action == CLEANUP_PREFIX_RT_DEL, false);
}
/* clean up prefsrc entries */
rt6_remove_prefsrc(ifp);
out:
in6_ifa_put(ifp);
}
static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, bool block)
{
struct inet6_dev *idev = ifp->idev;
unsigned long tmp_tstamp, age;
unsigned long regen_advance;
unsigned long now = jiffies;
s32 cnf_temp_preferred_lft;
struct inet6_ifaddr *ift;
struct ifa6_config cfg;
long max_desync_factor;
struct in6_addr addr;
int ret = 0;
write_lock_bh(&idev->lock);
retry:
in6_dev_hold(idev);
if (idev->cnf.use_tempaddr <= 0) {
write_unlock_bh(&idev->lock);
pr_info("%s: use_tempaddr is disabled\n", __func__);
in6_dev_put(idev);
ret = -1;
goto out;
}
spin_lock_bh(&ifp->lock);
if (ifp->regen_count++ >= idev->cnf.regen_max_retry) {
idev->cnf.use_tempaddr = -1; /*XXX*/
spin_unlock_bh(&ifp->lock);
write_unlock_bh(&idev->lock);
pr_warn("%s: regeneration time exceeded - disabled temporary address support\n",
__func__);
in6_dev_put(idev);
ret = -1;
goto out;
}
in6_ifa_hold(ifp);
memcpy(addr.s6_addr, ifp->addr.s6_addr, 8);
ipv6_gen_rnd_iid(&addr);
age = (now - ifp->tstamp) / HZ;
regen_advance = idev->cnf.regen_max_retry *
idev->cnf.dad_transmits *
max(NEIGH_VAR(idev->nd_parms, RETRANS_TIME), HZ/100) / HZ;
/* recalculate max_desync_factor each time and update
* idev->desync_factor if it's larger
*/
cnf_temp_preferred_lft = READ_ONCE(idev->cnf.temp_prefered_lft);
max_desync_factor = min_t(long,
idev->cnf.max_desync_factor,
cnf_temp_preferred_lft - regen_advance);
if (unlikely(idev->desync_factor > max_desync_factor)) {
if (max_desync_factor > 0) {
get_random_bytes(&idev->desync_factor,
sizeof(idev->desync_factor));
idev->desync_factor %= max_desync_factor;
} else {
idev->desync_factor = 0;
}
}
memset(&cfg, 0, sizeof(cfg));
cfg.valid_lft = min_t(__u32, ifp->valid_lft,
idev->cnf.temp_valid_lft + age);
cfg.preferred_lft = cnf_temp_preferred_lft + age - idev->desync_factor;
cfg.preferred_lft = min_t(__u32, ifp->prefered_lft, cfg.preferred_lft);
cfg.plen = ifp->prefix_len;
tmp_tstamp = ifp->tstamp;
spin_unlock_bh(&ifp->lock);
write_unlock_bh(&idev->lock);
/* A temporary address is created only if this calculated Preferred
* Lifetime is greater than REGEN_ADVANCE time units. In particular,
* an implementation must not create a temporary address with a zero
* Preferred Lifetime.
* Use age calculation as in addrconf_verify to avoid unnecessary
* temporary addresses being generated.
*/
age = (now - tmp_tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ;
if (cfg.preferred_lft <= regen_advance + age) {
in6_ifa_put(ifp);
in6_dev_put(idev);
ret = -1;
goto out;
}
cfg.ifa_flags = IFA_F_TEMPORARY;
/* set in addrconf_prefix_rcv() */
if (ifp->flags & IFA_F_OPTIMISTIC)
cfg.ifa_flags |= IFA_F_OPTIMISTIC;
cfg.pfx = &addr;
cfg.scope = ipv6_addr_scope(cfg.pfx);
ift = ipv6_add_addr(idev, &cfg, block, NULL);
if (IS_ERR(ift)) {
in6_ifa_put(ifp);
in6_dev_put(idev);
pr_info("%s: retry temporary address regeneration\n", __func__);
write_lock_bh(&idev->lock);
goto retry;
}
spin_lock_bh(&ift->lock);
ift->ifpub = ifp;
ift->cstamp = now;
ift->tstamp = tmp_tstamp;
spin_unlock_bh(&ift->lock);
addrconf_dad_start(ift);
in6_ifa_put(ift);
in6_dev_put(idev);
out:
return ret;
}
/*
* Choose an appropriate source address (RFC3484)
*/
enum {
IPV6_SADDR_RULE_INIT = 0,
IPV6_SADDR_RULE_LOCAL,
IPV6_SADDR_RULE_SCOPE,
IPV6_SADDR_RULE_PREFERRED,
#ifdef CONFIG_IPV6_MIP6
IPV6_SADDR_RULE_HOA,
#endif
IPV6_SADDR_RULE_OIF,
IPV6_SADDR_RULE_LABEL,
IPV6_SADDR_RULE_PRIVACY,
IPV6_SADDR_RULE_ORCHID,
IPV6_SADDR_RULE_PREFIX,
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
IPV6_SADDR_RULE_NOT_OPTIMISTIC,
#endif
IPV6_SADDR_RULE_MAX
};
struct ipv6_saddr_score {
int rule;
int addr_type;
struct inet6_ifaddr *ifa;
DECLARE_BITMAP(scorebits, IPV6_SADDR_RULE_MAX);
int scopedist;
int matchlen;
};
struct ipv6_saddr_dst {
const struct in6_addr *addr;
int ifindex;
int scope;
int label;
unsigned int prefs;
};
static inline int ipv6_saddr_preferred(int type)
{
if (type & (IPV6_ADDR_MAPPED|IPV6_ADDR_COMPATv4|IPV6_ADDR_LOOPBACK))
return 1;
return 0;
}
static bool ipv6_use_optimistic_addr(struct net *net,
struct inet6_dev *idev)
{
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
if (!idev)
return false;
if (!net->ipv6.devconf_all->optimistic_dad && !idev->cnf.optimistic_dad)
return false;
if (!net->ipv6.devconf_all->use_optimistic && !idev->cnf.use_optimistic)
return false;
return true;
#else
return false;
#endif
}
static bool ipv6_allow_optimistic_dad(struct net *net,
struct inet6_dev *idev)
{
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
if (!idev)
return false;
if (!net->ipv6.devconf_all->optimistic_dad && !idev->cnf.optimistic_dad)
return false;
return true;
#else
return false;
#endif
}
static int ipv6_get_saddr_eval(struct net *net,
struct ipv6_saddr_score *score,
struct ipv6_saddr_dst *dst,
int i)
{
int ret;
if (i <= score->rule) {
switch (i) {
case IPV6_SADDR_RULE_SCOPE:
ret = score->scopedist;
break;
case IPV6_SADDR_RULE_PREFIX:
ret = score->matchlen;
break;
default:
ret = !!test_bit(i, score->scorebits);
}
goto out;
}
switch (i) {
case IPV6_SADDR_RULE_INIT:
/* Rule 0: remember if hiscore is not ready yet */
ret = !!score->ifa;
break;
case IPV6_SADDR_RULE_LOCAL:
/* Rule 1: Prefer same address */
ret = ipv6_addr_equal(&score->ifa->addr, dst->addr);
break;
case IPV6_SADDR_RULE_SCOPE:
/* Rule 2: Prefer appropriate scope
*
* ret
* ^
* -1 | d 15
* ---+--+-+---> scope
* |
* | d is scope of the destination.
* B-d | \
* | \ <- smaller scope is better if
* B-15 | \ if scope is enough for destination.
* | ret = B - scope (-1 <= scope >= d <= 15).
* d-C-1 | /
* |/ <- greater is better
* -C / if scope is not enough for destination.
* /| ret = scope - C (-1 <= d < scope <= 15).
*
* d - C - 1 < B -15 (for all -1 <= d <= 15).
* C > d + 14 - B >= 15 + 14 - B = 29 - B.
* Assume B = 0 and we get C > 29.
*/
ret = __ipv6_addr_src_scope(score->addr_type);
if (ret >= dst->scope)
ret = -ret;
else
ret -= 128; /* 30 is enough */
score->scopedist = ret;
break;
case IPV6_SADDR_RULE_PREFERRED:
{
/* Rule 3: Avoid deprecated and optimistic addresses */
u8 avoid = IFA_F_DEPRECATED;
if (!ipv6_use_optimistic_addr(net, score->ifa->idev))
avoid |= IFA_F_OPTIMISTIC;
ret = ipv6_saddr_preferred(score->addr_type) ||
!(score->ifa->flags & avoid);
break;
}
#ifdef CONFIG_IPV6_MIP6
case IPV6_SADDR_RULE_HOA:
{
/* Rule 4: Prefer home address */
int prefhome = !(dst->prefs & IPV6_PREFER_SRC_COA);
ret = !(score->ifa->flags & IFA_F_HOMEADDRESS) ^ prefhome;
break;
}
#endif
case IPV6_SADDR_RULE_OIF:
/* Rule 5: Prefer outgoing interface */
ret = (!dst->ifindex ||
dst->ifindex == score->ifa->idev->dev->ifindex);
break;
case IPV6_SADDR_RULE_LABEL:
/* Rule 6: Prefer matching label */
ret = ipv6_addr_label(net,
&score->ifa->addr, score->addr_type,
score->ifa->idev->dev->ifindex) == dst->label;
break;
case IPV6_SADDR_RULE_PRIVACY:
{
/* Rule 7: Prefer public address
* Note: prefer temporary address if use_tempaddr >= 2
*/
int preftmp = dst->prefs & (IPV6_PREFER_SRC_PUBLIC|IPV6_PREFER_SRC_TMP) ?
!!(dst->prefs & IPV6_PREFER_SRC_TMP) :
score->ifa->idev->cnf.use_tempaddr >= 2;
ret = (!(score->ifa->flags & IFA_F_TEMPORARY)) ^ preftmp;
break;
}
case IPV6_SADDR_RULE_ORCHID:
/* Rule 8-: Prefer ORCHID vs ORCHID or
* non-ORCHID vs non-ORCHID
*/
ret = !(ipv6_addr_orchid(&score->ifa->addr) ^
ipv6_addr_orchid(dst->addr));
break;
case IPV6_SADDR_RULE_PREFIX:
/* Rule 8: Use longest matching prefix */
ret = ipv6_addr_diff(&score->ifa->addr, dst->addr);
if (ret > score->ifa->prefix_len)
ret = score->ifa->prefix_len;
score->matchlen = ret;
break;
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
case IPV6_SADDR_RULE_NOT_OPTIMISTIC:
/* Optimistic addresses still have lower precedence than other
* preferred addresses.
*/
ret = !(score->ifa->flags & IFA_F_OPTIMISTIC);
break;
#endif
default:
ret = 0;
}
if (ret)
__set_bit(i, score->scorebits);
score->rule = i;
out:
return ret;
}
static int __ipv6_dev_get_saddr(struct net *net,
struct ipv6_saddr_dst *dst,
struct inet6_dev *idev,
struct ipv6_saddr_score *scores,
int hiscore_idx)
{
struct ipv6_saddr_score *score = &scores[1 - hiscore_idx], *hiscore = &scores[hiscore_idx];
list_for_each_entry_rcu(score->ifa, &idev->addr_list, if_list) {
int i;
/*
* - Tentative Address (RFC2462 section 5.4)
* - A tentative address is not considered
* "assigned to an interface" in the traditional
* sense, unless it is also flagged as optimistic.
* - Candidate Source Address (section 4)
* - In any case, anycast addresses, multicast
* addresses, and the unspecified address MUST
* NOT be included in a candidate set.
*/
if ((score->ifa->flags & IFA_F_TENTATIVE) &&
(!(score->ifa->flags & IFA_F_OPTIMISTIC)))
continue;
score->addr_type = __ipv6_addr_type(&score->ifa->addr);
if (unlikely(score->addr_type == IPV6_ADDR_ANY ||
score->addr_type & IPV6_ADDR_MULTICAST)) {
net_dbg_ratelimited("ADDRCONF: unspecified / multicast address assigned as unicast address on %s",
idev->dev->name);
continue;
}
score->rule = -1;
bitmap_zero(score->scorebits, IPV6_SADDR_RULE_MAX);
for (i = 0; i < IPV6_SADDR_RULE_MAX; i++) {
int minihiscore, miniscore;
minihiscore = ipv6_get_saddr_eval(net, hiscore, dst, i);
miniscore = ipv6_get_saddr_eval(net, score, dst, i);
if (minihiscore > miniscore) {
if (i == IPV6_SADDR_RULE_SCOPE &&
score->scopedist > 0) {
/*
* special case:
* each remaining entry
* has too small (not enough)
* scope, because ifa entries
* are sorted by their scope
* values.
*/
goto out;
}
break;
} else if (minihiscore < miniscore) {
swap(hiscore, score);
hiscore_idx = 1 - hiscore_idx;
/* restore our iterator */
score->ifa = hiscore->ifa;
break;
}
}
}
out:
return hiscore_idx;
}
static int ipv6_get_saddr_master(struct net *net,
const struct net_device *dst_dev,
const struct net_device *master,
struct ipv6_saddr_dst *dst,
struct ipv6_saddr_score *scores,
int hiscore_idx)
{
struct inet6_dev *idev;
idev = __in6_dev_get(dst_dev);
if (idev)
hiscore_idx = __ipv6_dev_get_saddr(net, dst, idev,
scores, hiscore_idx);
idev = __in6_dev_get(master);
if (idev)
hiscore_idx = __ipv6_dev_get_saddr(net, dst, idev,
scores, hiscore_idx);
return hiscore_idx;
}
int ipv6_dev_get_saddr(struct net *net, const struct net_device *dst_dev,
const struct in6_addr *daddr, unsigned int prefs,
struct in6_addr *saddr)
{
struct ipv6_saddr_score scores[2], *hiscore;
struct ipv6_saddr_dst dst;
struct inet6_dev *idev;
struct net_device *dev;
int dst_type;
bool use_oif_addr = false;
int hiscore_idx = 0;
int ret = 0;
dst_type = __ipv6_addr_type(daddr);
dst.addr = daddr;
dst.ifindex = dst_dev ? dst_dev->ifindex : 0;
dst.scope = __ipv6_addr_src_scope(dst_type);
dst.label = ipv6_addr_label(net, daddr, dst_type, dst.ifindex);
dst.prefs = prefs;
scores[hiscore_idx].rule = -1;
scores[hiscore_idx].ifa = NULL;
rcu_read_lock();
/* Candidate Source Address (section 4)
* - multicast and link-local destination address,
* the set of candidate source address MUST only
* include addresses assigned to interfaces
* belonging to the same link as the outgoing
* interface.
* (- For site-local destination addresses, the
* set of candidate source addresses MUST only
* include addresses assigned to interfaces
* belonging to the same site as the outgoing
* interface.)
* - "It is RECOMMENDED that the candidate source addresses
* be the set of unicast addresses assigned to the
* interface that will be used to send to the destination
* (the 'outgoing' interface)." (RFC 6724)
*/
if (dst_dev) {
idev = __in6_dev_get(dst_dev);
if ((dst_type & IPV6_ADDR_MULTICAST) ||
dst.scope <= IPV6_ADDR_SCOPE_LINKLOCAL ||
(idev && idev->cnf.use_oif_addrs_only)) {
use_oif_addr = true;
}
}
if (use_oif_addr) {
if (idev)
hiscore_idx = __ipv6_dev_get_saddr(net, &dst, idev, scores, hiscore_idx);
} else {
const struct net_device *master;
int master_idx = 0;
/* if dst_dev exists and is enslaved to an L3 device, then
* prefer addresses from dst_dev and then the master over
* any other enslaved devices in the L3 domain.
*/
master = l3mdev_master_dev_rcu(dst_dev);
if (master) {
master_idx = master->ifindex;
hiscore_idx = ipv6_get_saddr_master(net, dst_dev,
master, &dst,
scores, hiscore_idx);
if (scores[hiscore_idx].ifa)
goto out;
}
for_each_netdev_rcu(net, dev) {
/* only consider addresses on devices in the
* same L3 domain
*/
if (l3mdev_master_ifindex_rcu(dev) != master_idx)
continue;
idev = __in6_dev_get(dev);
if (!idev)
continue;
hiscore_idx = __ipv6_dev_get_saddr(net, &dst, idev, scores, hiscore_idx);
}
}
out:
hiscore = &scores[hiscore_idx];
if (!hiscore->ifa)
ret = -EADDRNOTAVAIL;
else
*saddr = hiscore->ifa->addr;
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL(ipv6_dev_get_saddr);
static int __ipv6_get_lladdr(struct inet6_dev *idev, struct in6_addr *addr,
u32 banned_flags)
{
struct inet6_ifaddr *ifp;
int err = -EADDRNOTAVAIL;
list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) {
if (ifp->scope > IFA_LINK)
break;
if (ifp->scope == IFA_LINK &&
!(ifp->flags & banned_flags)) {
*addr = ifp->addr;
err = 0;
break;
}
}
return err;
}
int ipv6_get_lladdr(struct net_device *dev, struct in6_addr *addr,
u32 banned_flags)
{
struct inet6_dev *idev;
int err = -EADDRNOTAVAIL;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev) {
read_lock_bh(&idev->lock);
err = __ipv6_get_lladdr(idev, addr, banned_flags);
read_unlock_bh(&idev->lock);
}
rcu_read_unlock();
return err;
}
static int ipv6_count_addresses(const struct inet6_dev *idev)
{
const struct inet6_ifaddr *ifp;
int cnt = 0;
rcu_read_lock();
list_for_each_entry_rcu(ifp, &idev->addr_list, if_list)
cnt++;
rcu_read_unlock();
return cnt;
}
int ipv6_chk_addr(struct net *net, const struct in6_addr *addr,
const struct net_device *dev, int strict)
{
return ipv6_chk_addr_and_flags(net, addr, dev, !dev,
strict, IFA_F_TENTATIVE);
}
EXPORT_SYMBOL(ipv6_chk_addr);
/* device argument is used to find the L3 domain of interest. If
* skip_dev_check is set, then the ifp device is not checked against
* the passed in dev argument. So the 2 cases for addresses checks are:
* 1. does the address exist in the L3 domain that dev is part of
* (skip_dev_check = true), or
*
* 2. does the address exist on the specific device
* (skip_dev_check = false)
*/
static struct net_device *
__ipv6_chk_addr_and_flags(struct net *net, const struct in6_addr *addr,
const struct net_device *dev, bool skip_dev_check,
int strict, u32 banned_flags)
{
unsigned int hash = inet6_addr_hash(net, addr);
struct net_device *l3mdev, *ndev;
struct inet6_ifaddr *ifp;
u32 ifp_flags;
rcu_read_lock();
l3mdev = l3mdev_master_dev_rcu(dev);
if (skip_dev_check)
dev = NULL;
hlist_for_each_entry_rcu(ifp, &net->ipv6.inet6_addr_lst[hash], addr_lst) {
ndev = ifp->idev->dev;
if (l3mdev_master_dev_rcu(ndev) != l3mdev)
continue;
/* Decouple optimistic from tentative for evaluation here.
* Ban optimistic addresses explicitly, when required.
*/
ifp_flags = (ifp->flags&IFA_F_OPTIMISTIC)
? (ifp->flags&~IFA_F_TENTATIVE)
: ifp->flags;
if (ipv6_addr_equal(&ifp->addr, addr) &&
!(ifp_flags&banned_flags) &&
(!dev || ndev == dev ||
!(ifp->scope&(IFA_LINK|IFA_HOST) || strict))) {
rcu_read_unlock();
return ndev;
}
}
rcu_read_unlock();
return NULL;
}
int ipv6_chk_addr_and_flags(struct net *net, const struct in6_addr *addr,
const struct net_device *dev, bool skip_dev_check,
int strict, u32 banned_flags)
{
return __ipv6_chk_addr_and_flags(net, addr, dev, skip_dev_check,
strict, banned_flags) ? 1 : 0;
}
EXPORT_SYMBOL(ipv6_chk_addr_and_flags);
/* Compares an address/prefix_len with addresses on device @dev.
* If one is found it returns true.
*/
bool ipv6_chk_custom_prefix(const struct in6_addr *addr,
const unsigned int prefix_len, struct net_device *dev)
{
const struct inet6_ifaddr *ifa;
const struct inet6_dev *idev;
bool ret = false;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev) {
list_for_each_entry_rcu(ifa, &idev->addr_list, if_list) {
ret = ipv6_prefix_equal(addr, &ifa->addr, prefix_len);
if (ret)
break;
}
}
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL(ipv6_chk_custom_prefix);
int ipv6_chk_prefix(const struct in6_addr *addr, struct net_device *dev)
{
const struct inet6_ifaddr *ifa;
const struct inet6_dev *idev;
int onlink;
onlink = 0;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev) {
list_for_each_entry_rcu(ifa, &idev->addr_list, if_list) {
onlink = ipv6_prefix_equal(addr, &ifa->addr,
ifa->prefix_len);
if (onlink)
break;
}
}
rcu_read_unlock();
return onlink;
}
EXPORT_SYMBOL(ipv6_chk_prefix);
/**
* ipv6_dev_find - find the first device with a given source address.
* @net: the net namespace
* @addr: the source address
* @dev: used to find the L3 domain of interest
*
* The caller should be protected by RCU, or RTNL.
*/
struct net_device *ipv6_dev_find(struct net *net, const struct in6_addr *addr,
struct net_device *dev)
{
return __ipv6_chk_addr_and_flags(net, addr, dev, !dev, 1,
IFA_F_TENTATIVE);
}
EXPORT_SYMBOL(ipv6_dev_find);
struct inet6_ifaddr *ipv6_get_ifaddr(struct net *net, const struct in6_addr *addr,
struct net_device *dev, int strict)
{
unsigned int hash = inet6_addr_hash(net, addr);
struct inet6_ifaddr *ifp, *result = NULL;
rcu_read_lock();
hlist_for_each_entry_rcu(ifp, &net->ipv6.inet6_addr_lst[hash], addr_lst) {
if (ipv6_addr_equal(&ifp->addr, addr)) {
if (!dev || ifp->idev->dev == dev ||
!(ifp->scope&(IFA_LINK|IFA_HOST) || strict)) {
result = ifp;
in6_ifa_hold(ifp);
break;
}
}
}
rcu_read_unlock();
return result;
}
/* Gets referenced address, destroys ifaddr */
static void addrconf_dad_stop(struct inet6_ifaddr *ifp, int dad_failed)
{
if (dad_failed)
ifp->flags |= IFA_F_DADFAILED;
if (ifp->flags&IFA_F_TEMPORARY) {
struct inet6_ifaddr *ifpub;
spin_lock_bh(&ifp->lock);
ifpub = ifp->ifpub;
if (ifpub) {
in6_ifa_hold(ifpub);
spin_unlock_bh(&ifp->lock);
ipv6_create_tempaddr(ifpub, true);
in6_ifa_put(ifpub);
} else {
spin_unlock_bh(&ifp->lock);
}
ipv6_del_addr(ifp);
} else if (ifp->flags&IFA_F_PERMANENT || !dad_failed) {
spin_lock_bh(&ifp->lock);
addrconf_del_dad_work(ifp);
ifp->flags |= IFA_F_TENTATIVE;
if (dad_failed)
ifp->flags &= ~IFA_F_OPTIMISTIC;
spin_unlock_bh(&ifp->lock);
if (dad_failed)
ipv6_ifa_notify(0, ifp);
in6_ifa_put(ifp);
} else {
ipv6_del_addr(ifp);
}
}
static int addrconf_dad_end(struct inet6_ifaddr *ifp)
{
int err = -ENOENT;
spin_lock_bh(&ifp->lock);
if (ifp->state == INET6_IFADDR_STATE_DAD) {
ifp->state = INET6_IFADDR_STATE_POSTDAD;
err = 0;
}
spin_unlock_bh(&ifp->lock);
return err;
}
void addrconf_dad_failure(struct sk_buff *skb, struct inet6_ifaddr *ifp)
{
struct inet6_dev *idev = ifp->idev;
struct net *net = dev_net(idev->dev);
if (addrconf_dad_end(ifp)) {
in6_ifa_put(ifp);
return;
}
net_info_ratelimited("%s: IPv6 duplicate address %pI6c used by %pM detected!\n",
ifp->idev->dev->name, &ifp->addr, eth_hdr(skb)->h_source);
spin_lock_bh(&ifp->lock);
if (ifp->flags & IFA_F_STABLE_PRIVACY) {
struct in6_addr new_addr;
struct inet6_ifaddr *ifp2;
int retries = ifp->stable_privacy_retry + 1;
struct ifa6_config cfg = {
.pfx = &new_addr,
.plen = ifp->prefix_len,
.ifa_flags = ifp->flags,
.valid_lft = ifp->valid_lft,
.preferred_lft = ifp->prefered_lft,
.scope = ifp->scope,
};
if (retries > net->ipv6.sysctl.idgen_retries) {
net_info_ratelimited("%s: privacy stable address generation failed because of DAD conflicts!\n",
ifp->idev->dev->name);
goto errdad;
}
new_addr = ifp->addr;
if (ipv6_generate_stable_address(&new_addr, retries,
idev))
goto errdad;
spin_unlock_bh(&ifp->lock);
if (idev->cnf.max_addresses &&
ipv6_count_addresses(idev) >=
idev->cnf.max_addresses)
goto lock_errdad;
net_info_ratelimited("%s: generating new stable privacy address because of DAD conflict\n",
ifp->idev->dev->name);
ifp2 = ipv6_add_addr(idev, &cfg, false, NULL);
if (IS_ERR(ifp2))
goto lock_errdad;
spin_lock_bh(&ifp2->lock);
ifp2->stable_privacy_retry = retries;
ifp2->state = INET6_IFADDR_STATE_PREDAD;
spin_unlock_bh(&ifp2->lock);
addrconf_mod_dad_work(ifp2, net->ipv6.sysctl.idgen_delay);
in6_ifa_put(ifp2);
lock_errdad:
spin_lock_bh(&ifp->lock);
}
errdad:
/* transition from _POSTDAD to _ERRDAD */
ifp->state = INET6_IFADDR_STATE_ERRDAD;
spin_unlock_bh(&ifp->lock);
addrconf_mod_dad_work(ifp, 0);
in6_ifa_put(ifp);
}
/* Join to solicited addr multicast group.
* caller must hold RTNL */
void addrconf_join_solict(struct net_device *dev, const struct in6_addr *addr)
{
struct in6_addr maddr;
if (dev->flags&(IFF_LOOPBACK|IFF_NOARP))
return;
addrconf_addr_solict_mult(addr, &maddr);
ipv6_dev_mc_inc(dev, &maddr);
}
/* caller must hold RTNL */
void addrconf_leave_solict(struct inet6_dev *idev, const struct in6_addr *addr)
{
struct in6_addr maddr;
if (idev->dev->flags&(IFF_LOOPBACK|IFF_NOARP))
return;
addrconf_addr_solict_mult(addr, &maddr);
__ipv6_dev_mc_dec(idev, &maddr);
}
/* caller must hold RTNL */
static void addrconf_join_anycast(struct inet6_ifaddr *ifp)
{
struct in6_addr addr;
if (ifp->prefix_len >= 127) /* RFC 6164 */
return;
ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len);
if (ipv6_addr_any(&addr))
return;
__ipv6_dev_ac_inc(ifp->idev, &addr);
}
/* caller must hold RTNL */
static void addrconf_leave_anycast(struct inet6_ifaddr *ifp)
{
struct in6_addr addr;
if (ifp->prefix_len >= 127) /* RFC 6164 */
return;
ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len);
if (ipv6_addr_any(&addr))
return;
__ipv6_dev_ac_dec(ifp->idev, &addr);
}
static int addrconf_ifid_6lowpan(u8 *eui, struct net_device *dev)
{
switch (dev->addr_len) {
case ETH_ALEN:
memcpy(eui, dev->dev_addr, 3);
eui[3] = 0xFF;
eui[4] = 0xFE;
memcpy(eui + 5, dev->dev_addr + 3, 3);
break;
case EUI64_ADDR_LEN:
memcpy(eui, dev->dev_addr, EUI64_ADDR_LEN);
eui[0] ^= 2;
break;
default:
return -1;
}
return 0;
}
static int addrconf_ifid_ieee1394(u8 *eui, struct net_device *dev)
{
const union fwnet_hwaddr *ha;
if (dev->addr_len != FWNET_ALEN)
return -1;
ha = (const union fwnet_hwaddr *)dev->dev_addr;
memcpy(eui, &ha->uc.uniq_id, sizeof(ha->uc.uniq_id));
eui[0] ^= 2;
return 0;
}
static int addrconf_ifid_arcnet(u8 *eui, struct net_device *dev)
{
/* XXX: inherit EUI-64 from other interface -- yoshfuji */
if (dev->addr_len != ARCNET_ALEN)
return -1;
memset(eui, 0, 7);
eui[7] = *(u8 *)dev->dev_addr;
return 0;
}
static int addrconf_ifid_infiniband(u8 *eui, struct net_device *dev)
{
if (dev->addr_len != INFINIBAND_ALEN)
return -1;
memcpy(eui, dev->dev_addr + 12, 8);
eui[0] |= 2;
return 0;
}
static int __ipv6_isatap_ifid(u8 *eui, __be32 addr)
{
if (addr == 0)
return -1;
eui[0] = (ipv4_is_zeronet(addr) || ipv4_is_private_10(addr) ||
ipv4_is_loopback(addr) || ipv4_is_linklocal_169(addr) ||
ipv4_is_private_172(addr) || ipv4_is_test_192(addr) ||
ipv4_is_anycast_6to4(addr) || ipv4_is_private_192(addr) ||
ipv4_is_test_198(addr) || ipv4_is_multicast(addr) ||
ipv4_is_lbcast(addr)) ? 0x00 : 0x02;
eui[1] = 0;
eui[2] = 0x5E;
eui[3] = 0xFE;
memcpy(eui + 4, &addr, 4);
return 0;
}
static int addrconf_ifid_sit(u8 *eui, struct net_device *dev)
{
if (dev->priv_flags & IFF_ISATAP)
return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr);
return -1;
}
static int addrconf_ifid_gre(u8 *eui, struct net_device *dev)
{
return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr);
}
static int addrconf_ifid_ip6tnl(u8 *eui, struct net_device *dev)
{
memcpy(eui, dev->perm_addr, 3);
memcpy(eui + 5, dev->perm_addr + 3, 3);
eui[3] = 0xFF;
eui[4] = 0xFE;
eui[0] ^= 2;
return 0;
}
static int ipv6_generate_eui64(u8 *eui, struct net_device *dev)
{
switch (dev->type) {
case ARPHRD_ETHER:
case ARPHRD_FDDI:
return addrconf_ifid_eui48(eui, dev);
case ARPHRD_ARCNET:
return addrconf_ifid_arcnet(eui, dev);
case ARPHRD_INFINIBAND:
return addrconf_ifid_infiniband(eui, dev);
case ARPHRD_SIT:
return addrconf_ifid_sit(eui, dev);
case ARPHRD_IPGRE:
case ARPHRD_TUNNEL:
return addrconf_ifid_gre(eui, dev);
case ARPHRD_6LOWPAN:
return addrconf_ifid_6lowpan(eui, dev);
case ARPHRD_IEEE1394:
return addrconf_ifid_ieee1394(eui, dev);
case ARPHRD_TUNNEL6:
case ARPHRD_IP6GRE:
case ARPHRD_RAWIP:
return addrconf_ifid_ip6tnl(eui, dev);
}
return -1;
}
static int ipv6_inherit_eui64(u8 *eui, struct inet6_dev *idev)
{
int err = -1;
struct inet6_ifaddr *ifp;
read_lock_bh(&idev->lock);
list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) {
if (ifp->scope > IFA_LINK)
break;
if (ifp->scope == IFA_LINK && !(ifp->flags&IFA_F_TENTATIVE)) {
memcpy(eui, ifp->addr.s6_addr+8, 8);
err = 0;
break;
}
}
read_unlock_bh(&idev->lock);
return err;
}
/* Generation of a randomized Interface Identifier
* draft-ietf-6man-rfc4941bis, Section 3.3.1
*/
static void ipv6_gen_rnd_iid(struct in6_addr *addr)
{
regen:
get_random_bytes(&addr->s6_addr[8], 8);
/* <draft-ietf-6man-rfc4941bis-08.txt>, Section 3.3.1:
* check if generated address is not inappropriate:
*
* - Reserved IPv6 Interface Identifiers
* - XXX: already assigned to an address on the device
*/
/* Subnet-router anycast: 0000:0000:0000:0000 */
if (!(addr->s6_addr32[2] | addr->s6_addr32[3]))
goto regen;
/* IANA Ethernet block: 0200:5EFF:FE00:0000-0200:5EFF:FE00:5212
* Proxy Mobile IPv6: 0200:5EFF:FE00:5213
* IANA Ethernet block: 0200:5EFF:FE00:5214-0200:5EFF:FEFF:FFFF
*/
if (ntohl(addr->s6_addr32[2]) == 0x02005eff &&
(ntohl(addr->s6_addr32[3]) & 0Xff000000) == 0xfe000000)
goto regen;
/* Reserved subnet anycast addresses */
if (ntohl(addr->s6_addr32[2]) == 0xfdffffff &&
ntohl(addr->s6_addr32[3]) >= 0Xffffff80)
goto regen;
}
/*
* Add prefix route.
*/
static void
addrconf_prefix_route(struct in6_addr *pfx, int plen, u32 metric,
struct net_device *dev, unsigned long expires,
u32 flags, gfp_t gfp_flags)
{
struct fib6_config cfg = {
.fc_table = l3mdev_fib_table(dev) ? : RT6_TABLE_PREFIX,
.fc_metric = metric ? : IP6_RT_PRIO_ADDRCONF,
.fc_ifindex = dev->ifindex,
.fc_expires = expires,
.fc_dst_len = plen,
.fc_flags = RTF_UP | flags,
.fc_nlinfo.nl_net = dev_net(dev),
.fc_protocol = RTPROT_KERNEL,
.fc_type = RTN_UNICAST,
};
cfg.fc_dst = *pfx;
/* Prevent useless cloning on PtP SIT.
This thing is done here expecting that the whole
class of non-broadcast devices need not cloning.
*/
#if IS_ENABLED(CONFIG_IPV6_SIT)
if (dev->type == ARPHRD_SIT && (dev->flags & IFF_POINTOPOINT))
cfg.fc_flags |= RTF_NONEXTHOP;
#endif
ip6_route_add(&cfg, gfp_flags, NULL);
}
static struct fib6_info *addrconf_get_prefix_route(const struct in6_addr *pfx,
int plen,
const struct net_device *dev,
u32 flags, u32 noflags,
bool no_gw)
{
struct fib6_node *fn;
struct fib6_info *rt = NULL;
struct fib6_table *table;
u32 tb_id = l3mdev_fib_table(dev) ? : RT6_TABLE_PREFIX;
table = fib6_get_table(dev_net(dev), tb_id);
if (!table)
return NULL;
rcu_read_lock();
fn = fib6_locate(&table->tb6_root, pfx, plen, NULL, 0, true);
if (!fn)
goto out;
for_each_fib6_node_rt_rcu(fn) {
/* prefix routes only use builtin fib6_nh */
if (rt->nh)
continue;
if (rt->fib6_nh->fib_nh_dev->ifindex != dev->ifindex)
continue;
if (no_gw && rt->fib6_nh->fib_nh_gw_family)
continue;
if ((rt->fib6_flags & flags) != flags)
continue;
if ((rt->fib6_flags & noflags) != 0)
continue;
if (!fib6_info_hold_safe(rt))
continue;
break;
}
out:
rcu_read_unlock();
return rt;
}
/* Create "default" multicast route to the interface */
static void addrconf_add_mroute(struct net_device *dev)
{
struct fib6_config cfg = {
.fc_table = l3mdev_fib_table(dev) ? : RT6_TABLE_LOCAL,
.fc_metric = IP6_RT_PRIO_ADDRCONF,
.fc_ifindex = dev->ifindex,
.fc_dst_len = 8,
.fc_flags = RTF_UP,
.fc_type = RTN_MULTICAST,
.fc_nlinfo.nl_net = dev_net(dev),
.fc_protocol = RTPROT_KERNEL,
};
ipv6_addr_set(&cfg.fc_dst, htonl(0xFF000000), 0, 0, 0);
ip6_route_add(&cfg, GFP_KERNEL, NULL);
}
static struct inet6_dev *addrconf_add_dev(struct net_device *dev)
{
struct inet6_dev *idev;
ASSERT_RTNL();
idev = ipv6_find_idev(dev);
if (IS_ERR(idev))
return idev;
if (idev->cnf.disable_ipv6)
return ERR_PTR(-EACCES);
/* Add default multicast route */
if (!(dev->flags & IFF_LOOPBACK) && !netif_is_l3_master(dev))
addrconf_add_mroute(dev);
return idev;
}
static void manage_tempaddrs(struct inet6_dev *idev,
struct inet6_ifaddr *ifp,
__u32 valid_lft, __u32 prefered_lft,
bool create, unsigned long now)
{
u32 flags;
struct inet6_ifaddr *ift;
read_lock_bh(&idev->lock);
/* update all temporary addresses in the list */
list_for_each_entry(ift, &idev->tempaddr_list, tmp_list) {
int age, max_valid, max_prefered;
if (ifp != ift->ifpub)
continue;
/* RFC 4941 section 3.3:
* If a received option will extend the lifetime of a public
* address, the lifetimes of temporary addresses should
* be extended, subject to the overall constraint that no
* temporary addresses should ever remain "valid" or "preferred"
* for a time longer than (TEMP_VALID_LIFETIME) or
* (TEMP_PREFERRED_LIFETIME - DESYNC_FACTOR), respectively.
*/
age = (now - ift->cstamp) / HZ;
max_valid = idev->cnf.temp_valid_lft - age;
if (max_valid < 0)
max_valid = 0;
max_prefered = idev->cnf.temp_prefered_lft -
idev->desync_factor - age;
if (max_prefered < 0)
max_prefered = 0;
if (valid_lft > max_valid)
valid_lft = max_valid;
if (prefered_lft > max_prefered)
prefered_lft = max_prefered;
spin_lock(&ift->lock);
flags = ift->flags;
ift->valid_lft = valid_lft;
ift->prefered_lft = prefered_lft;
ift->tstamp = now;
if (prefered_lft > 0)
ift->flags &= ~IFA_F_DEPRECATED;
spin_unlock(&ift->lock);
if (!(flags&IFA_F_TENTATIVE))
ipv6_ifa_notify(0, ift);
}
/* Also create a temporary address if it's enabled but no temporary
* address currently exists.
* However, we get called with valid_lft == 0, prefered_lft == 0, create == false
* as part of cleanup (ie. deleting the mngtmpaddr).
* We don't want that to result in creating a new temporary ip address.
*/
if (list_empty(&idev->tempaddr_list) && (valid_lft || prefered_lft))
create = true;
if (create && idev->cnf.use_tempaddr > 0) {
/* When a new public address is created as described
* in [ADDRCONF], also create a new temporary address.
*/
read_unlock_bh(&idev->lock);
ipv6_create_tempaddr(ifp, false);
} else {
read_unlock_bh(&idev->lock);
}
}
static bool is_addr_mode_generate_stable(struct inet6_dev *idev)
{
return idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_STABLE_PRIVACY ||
idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_RANDOM;
}
int addrconf_prefix_rcv_add_addr(struct net *net, struct net_device *dev,
const struct prefix_info *pinfo,
struct inet6_dev *in6_dev,
const struct in6_addr *addr, int addr_type,
u32 addr_flags, bool sllao, bool tokenized,
__u32 valid_lft, u32 prefered_lft)
{
struct inet6_ifaddr *ifp = ipv6_get_ifaddr(net, addr, dev, 1);
int create = 0, update_lft = 0;
if (!ifp && valid_lft) {
int max_addresses = in6_dev->cnf.max_addresses;
struct ifa6_config cfg = {
.pfx = addr,
.plen = pinfo->prefix_len,
.ifa_flags = addr_flags,
.valid_lft = valid_lft,
.preferred_lft = prefered_lft,
.scope = addr_type & IPV6_ADDR_SCOPE_MASK,
.ifa_proto = IFAPROT_KERNEL_RA
};
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
if ((net->ipv6.devconf_all->optimistic_dad ||
in6_dev->cnf.optimistic_dad) &&
!net->ipv6.devconf_all->forwarding && sllao)
cfg.ifa_flags |= IFA_F_OPTIMISTIC;
#endif
/* Do not allow to create too much of autoconfigured
* addresses; this would be too easy way to crash kernel.
*/
if (!max_addresses ||
ipv6_count_addresses(in6_dev) < max_addresses)
ifp = ipv6_add_addr(in6_dev, &cfg, false, NULL);
if (IS_ERR_OR_NULL(ifp))
return -1;
create = 1;
spin_lock_bh(&ifp->lock);
ifp->flags |= IFA_F_MANAGETEMPADDR;
ifp->cstamp = jiffies;
ifp->tokenized = tokenized;
spin_unlock_bh(&ifp->lock);
addrconf_dad_start(ifp);
}
if (ifp) {
u32 flags;
unsigned long now;
u32 stored_lft;
/* update lifetime (RFC2462 5.5.3 e) */
spin_lock_bh(&ifp->lock);
now = jiffies;
if (ifp->valid_lft > (now - ifp->tstamp) / HZ)
stored_lft = ifp->valid_lft - (now - ifp->tstamp) / HZ;
else
stored_lft = 0;
if (!create && stored_lft) {
const u32 minimum_lft = min_t(u32,
stored_lft, MIN_VALID_LIFETIME);
valid_lft = max(valid_lft, minimum_lft);
/* RFC4862 Section 5.5.3e:
* "Note that the preferred lifetime of the
* corresponding address is always reset to
* the Preferred Lifetime in the received
* Prefix Information option, regardless of
* whether the valid lifetime is also reset or
* ignored."
*
* So we should always update prefered_lft here.
*/
update_lft = 1;
}
if (update_lft) {
ifp->valid_lft = valid_lft;
ifp->prefered_lft = prefered_lft;
ifp->tstamp = now;
flags = ifp->flags;
ifp->flags &= ~IFA_F_DEPRECATED;
spin_unlock_bh(&ifp->lock);
if (!(flags&IFA_F_TENTATIVE))
ipv6_ifa_notify(0, ifp);
} else
spin_unlock_bh(&ifp->lock);
manage_tempaddrs(in6_dev, ifp, valid_lft, prefered_lft,
create, now);
in6_ifa_put(ifp);
addrconf_verify(net);
}
return 0;
}
EXPORT_SYMBOL_GPL(addrconf_prefix_rcv_add_addr);
void addrconf_prefix_rcv(struct net_device *dev, u8 *opt, int len, bool sllao)
{
struct prefix_info *pinfo;
__u32 valid_lft;
__u32 prefered_lft;
int addr_type, err;
u32 addr_flags = 0;
struct inet6_dev *in6_dev;
struct net *net = dev_net(dev);
pinfo = (struct prefix_info *) opt;
if (len < sizeof(struct prefix_info)) {
netdev_dbg(dev, "addrconf: prefix option too short\n");
return;
}
/*
* Validation checks ([ADDRCONF], page 19)
*/
addr_type = ipv6_addr_type(&pinfo->prefix);
if (addr_type & (IPV6_ADDR_MULTICAST|IPV6_ADDR_LINKLOCAL))
return;
valid_lft = ntohl(pinfo->valid);
prefered_lft = ntohl(pinfo->prefered);
if (prefered_lft > valid_lft) {
net_warn_ratelimited("addrconf: prefix option has invalid lifetime\n");
return;
}
in6_dev = in6_dev_get(dev);
if (!in6_dev) {
net_dbg_ratelimited("addrconf: device %s not configured\n",
dev->name);
return;
}
if (valid_lft != 0 && valid_lft < in6_dev->cnf.accept_ra_min_lft)
goto put;
/*
* Two things going on here:
* 1) Add routes for on-link prefixes
* 2) Configure prefixes with the auto flag set
*/
if (pinfo->onlink) {
struct fib6_info *rt;
unsigned long rt_expires;
/* Avoid arithmetic overflow. Really, we could
* save rt_expires in seconds, likely valid_lft,
* but it would require division in fib gc, that it
* not good.
*/
if (HZ > USER_HZ)
rt_expires = addrconf_timeout_fixup(valid_lft, HZ);
else
rt_expires = addrconf_timeout_fixup(valid_lft, USER_HZ);
if (addrconf_finite_timeout(rt_expires))
rt_expires *= HZ;
rt = addrconf_get_prefix_route(&pinfo->prefix,
pinfo->prefix_len,
dev,
RTF_ADDRCONF | RTF_PREFIX_RT,
RTF_DEFAULT, true);
if (rt) {
/* Autoconf prefix route */
if (valid_lft == 0) {
ip6_del_rt(net, rt, false);
rt = NULL;
} else if (addrconf_finite_timeout(rt_expires)) {
/* not infinity */
fib6_set_expires(rt, jiffies + rt_expires);
} else {
fib6_clean_expires(rt);
}
} else if (valid_lft) {
clock_t expires = 0;
int flags = RTF_ADDRCONF | RTF_PREFIX_RT;
if (addrconf_finite_timeout(rt_expires)) {
/* not infinity */
flags |= RTF_EXPIRES;
expires = jiffies_to_clock_t(rt_expires);
}
addrconf_prefix_route(&pinfo->prefix, pinfo->prefix_len,
0, dev, expires, flags,
GFP_ATOMIC);
}
fib6_info_release(rt);
}
/* Try to figure out our local address for this prefix */
if (pinfo->autoconf && in6_dev->cnf.autoconf) {
struct in6_addr addr;
bool tokenized = false, dev_addr_generated = false;
if (pinfo->prefix_len == 64) {
memcpy(&addr, &pinfo->prefix, 8);
if (!ipv6_addr_any(&in6_dev->token)) {
read_lock_bh(&in6_dev->lock);
memcpy(addr.s6_addr + 8,
in6_dev->token.s6_addr + 8, 8);
read_unlock_bh(&in6_dev->lock);
tokenized = true;
} else if (is_addr_mode_generate_stable(in6_dev) &&
!ipv6_generate_stable_address(&addr, 0,
in6_dev)) {
addr_flags |= IFA_F_STABLE_PRIVACY;
goto ok;
} else if (ipv6_generate_eui64(addr.s6_addr + 8, dev) &&
ipv6_inherit_eui64(addr.s6_addr + 8, in6_dev)) {
goto put;
} else {
dev_addr_generated = true;
}
goto ok;
}
net_dbg_ratelimited("IPv6 addrconf: prefix with wrong length %d\n",
pinfo->prefix_len);
goto put;
ok:
err = addrconf_prefix_rcv_add_addr(net, dev, pinfo, in6_dev,
&addr, addr_type,
addr_flags, sllao,
tokenized, valid_lft,
prefered_lft);
if (err)
goto put;
/* Ignore error case here because previous prefix add addr was
* successful which will be notified.
*/
ndisc_ops_prefix_rcv_add_addr(net, dev, pinfo, in6_dev, &addr,
addr_type, addr_flags, sllao,
tokenized, valid_lft,
prefered_lft,
dev_addr_generated);
}
inet6_prefix_notify(RTM_NEWPREFIX, in6_dev, pinfo);
put:
in6_dev_put(in6_dev);
}
static int addrconf_set_sit_dstaddr(struct net *net, struct net_device *dev,
struct in6_ifreq *ireq)
{
struct ip_tunnel_parm p = { };
int err;
if (!(ipv6_addr_type(&ireq->ifr6_addr) & IPV6_ADDR_COMPATv4))
return -EADDRNOTAVAIL;
p.iph.daddr = ireq->ifr6_addr.s6_addr32[3];
p.iph.version = 4;
p.iph.ihl = 5;
p.iph.protocol = IPPROTO_IPV6;
p.iph.ttl = 64;
if (!dev->netdev_ops->ndo_tunnel_ctl)
return -EOPNOTSUPP;
err = dev->netdev_ops->ndo_tunnel_ctl(dev, &p, SIOCADDTUNNEL);
if (err)
return err;
dev = __dev_get_by_name(net, p.name);
if (!dev)
return -ENOBUFS;
return dev_open(dev, NULL);
}
/*
* Set destination address.
* Special case for SIT interfaces where we create a new "virtual"
* device.
*/
int addrconf_set_dstaddr(struct net *net, void __user *arg)
{
struct net_device *dev;
struct in6_ifreq ireq;
int err = -ENODEV;
if (!IS_ENABLED(CONFIG_IPV6_SIT))
return -ENODEV;
if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
return -EFAULT;
rtnl_lock();
dev = __dev_get_by_index(net, ireq.ifr6_ifindex);
if (dev && dev->type == ARPHRD_SIT)
err = addrconf_set_sit_dstaddr(net, dev, &ireq);
rtnl_unlock();
return err;
}
static int ipv6_mc_config(struct sock *sk, bool join,
const struct in6_addr *addr, int ifindex)
{
int ret;
ASSERT_RTNL();
lock_sock(sk);
if (join)
ret = ipv6_sock_mc_join(sk, ifindex, addr);
else
ret = ipv6_sock_mc_drop(sk, ifindex, addr);
release_sock(sk);
return ret;
}
/*
* Manual configuration of address on an interface
*/
static int inet6_addr_add(struct net *net, int ifindex,
struct ifa6_config *cfg,
struct netlink_ext_ack *extack)
{
struct inet6_ifaddr *ifp;
struct inet6_dev *idev;
struct net_device *dev;
unsigned long timeout;
clock_t expires;
u32 flags;
ASSERT_RTNL();
if (cfg->plen > 128) {
NL_SET_ERR_MSG_MOD(extack, "Invalid prefix length");
return -EINVAL;
}
/* check the lifetime */
if (!cfg->valid_lft || cfg->preferred_lft > cfg->valid_lft) {
NL_SET_ERR_MSG_MOD(extack, "address lifetime invalid");
return -EINVAL;
}
if (cfg->ifa_flags & IFA_F_MANAGETEMPADDR && cfg->plen != 64) {
NL_SET_ERR_MSG_MOD(extack, "address with \"mngtmpaddr\" flag must have a prefix length of 64");
return -EINVAL;
}
dev = __dev_get_by_index(net, ifindex);
if (!dev)
return -ENODEV;
idev = addrconf_add_dev(dev);
if (IS_ERR(idev)) {
NL_SET_ERR_MSG_MOD(extack, "IPv6 is disabled on this device");
return PTR_ERR(idev);
}
if (cfg->ifa_flags & IFA_F_MCAUTOJOIN) {
int ret = ipv6_mc_config(net->ipv6.mc_autojoin_sk,
true, cfg->pfx, ifindex);
if (ret < 0) {
NL_SET_ERR_MSG_MOD(extack, "Multicast auto join failed");
return ret;
}
}
cfg->scope = ipv6_addr_scope(cfg->pfx);
timeout = addrconf_timeout_fixup(cfg->valid_lft, HZ);
if (addrconf_finite_timeout(timeout)) {
expires = jiffies_to_clock_t(timeout * HZ);
cfg->valid_lft = timeout;
flags = RTF_EXPIRES;
} else {
expires = 0;
flags = 0;
cfg->ifa_flags |= IFA_F_PERMANENT;
}
timeout = addrconf_timeout_fixup(cfg->preferred_lft, HZ);
if (addrconf_finite_timeout(timeout)) {
if (timeout == 0)
cfg->ifa_flags |= IFA_F_DEPRECATED;
cfg->preferred_lft = timeout;
}
ifp = ipv6_add_addr(idev, cfg, true, extack);
if (!IS_ERR(ifp)) {
if (!(cfg->ifa_flags & IFA_F_NOPREFIXROUTE)) {
addrconf_prefix_route(&ifp->addr, ifp->prefix_len,
ifp->rt_priority, dev, expires,
flags, GFP_KERNEL);
}
/* Send a netlink notification if DAD is enabled and
* optimistic flag is not set
*/
if (!(ifp->flags & (IFA_F_OPTIMISTIC | IFA_F_NODAD)))
ipv6_ifa_notify(0, ifp);
/*
* Note that section 3.1 of RFC 4429 indicates
* that the Optimistic flag should not be set for
* manually configured addresses
*/
addrconf_dad_start(ifp);
if (cfg->ifa_flags & IFA_F_MANAGETEMPADDR)
manage_tempaddrs(idev, ifp, cfg->valid_lft,
cfg->preferred_lft, true, jiffies);
in6_ifa_put(ifp);
addrconf_verify_rtnl(net);
return 0;
} else if (cfg->ifa_flags & IFA_F_MCAUTOJOIN) {
ipv6_mc_config(net->ipv6.mc_autojoin_sk, false,
cfg->pfx, ifindex);
}
return PTR_ERR(ifp);
}
static int inet6_addr_del(struct net *net, int ifindex, u32 ifa_flags,
const struct in6_addr *pfx, unsigned int plen,
struct netlink_ext_ack *extack)
{
struct inet6_ifaddr *ifp;
struct inet6_dev *idev;
struct net_device *dev;
if (plen > 128) {
NL_SET_ERR_MSG_MOD(extack, "Invalid prefix length");
return -EINVAL;
}
dev = __dev_get_by_index(net, ifindex);
if (!dev) {
NL_SET_ERR_MSG_MOD(extack, "Unable to find the interface");
return -ENODEV;
}
idev = __in6_dev_get(dev);
if (!idev) {
NL_SET_ERR_MSG_MOD(extack, "IPv6 is disabled on this device");
return -ENXIO;
}
read_lock_bh(&idev->lock);
list_for_each_entry(ifp, &idev->addr_list, if_list) {
if (ifp->prefix_len == plen &&
ipv6_addr_equal(pfx, &ifp->addr)) {
in6_ifa_hold(ifp);
read_unlock_bh(&idev->lock);
if (!(ifp->flags & IFA_F_TEMPORARY) &&
(ifa_flags & IFA_F_MANAGETEMPADDR))
manage_tempaddrs(idev, ifp, 0, 0, false,
jiffies);
ipv6_del_addr(ifp);
addrconf_verify_rtnl(net);
if (ipv6_addr_is_multicast(pfx)) {
ipv6_mc_config(net->ipv6.mc_autojoin_sk,
false, pfx, dev->ifindex);
}
return 0;
}
}
read_unlock_bh(&idev->lock);
NL_SET_ERR_MSG_MOD(extack, "address not found");
return -EADDRNOTAVAIL;
}
int addrconf_add_ifaddr(struct net *net, void __user *arg)
{
struct ifa6_config cfg = {
.ifa_flags = IFA_F_PERMANENT,
.preferred_lft = INFINITY_LIFE_TIME,
.valid_lft = INFINITY_LIFE_TIME,
};
struct in6_ifreq ireq;
int err;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
return -EFAULT;
cfg.pfx = &ireq.ifr6_addr;
cfg.plen = ireq.ifr6_prefixlen;
rtnl_lock();
err = inet6_addr_add(net, ireq.ifr6_ifindex, &cfg, NULL);
rtnl_unlock();
return err;
}
int addrconf_del_ifaddr(struct net *net, void __user *arg)
{
struct in6_ifreq ireq;
int err;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
return -EFAULT;
rtnl_lock();
err = inet6_addr_del(net, ireq.ifr6_ifindex, 0, &ireq.ifr6_addr,
ireq.ifr6_prefixlen, NULL);
rtnl_unlock();
return err;
}
static void add_addr(struct inet6_dev *idev, const struct in6_addr *addr,
int plen, int scope, u8 proto)
{
struct inet6_ifaddr *ifp;
struct ifa6_config cfg = {
.pfx = addr,
.plen = plen,
.ifa_flags = IFA_F_PERMANENT,
.valid_lft = INFINITY_LIFE_TIME,
.preferred_lft = INFINITY_LIFE_TIME,
.scope = scope,
.ifa_proto = proto
};
ifp = ipv6_add_addr(idev, &cfg, true, NULL);
if (!IS_ERR(ifp)) {
spin_lock_bh(&ifp->lock);
ifp->flags &= ~IFA_F_TENTATIVE;
spin_unlock_bh(&ifp->lock);
rt_genid_bump_ipv6(dev_net(idev->dev));
ipv6_ifa_notify(RTM_NEWADDR, ifp);
in6_ifa_put(ifp);
}
}
#if IS_ENABLED(CONFIG_IPV6_SIT) || IS_ENABLED(CONFIG_NET_IPGRE) || IS_ENABLED(CONFIG_IPV6_GRE)
static void add_v4_addrs(struct inet6_dev *idev)
{
struct in6_addr addr;
struct net_device *dev;
struct net *net = dev_net(idev->dev);
int scope, plen, offset = 0;
u32 pflags = 0;
ASSERT_RTNL();
memset(&addr, 0, sizeof(struct in6_addr));
/* in case of IP6GRE the dev_addr is an IPv6 and therefore we use only the last 4 bytes */
if (idev->dev->addr_len == sizeof(struct in6_addr))
offset = sizeof(struct in6_addr) - 4;
memcpy(&addr.s6_addr32[3], idev->dev->dev_addr + offset, 4);
if (!(idev->dev->flags & IFF_POINTOPOINT) && idev->dev->type == ARPHRD_SIT) {
scope = IPV6_ADDR_COMPATv4;
plen = 96;
pflags |= RTF_NONEXTHOP;
} else {
if (idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_NONE)
return;
addr.s6_addr32[0] = htonl(0xfe800000);
scope = IFA_LINK;
plen = 64;
}
if (addr.s6_addr32[3]) {
add_addr(idev, &addr, plen, scope, IFAPROT_UNSPEC);
addrconf_prefix_route(&addr, plen, 0, idev->dev, 0, pflags,
GFP_KERNEL);
return;
}
for_each_netdev(net, dev) {
struct in_device *in_dev = __in_dev_get_rtnl(dev);
if (in_dev && (dev->flags & IFF_UP)) {
struct in_ifaddr *ifa;
int flag = scope;
in_dev_for_each_ifa_rtnl(ifa, in_dev) {
addr.s6_addr32[3] = ifa->ifa_local;
if (ifa->ifa_scope == RT_SCOPE_LINK)
continue;
if (ifa->ifa_scope >= RT_SCOPE_HOST) {
if (idev->dev->flags&IFF_POINTOPOINT)
continue;
flag |= IFA_HOST;
}
add_addr(idev, &addr, plen, flag,
IFAPROT_UNSPEC);
addrconf_prefix_route(&addr, plen, 0, idev->dev,
0, pflags, GFP_KERNEL);
}
}
}
}
#endif
static void init_loopback(struct net_device *dev)
{
struct inet6_dev *idev;
/* ::1 */
ASSERT_RTNL();
idev = ipv6_find_idev(dev);
if (IS_ERR(idev)) {
pr_debug("%s: add_dev failed\n", __func__);
return;
}
add_addr(idev, &in6addr_loopback, 128, IFA_HOST, IFAPROT_KERNEL_LO);
}
void addrconf_add_linklocal(struct inet6_dev *idev,
const struct in6_addr *addr, u32 flags)
{
struct ifa6_config cfg = {
.pfx = addr,
.plen = 64,
.ifa_flags = flags | IFA_F_PERMANENT,
.valid_lft = INFINITY_LIFE_TIME,
.preferred_lft = INFINITY_LIFE_TIME,
.scope = IFA_LINK,
.ifa_proto = IFAPROT_KERNEL_LL
};
struct inet6_ifaddr *ifp;
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
if ((dev_net(idev->dev)->ipv6.devconf_all->optimistic_dad ||
idev->cnf.optimistic_dad) &&
!dev_net(idev->dev)->ipv6.devconf_all->forwarding)
cfg.ifa_flags |= IFA_F_OPTIMISTIC;
#endif
ifp = ipv6_add_addr(idev, &cfg, true, NULL);
if (!IS_ERR(ifp)) {
addrconf_prefix_route(&ifp->addr, ifp->prefix_len, 0, idev->dev,
0, 0, GFP_ATOMIC);
addrconf_dad_start(ifp);
in6_ifa_put(ifp);
}
}
EXPORT_SYMBOL_GPL(addrconf_add_linklocal);
static bool ipv6_reserved_interfaceid(struct in6_addr address)
{
if ((address.s6_addr32[2] | address.s6_addr32[3]) == 0)
return true;
if (address.s6_addr32[2] == htonl(0x02005eff) &&
((address.s6_addr32[3] & htonl(0xfe000000)) == htonl(0xfe000000)))
return true;
if (address.s6_addr32[2] == htonl(0xfdffffff) &&
((address.s6_addr32[3] & htonl(0xffffff80)) == htonl(0xffffff80)))
return true;
return false;
}
static int ipv6_generate_stable_address(struct in6_addr *address,
u8 dad_count,
const struct inet6_dev *idev)
{
static DEFINE_SPINLOCK(lock);
static __u32 digest[SHA1_DIGEST_WORDS];
static __u32 workspace[SHA1_WORKSPACE_WORDS];
static union {
char __data[SHA1_BLOCK_SIZE];
struct {
struct in6_addr secret;
__be32 prefix[2];
unsigned char hwaddr[MAX_ADDR_LEN];
u8 dad_count;
} __packed;
} data;
struct in6_addr secret;
struct in6_addr temp;
struct net *net = dev_net(idev->dev);
BUILD_BUG_ON(sizeof(data.__data) != sizeof(data));
if (idev->cnf.stable_secret.initialized)
secret = idev->cnf.stable_secret.secret;
else if (net->ipv6.devconf_dflt->stable_secret.initialized)
secret = net->ipv6.devconf_dflt->stable_secret.secret;
else
return -1;
retry:
spin_lock_bh(&lock);
sha1_init(digest);
memset(&data, 0, sizeof(data));
memset(workspace, 0, sizeof(workspace));
memcpy(data.hwaddr, idev->dev->perm_addr, idev->dev->addr_len);
data.prefix[0] = address->s6_addr32[0];
data.prefix[1] = address->s6_addr32[1];
data.secret = secret;
data.dad_count = dad_count;
sha1_transform(digest, data.__data, workspace);
temp = *address;
temp.s6_addr32[2] = (__force __be32)digest[0];
temp.s6_addr32[3] = (__force __be32)digest[1];
spin_unlock_bh(&lock);
if (ipv6_reserved_interfaceid(temp)) {
dad_count++;
if (dad_count > dev_net(idev->dev)->ipv6.sysctl.idgen_retries)
return -1;
goto retry;
}
*address = temp;
return 0;
}
static void ipv6_gen_mode_random_init(struct inet6_dev *idev)
{
struct ipv6_stable_secret *s = &idev->cnf.stable_secret;
if (s->initialized)
return;
s = &idev->cnf.stable_secret;
get_random_bytes(&s->secret, sizeof(s->secret));
s->initialized = true;
}
static void addrconf_addr_gen(struct inet6_dev *idev, bool prefix_route)
{
struct in6_addr addr;
/* no link local addresses on L3 master devices */
if (netif_is_l3_master(idev->dev))
return;
/* no link local addresses on devices flagged as slaves */
if (idev->dev->priv_flags & IFF_NO_ADDRCONF)
return;
ipv6_addr_set(&addr, htonl(0xFE800000), 0, 0, 0);
switch (idev->cnf.addr_gen_mode) {
case IN6_ADDR_GEN_MODE_RANDOM:
ipv6_gen_mode_random_init(idev);
fallthrough;
case IN6_ADDR_GEN_MODE_STABLE_PRIVACY:
if (!ipv6_generate_stable_address(&addr, 0, idev))
addrconf_add_linklocal(idev, &addr,
IFA_F_STABLE_PRIVACY);
else if (prefix_route)
addrconf_prefix_route(&addr, 64, 0, idev->dev,
0, 0, GFP_KERNEL);
break;
case IN6_ADDR_GEN_MODE_EUI64:
/* addrconf_add_linklocal also adds a prefix_route and we
* only need to care about prefix routes if ipv6_generate_eui64
* couldn't generate one.
*/
if (ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) == 0)
addrconf_add_linklocal(idev, &addr, 0);
else if (prefix_route)
addrconf_prefix_route(&addr, 64, 0, idev->dev,
0, 0, GFP_KERNEL);
break;
case IN6_ADDR_GEN_MODE_NONE:
default:
/* will not add any link local address */
break;
}
}
static void addrconf_dev_config(struct net_device *dev)
{
struct inet6_dev *idev;
ASSERT_RTNL();
if ((dev->type != ARPHRD_ETHER) &&
(dev->type != ARPHRD_FDDI) &&
(dev->type != ARPHRD_ARCNET) &&
(dev->type != ARPHRD_INFINIBAND) &&
(dev->type != ARPHRD_IEEE1394) &&
(dev->type != ARPHRD_TUNNEL6) &&
(dev->type != ARPHRD_6LOWPAN) &&
(dev->type != ARPHRD_TUNNEL) &&
(dev->type != ARPHRD_NONE) &&
(dev->type != ARPHRD_RAWIP)) {
/* Alas, we support only Ethernet autoconfiguration. */
idev = __in6_dev_get(dev);
if (!IS_ERR_OR_NULL(idev) && dev->flags & IFF_UP &&
dev->flags & IFF_MULTICAST)
ipv6_mc_up(idev);
return;
}
idev = addrconf_add_dev(dev);
if (IS_ERR(idev))
return;
/* this device type has no EUI support */
if (dev->type == ARPHRD_NONE &&
idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_EUI64)
idev->cnf.addr_gen_mode = IN6_ADDR_GEN_MODE_RANDOM;
addrconf_addr_gen(idev, false);
}
#if IS_ENABLED(CONFIG_IPV6_SIT)
static void addrconf_sit_config(struct net_device *dev)
{
struct inet6_dev *idev;
ASSERT_RTNL();
/*
* Configure the tunnel with one of our IPv4
* addresses... we should configure all of
* our v4 addrs in the tunnel
*/
idev = ipv6_find_idev(dev);
if (IS_ERR(idev)) {
pr_debug("%s: add_dev failed\n", __func__);
return;
}
if (dev->priv_flags & IFF_ISATAP) {
addrconf_addr_gen(idev, false);
return;
}
add_v4_addrs(idev);
if (dev->flags&IFF_POINTOPOINT)
addrconf_add_mroute(dev);
}
#endif
#if IS_ENABLED(CONFIG_NET_IPGRE) || IS_ENABLED(CONFIG_IPV6_GRE)
static void addrconf_gre_config(struct net_device *dev)
{
struct inet6_dev *idev;
ASSERT_RTNL();
idev = ipv6_find_idev(dev);
if (IS_ERR(idev)) {
pr_debug("%s: add_dev failed\n", __func__);
return;
}
if (dev->type == ARPHRD_ETHER) {
addrconf_addr_gen(idev, true);
return;
}
add_v4_addrs(idev);
if (dev->flags & IFF_POINTOPOINT)
addrconf_add_mroute(dev);
}
#endif
static void addrconf_init_auto_addrs(struct net_device *dev)
{
switch (dev->type) {
#if IS_ENABLED(CONFIG_IPV6_SIT)
case ARPHRD_SIT:
addrconf_sit_config(dev);
break;
#endif
#if IS_ENABLED(CONFIG_NET_IPGRE) || IS_ENABLED(CONFIG_IPV6_GRE)
case ARPHRD_IP6GRE:
case ARPHRD_IPGRE:
addrconf_gre_config(dev);
break;
#endif
case ARPHRD_LOOPBACK:
init_loopback(dev);
break;
default:
addrconf_dev_config(dev);
break;
}
}
static int fixup_permanent_addr(struct net *net,
struct inet6_dev *idev,
struct inet6_ifaddr *ifp)
{
/* !fib6_node means the host route was removed from the
* FIB, for example, if 'lo' device is taken down. In that
* case regenerate the host route.
*/
if (!ifp->rt || !ifp->rt->fib6_node) {
struct fib6_info *f6i, *prev;
f6i = addrconf_f6i_alloc(net, idev, &ifp->addr, false,
GFP_ATOMIC, NULL);
if (IS_ERR(f6i))
return PTR_ERR(f6i);
/* ifp->rt can be accessed outside of rtnl */
spin_lock(&ifp->lock);
prev = ifp->rt;
ifp->rt = f6i;
spin_unlock(&ifp->lock);
fib6_info_release(prev);
}
if (!(ifp->flags & IFA_F_NOPREFIXROUTE)) {
addrconf_prefix_route(&ifp->addr, ifp->prefix_len,
ifp->rt_priority, idev->dev, 0, 0,
GFP_ATOMIC);
}
if (ifp->state == INET6_IFADDR_STATE_PREDAD)
addrconf_dad_start(ifp);
return 0;
}
static void addrconf_permanent_addr(struct net *net, struct net_device *dev)
{
struct inet6_ifaddr *ifp, *tmp;
struct inet6_dev *idev;
idev = __in6_dev_get(dev);
if (!idev)
return;
write_lock_bh(&idev->lock);
list_for_each_entry_safe(ifp, tmp, &idev->addr_list, if_list) {
if ((ifp->flags & IFA_F_PERMANENT) &&
fixup_permanent_addr(net, idev, ifp) < 0) {
write_unlock_bh(&idev->lock);
in6_ifa_hold(ifp);
ipv6_del_addr(ifp);
write_lock_bh(&idev->lock);
net_info_ratelimited("%s: Failed to add prefix route for address %pI6c; dropping\n",
idev->dev->name, &ifp->addr);
}
}
write_unlock_bh(&idev->lock);
}
static int addrconf_notify(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
struct netdev_notifier_change_info *change_info;
struct netdev_notifier_changeupper_info *info;
struct inet6_dev *idev = __in6_dev_get(dev);
struct net *net = dev_net(dev);
int run_pending = 0;
int err;
switch (event) {
case NETDEV_REGISTER:
if (!idev && dev->mtu >= IPV6_MIN_MTU) {
idev = ipv6_add_dev(dev);
if (IS_ERR(idev))
return notifier_from_errno(PTR_ERR(idev));
}
break;
case NETDEV_CHANGEMTU:
/* if MTU under IPV6_MIN_MTU stop IPv6 on this interface. */
if (dev->mtu < IPV6_MIN_MTU) {
addrconf_ifdown(dev, dev != net->loopback_dev);
break;
}
if (idev) {
rt6_mtu_change(dev, dev->mtu);
idev->cnf.mtu6 = dev->mtu;
break;
}
/* allocate new idev */
idev = ipv6_add_dev(dev);
if (IS_ERR(idev))
break;
/* device is still not ready */
if (!(idev->if_flags & IF_READY))
break;
run_pending = 1;
fallthrough;
case NETDEV_UP:
case NETDEV_CHANGE:
if (idev && idev->cnf.disable_ipv6)
break;
if (dev->priv_flags & IFF_NO_ADDRCONF) {
if (event == NETDEV_UP && !IS_ERR_OR_NULL(idev) &&
dev->flags & IFF_UP && dev->flags & IFF_MULTICAST)
ipv6_mc_up(idev);
break;
}
if (event == NETDEV_UP) {
/* restore routes for permanent addresses */
addrconf_permanent_addr(net, dev);
if (!addrconf_link_ready(dev)) {
/* device is not ready yet. */
pr_debug("ADDRCONF(NETDEV_UP): %s: link is not ready\n",
dev->name);
break;
}
if (!idev && dev->mtu >= IPV6_MIN_MTU)
idev = ipv6_add_dev(dev);
if (!IS_ERR_OR_NULL(idev)) {
idev->if_flags |= IF_READY;
run_pending = 1;
}
} else if (event == NETDEV_CHANGE) {
if (!addrconf_link_ready(dev)) {
/* device is still not ready. */
rt6_sync_down_dev(dev, event);
break;
}
if (!IS_ERR_OR_NULL(idev)) {
if (idev->if_flags & IF_READY) {
/* device is already configured -
* but resend MLD reports, we might
* have roamed and need to update
* multicast snooping switches
*/
ipv6_mc_up(idev);
change_info = ptr;
if (change_info->flags_changed & IFF_NOARP)
addrconf_dad_run(idev, true);
rt6_sync_up(dev, RTNH_F_LINKDOWN);
break;
}
idev->if_flags |= IF_READY;
}
pr_debug("ADDRCONF(NETDEV_CHANGE): %s: link becomes ready\n",
dev->name);
run_pending = 1;
}
addrconf_init_auto_addrs(dev);
if (!IS_ERR_OR_NULL(idev)) {
if (run_pending)
addrconf_dad_run(idev, false);
/* Device has an address by now */
rt6_sync_up(dev, RTNH_F_DEAD);
/*
* If the MTU changed during the interface down,
* when the interface up, the changed MTU must be
* reflected in the idev as well as routers.
*/
if (idev->cnf.mtu6 != dev->mtu &&
dev->mtu >= IPV6_MIN_MTU) {
rt6_mtu_change(dev, dev->mtu);
idev->cnf.mtu6 = dev->mtu;
}
idev->tstamp = jiffies;
inet6_ifinfo_notify(RTM_NEWLINK, idev);
/*
* If the changed mtu during down is lower than
* IPV6_MIN_MTU stop IPv6 on this interface.
*/
if (dev->mtu < IPV6_MIN_MTU)
addrconf_ifdown(dev, dev != net->loopback_dev);
}
break;
case NETDEV_DOWN:
case NETDEV_UNREGISTER:
/*
* Remove all addresses from this interface.
*/
addrconf_ifdown(dev, event != NETDEV_DOWN);
break;
case NETDEV_CHANGENAME:
if (idev) {
snmp6_unregister_dev(idev);
addrconf_sysctl_unregister(idev);
err = addrconf_sysctl_register(idev);
if (err)
return notifier_from_errno(err);
err = snmp6_register_dev(idev);
if (err) {
addrconf_sysctl_unregister(idev);
return notifier_from_errno(err);
}
}
break;
case NETDEV_PRE_TYPE_CHANGE:
case NETDEV_POST_TYPE_CHANGE:
if (idev)
addrconf_type_change(dev, event);
break;
case NETDEV_CHANGEUPPER:
info = ptr;
/* flush all routes if dev is linked to or unlinked from
* an L3 master device (e.g., VRF)
*/
if (info->upper_dev && netif_is_l3_master(info->upper_dev))
addrconf_ifdown(dev, false);
}
return NOTIFY_OK;
}
/*
* addrconf module should be notified of a device going up
*/
static struct notifier_block ipv6_dev_notf = {
.notifier_call = addrconf_notify,
.priority = ADDRCONF_NOTIFY_PRIORITY,
};
static void addrconf_type_change(struct net_device *dev, unsigned long event)
{
struct inet6_dev *idev;
ASSERT_RTNL();
idev = __in6_dev_get(dev);
if (event == NETDEV_POST_TYPE_CHANGE)
ipv6_mc_remap(idev);
else if (event == NETDEV_PRE_TYPE_CHANGE)
ipv6_mc_unmap(idev);
}
static bool addr_is_local(const struct in6_addr *addr)
{
return ipv6_addr_type(addr) &
(IPV6_ADDR_LINKLOCAL | IPV6_ADDR_LOOPBACK);
}
static int addrconf_ifdown(struct net_device *dev, bool unregister)
{
unsigned long event = unregister ? NETDEV_UNREGISTER : NETDEV_DOWN;
struct net *net = dev_net(dev);
struct inet6_dev *idev;
struct inet6_ifaddr *ifa;
LIST_HEAD(tmp_addr_list);
bool keep_addr = false;
bool was_ready;
int state, i;
ASSERT_RTNL();
rt6_disable_ip(dev, event);
idev = __in6_dev_get(dev);
if (!idev)
return -ENODEV;
/*
* Step 1: remove reference to ipv6 device from parent device.
* Do not dev_put!
*/
if (unregister) {
idev->dead = 1;
/* protected by rtnl_lock */
RCU_INIT_POINTER(dev->ip6_ptr, NULL);
/* Step 1.5: remove snmp6 entry */
snmp6_unregister_dev(idev);
}
/* combine the user config with event to determine if permanent
* addresses are to be removed from address hash table
*/
if (!unregister && !idev->cnf.disable_ipv6) {
/* aggregate the system setting and interface setting */
int _keep_addr = net->ipv6.devconf_all->keep_addr_on_down;
if (!_keep_addr)
_keep_addr = idev->cnf.keep_addr_on_down;
keep_addr = (_keep_addr > 0);
}
/* Step 2: clear hash table */
for (i = 0; i < IN6_ADDR_HSIZE; i++) {
struct hlist_head *h = &net->ipv6.inet6_addr_lst[i];
spin_lock_bh(&net->ipv6.addrconf_hash_lock);
restart:
hlist_for_each_entry_rcu(ifa, h, addr_lst) {
if (ifa->idev == idev) {
addrconf_del_dad_work(ifa);
/* combined flag + permanent flag decide if
* address is retained on a down event
*/
if (!keep_addr ||
!(ifa->flags & IFA_F_PERMANENT) ||
addr_is_local(&ifa->addr)) {
hlist_del_init_rcu(&ifa->addr_lst);
goto restart;
}
}
}
spin_unlock_bh(&net->ipv6.addrconf_hash_lock);
}
write_lock_bh(&idev->lock);
addrconf_del_rs_timer(idev);
/* Step 2: clear flags for stateless addrconf, repeated down
* detection
*/
was_ready = idev->if_flags & IF_READY;
if (!unregister)
idev->if_flags &= ~(IF_RS_SENT|IF_RA_RCVD|IF_READY);
/* Step 3: clear tempaddr list */
while (!list_empty(&idev->tempaddr_list)) {
ifa = list_first_entry(&idev->tempaddr_list,
struct inet6_ifaddr, tmp_list);
list_del(&ifa->tmp_list);
write_unlock_bh(&idev->lock);
spin_lock_bh(&ifa->lock);
if (ifa->ifpub) {
in6_ifa_put(ifa->ifpub);
ifa->ifpub = NULL;
}
spin_unlock_bh(&ifa->lock);
in6_ifa_put(ifa);
write_lock_bh(&idev->lock);
}
list_for_each_entry(ifa, &idev->addr_list, if_list)
list_add_tail(&ifa->if_list_aux, &tmp_addr_list);
write_unlock_bh(&idev->lock);
while (!list_empty(&tmp_addr_list)) {
struct fib6_info *rt = NULL;
bool keep;
ifa = list_first_entry(&tmp_addr_list,
struct inet6_ifaddr, if_list_aux);
list_del(&ifa->if_list_aux);
addrconf_del_dad_work(ifa);
keep = keep_addr && (ifa->flags & IFA_F_PERMANENT) &&
!addr_is_local(&ifa->addr);
spin_lock_bh(&ifa->lock);
if (keep) {
/* set state to skip the notifier below */
state = INET6_IFADDR_STATE_DEAD;
ifa->state = INET6_IFADDR_STATE_PREDAD;
if (!(ifa->flags & IFA_F_NODAD))
ifa->flags |= IFA_F_TENTATIVE;
rt = ifa->rt;
ifa->rt = NULL;
} else {
state = ifa->state;
ifa->state = INET6_IFADDR_STATE_DEAD;
}
spin_unlock_bh(&ifa->lock);
if (rt)
ip6_del_rt(net, rt, false);
if (state != INET6_IFADDR_STATE_DEAD) {
__ipv6_ifa_notify(RTM_DELADDR, ifa);
inet6addr_notifier_call_chain(NETDEV_DOWN, ifa);
} else {
if (idev->cnf.forwarding)
addrconf_leave_anycast(ifa);
addrconf_leave_solict(ifa->idev, &ifa->addr);
}
if (!keep) {
write_lock_bh(&idev->lock);
list_del_rcu(&ifa->if_list);
write_unlock_bh(&idev->lock);
in6_ifa_put(ifa);
}
}
/* Step 5: Discard anycast and multicast list */
if (unregister) {
ipv6_ac_destroy_dev(idev);
ipv6_mc_destroy_dev(idev);
} else if (was_ready) {
ipv6_mc_down(idev);
}
idev->tstamp = jiffies;
idev->ra_mtu = 0;
/* Last: Shot the device (if unregistered) */
if (unregister) {
addrconf_sysctl_unregister(idev);
neigh_parms_release(&nd_tbl, idev->nd_parms);
neigh_ifdown(&nd_tbl, dev);
in6_dev_put(idev);
}
return 0;
}
static void addrconf_rs_timer(struct timer_list *t)
{
struct inet6_dev *idev = from_timer(idev, t, rs_timer);
struct net_device *dev = idev->dev;
struct in6_addr lladdr;
write_lock(&idev->lock);
if (idev->dead || !(idev->if_flags & IF_READY))
goto out;
if (!ipv6_accept_ra(idev))
goto out;
/* Announcement received after solicitation was sent */
if (idev->if_flags & IF_RA_RCVD)
goto out;
if (idev->rs_probes++ < idev->cnf.rtr_solicits || idev->cnf.rtr_solicits < 0) {
write_unlock(&idev->lock);
if (!ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE))
ndisc_send_rs(dev, &lladdr,
&in6addr_linklocal_allrouters);
else
goto put;
write_lock(&idev->lock);
idev->rs_interval = rfc3315_s14_backoff_update(
idev->rs_interval, idev->cnf.rtr_solicit_max_interval);
/* The wait after the last probe can be shorter */
addrconf_mod_rs_timer(idev, (idev->rs_probes ==
idev->cnf.rtr_solicits) ?
idev->cnf.rtr_solicit_delay :
idev->rs_interval);
} else {
/*
* Note: we do not support deprecated "all on-link"
* assumption any longer.
*/
pr_debug("%s: no IPv6 routers present\n", idev->dev->name);
}
out:
write_unlock(&idev->lock);
put:
in6_dev_put(idev);
}
/*
* Duplicate Address Detection
*/
static void addrconf_dad_kick(struct inet6_ifaddr *ifp)
{
unsigned long rand_num;
struct inet6_dev *idev = ifp->idev;
u64 nonce;
if (ifp->flags & IFA_F_OPTIMISTIC)
rand_num = 0;
else
rand_num = get_random_u32_below(idev->cnf.rtr_solicit_delay ? : 1);
nonce = 0;
if (idev->cnf.enhanced_dad ||
dev_net(idev->dev)->ipv6.devconf_all->enhanced_dad) {
do
get_random_bytes(&nonce, 6);
while (nonce == 0);
}
ifp->dad_nonce = nonce;
ifp->dad_probes = idev->cnf.dad_transmits;
addrconf_mod_dad_work(ifp, rand_num);
}
static void addrconf_dad_begin(struct inet6_ifaddr *ifp)
{
struct inet6_dev *idev = ifp->idev;
struct net_device *dev = idev->dev;
bool bump_id, notify = false;
struct net *net;
addrconf_join_solict(dev, &ifp->addr);
read_lock_bh(&idev->lock);
spin_lock(&ifp->lock);
if (ifp->state == INET6_IFADDR_STATE_DEAD)
goto out;
net = dev_net(dev);
if (dev->flags&(IFF_NOARP|IFF_LOOPBACK) ||
(net->ipv6.devconf_all->accept_dad < 1 &&
idev->cnf.accept_dad < 1) ||
!(ifp->flags&IFA_F_TENTATIVE) ||
ifp->flags & IFA_F_NODAD) {
bool send_na = false;
if (ifp->flags & IFA_F_TENTATIVE &&
!(ifp->flags & IFA_F_OPTIMISTIC))
send_na = true;
bump_id = ifp->flags & IFA_F_TENTATIVE;
ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED);
spin_unlock(&ifp->lock);
read_unlock_bh(&idev->lock);
addrconf_dad_completed(ifp, bump_id, send_na);
return;
}
if (!(idev->if_flags & IF_READY)) {
spin_unlock(&ifp->lock);
read_unlock_bh(&idev->lock);
/*
* If the device is not ready:
* - keep it tentative if it is a permanent address.
* - otherwise, kill it.
*/
in6_ifa_hold(ifp);
addrconf_dad_stop(ifp, 0);
return;
}
/*
* Optimistic nodes can start receiving
* Frames right away
*/
if (ifp->flags & IFA_F_OPTIMISTIC) {
ip6_ins_rt(net, ifp->rt);
if (ipv6_use_optimistic_addr(net, idev)) {
/* Because optimistic nodes can use this address,
* notify listeners. If DAD fails, RTM_DELADDR is sent.
*/
notify = true;
}
}
addrconf_dad_kick(ifp);
out:
spin_unlock(&ifp->lock);
read_unlock_bh(&idev->lock);
if (notify)
ipv6_ifa_notify(RTM_NEWADDR, ifp);
}
static void addrconf_dad_start(struct inet6_ifaddr *ifp)
{
bool begin_dad = false;
spin_lock_bh(&ifp->lock);
if (ifp->state != INET6_IFADDR_STATE_DEAD) {
ifp->state = INET6_IFADDR_STATE_PREDAD;
begin_dad = true;
}
spin_unlock_bh(&ifp->lock);
if (begin_dad)
addrconf_mod_dad_work(ifp, 0);
}
static void addrconf_dad_work(struct work_struct *w)
{
struct inet6_ifaddr *ifp = container_of(to_delayed_work(w),
struct inet6_ifaddr,
dad_work);
struct inet6_dev *idev = ifp->idev;
bool bump_id, disable_ipv6 = false;
struct in6_addr mcaddr;
enum {
DAD_PROCESS,
DAD_BEGIN,
DAD_ABORT,
} action = DAD_PROCESS;
rtnl_lock();
spin_lock_bh(&ifp->lock);
if (ifp->state == INET6_IFADDR_STATE_PREDAD) {
action = DAD_BEGIN;
ifp->state = INET6_IFADDR_STATE_DAD;
} else if (ifp->state == INET6_IFADDR_STATE_ERRDAD) {
action = DAD_ABORT;
ifp->state = INET6_IFADDR_STATE_POSTDAD;
if ((dev_net(idev->dev)->ipv6.devconf_all->accept_dad > 1 ||
idev->cnf.accept_dad > 1) &&
!idev->cnf.disable_ipv6 &&
!(ifp->flags & IFA_F_STABLE_PRIVACY)) {
struct in6_addr addr;
addr.s6_addr32[0] = htonl(0xfe800000);
addr.s6_addr32[1] = 0;
if (!ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) &&
ipv6_addr_equal(&ifp->addr, &addr)) {
/* DAD failed for link-local based on MAC */
idev->cnf.disable_ipv6 = 1;
pr_info("%s: IPv6 being disabled!\n",
ifp->idev->dev->name);
disable_ipv6 = true;
}
}
}
spin_unlock_bh(&ifp->lock);
if (action == DAD_BEGIN) {
addrconf_dad_begin(ifp);
goto out;
} else if (action == DAD_ABORT) {
in6_ifa_hold(ifp);
addrconf_dad_stop(ifp, 1);
if (disable_ipv6)
addrconf_ifdown(idev->dev, false);
goto out;
}
if (!ifp->dad_probes && addrconf_dad_end(ifp))
goto out;
write_lock_bh(&idev->lock);
if (idev->dead || !(idev->if_flags & IF_READY)) {
write_unlock_bh(&idev->lock);
goto out;
}
spin_lock(&ifp->lock);
if (ifp->state == INET6_IFADDR_STATE_DEAD) {
spin_unlock(&ifp->lock);
write_unlock_bh(&idev->lock);
goto out;
}
if (ifp->dad_probes == 0) {
bool send_na = false;
/*
* DAD was successful
*/
if (ifp->flags & IFA_F_TENTATIVE &&
!(ifp->flags & IFA_F_OPTIMISTIC))
send_na = true;
bump_id = ifp->flags & IFA_F_TENTATIVE;
ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED);
spin_unlock(&ifp->lock);
write_unlock_bh(&idev->lock);
addrconf_dad_completed(ifp, bump_id, send_na);
goto out;
}
ifp->dad_probes--;
addrconf_mod_dad_work(ifp,
max(NEIGH_VAR(ifp->idev->nd_parms, RETRANS_TIME),
HZ/100));
spin_unlock(&ifp->lock);
write_unlock_bh(&idev->lock);
/* send a neighbour solicitation for our addr */
addrconf_addr_solict_mult(&ifp->addr, &mcaddr);
ndisc_send_ns(ifp->idev->dev, &ifp->addr, &mcaddr, &in6addr_any,
ifp->dad_nonce);
out:
in6_ifa_put(ifp);
rtnl_unlock();
}
/* ifp->idev must be at least read locked */
static bool ipv6_lonely_lladdr(struct inet6_ifaddr *ifp)
{
struct inet6_ifaddr *ifpiter;
struct inet6_dev *idev = ifp->idev;
list_for_each_entry_reverse(ifpiter, &idev->addr_list, if_list) {
if (ifpiter->scope > IFA_LINK)
break;
if (ifp != ifpiter && ifpiter->scope == IFA_LINK &&
(ifpiter->flags & (IFA_F_PERMANENT|IFA_F_TENTATIVE|
IFA_F_OPTIMISTIC|IFA_F_DADFAILED)) ==
IFA_F_PERMANENT)
return false;
}
return true;
}
static void addrconf_dad_completed(struct inet6_ifaddr *ifp, bool bump_id,
bool send_na)
{
struct net_device *dev = ifp->idev->dev;
struct in6_addr lladdr;
bool send_rs, send_mld;
addrconf_del_dad_work(ifp);
/*
* Configure the address for reception. Now it is valid.
*/
ipv6_ifa_notify(RTM_NEWADDR, ifp);
/* If added prefix is link local and we are prepared to process
router advertisements, start sending router solicitations.
*/
read_lock_bh(&ifp->idev->lock);
send_mld = ifp->scope == IFA_LINK && ipv6_lonely_lladdr(ifp);
send_rs = send_mld &&
ipv6_accept_ra(ifp->idev) &&
ifp->idev->cnf.rtr_solicits != 0 &&
(dev->flags & IFF_LOOPBACK) == 0 &&
(dev->type != ARPHRD_TUNNEL) &&
!netif_is_team_port(dev);
read_unlock_bh(&ifp->idev->lock);
/* While dad is in progress mld report's source address is in6_addrany.
* Resend with proper ll now.
*/
if (send_mld)
ipv6_mc_dad_complete(ifp->idev);
/* send unsolicited NA if enabled */
if (send_na &&
(ifp->idev->cnf.ndisc_notify ||
dev_net(dev)->ipv6.devconf_all->ndisc_notify)) {
ndisc_send_na(dev, &in6addr_linklocal_allnodes, &ifp->addr,
/*router=*/ !!ifp->idev->cnf.forwarding,
/*solicited=*/ false, /*override=*/ true,
/*inc_opt=*/ true);
}
if (send_rs) {
/*
* If a host as already performed a random delay
* [...] as part of DAD [...] there is no need
* to delay again before sending the first RS
*/
if (ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE))
return;
ndisc_send_rs(dev, &lladdr, &in6addr_linklocal_allrouters);
write_lock_bh(&ifp->idev->lock);
spin_lock(&ifp->lock);
ifp->idev->rs_interval = rfc3315_s14_backoff_init(
ifp->idev->cnf.rtr_solicit_interval);
ifp->idev->rs_probes = 1;
ifp->idev->if_flags |= IF_RS_SENT;
addrconf_mod_rs_timer(ifp->idev, ifp->idev->rs_interval);
spin_unlock(&ifp->lock);
write_unlock_bh(&ifp->idev->lock);
}
if (bump_id)
rt_genid_bump_ipv6(dev_net(dev));
/* Make sure that a new temporary address will be created
* before this temporary address becomes deprecated.
*/
if (ifp->flags & IFA_F_TEMPORARY)
addrconf_verify_rtnl(dev_net(dev));
}
static void addrconf_dad_run(struct inet6_dev *idev, bool restart)
{
struct inet6_ifaddr *ifp;
read_lock_bh(&idev->lock);
list_for_each_entry(ifp, &idev->addr_list, if_list) {
spin_lock(&ifp->lock);
if ((ifp->flags & IFA_F_TENTATIVE &&
ifp->state == INET6_IFADDR_STATE_DAD) || restart) {
if (restart)
ifp->state = INET6_IFADDR_STATE_PREDAD;
addrconf_dad_kick(ifp);
}
spin_unlock(&ifp->lock);
}
read_unlock_bh(&idev->lock);
}
#ifdef CONFIG_PROC_FS
struct if6_iter_state {
struct seq_net_private p;
int bucket;
int offset;
};
static struct inet6_ifaddr *if6_get_first(struct seq_file *seq, loff_t pos)
{
struct if6_iter_state *state = seq->private;
struct net *net = seq_file_net(seq);
struct inet6_ifaddr *ifa = NULL;
int p = 0;
/* initial bucket if pos is 0 */
if (pos == 0) {
state->bucket = 0;
state->offset = 0;
}
for (; state->bucket < IN6_ADDR_HSIZE; ++state->bucket) {
hlist_for_each_entry_rcu(ifa, &net->ipv6.inet6_addr_lst[state->bucket],
addr_lst) {
/* sync with offset */
if (p < state->offset) {
p++;
continue;
}
return ifa;
}
/* prepare for next bucket */
state->offset = 0;
p = 0;
}
return NULL;
}
static struct inet6_ifaddr *if6_get_next(struct seq_file *seq,
struct inet6_ifaddr *ifa)
{
struct if6_iter_state *state = seq->private;
struct net *net = seq_file_net(seq);
hlist_for_each_entry_continue_rcu(ifa, addr_lst) {
state->offset++;
return ifa;
}
state->offset = 0;
while (++state->bucket < IN6_ADDR_HSIZE) {
hlist_for_each_entry_rcu(ifa,
&net->ipv6.inet6_addr_lst[state->bucket], addr_lst) {
return ifa;
}
}
return NULL;
}
static void *if6_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(rcu)
{
rcu_read_lock();
return if6_get_first(seq, *pos);
}
static void *if6_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct inet6_ifaddr *ifa;
ifa = if6_get_next(seq, v);
++*pos;
return ifa;
}
static void if6_seq_stop(struct seq_file *seq, void *v)
__releases(rcu)
{
rcu_read_unlock();
}
static int if6_seq_show(struct seq_file *seq, void *v)
{
struct inet6_ifaddr *ifp = (struct inet6_ifaddr *)v;
seq_printf(seq, "%pi6 %02x %02x %02x %02x %8s\n",
&ifp->addr,
ifp->idev->dev->ifindex,
ifp->prefix_len,
ifp->scope,
(u8) ifp->flags,
ifp->idev->dev->name);
return 0;
}
static const struct seq_operations if6_seq_ops = {
.start = if6_seq_start,
.next = if6_seq_next,
.show = if6_seq_show,
.stop = if6_seq_stop,
};
static int __net_init if6_proc_net_init(struct net *net)
{
if (!proc_create_net("if_inet6", 0444, net->proc_net, &if6_seq_ops,
sizeof(struct if6_iter_state)))
return -ENOMEM;
return 0;
}
static void __net_exit if6_proc_net_exit(struct net *net)
{
remove_proc_entry("if_inet6", net->proc_net);
}
static struct pernet_operations if6_proc_net_ops = {
.init = if6_proc_net_init,
.exit = if6_proc_net_exit,
};
int __init if6_proc_init(void)
{
return register_pernet_subsys(&if6_proc_net_ops);
}
void if6_proc_exit(void)
{
unregister_pernet_subsys(&if6_proc_net_ops);
}
#endif /* CONFIG_PROC_FS */
#if IS_ENABLED(CONFIG_IPV6_MIP6)
/* Check if address is a home address configured on any interface. */
int ipv6_chk_home_addr(struct net *net, const struct in6_addr *addr)
{
unsigned int hash = inet6_addr_hash(net, addr);
struct inet6_ifaddr *ifp = NULL;
int ret = 0;
rcu_read_lock();
hlist_for_each_entry_rcu(ifp, &net->ipv6.inet6_addr_lst[hash], addr_lst) {
if (ipv6_addr_equal(&ifp->addr, addr) &&
(ifp->flags & IFA_F_HOMEADDRESS)) {
ret = 1;
break;
}
}
rcu_read_unlock();
return ret;
}
#endif
/* RFC6554 has some algorithm to avoid loops in segment routing by
* checking if the segments contains any of a local interface address.
*
* Quote:
*
* To detect loops in the SRH, a router MUST determine if the SRH
* includes multiple addresses assigned to any interface on that router.
* If such addresses appear more than once and are separated by at least
* one address not assigned to that router.
*/
int ipv6_chk_rpl_srh_loop(struct net *net, const struct in6_addr *segs,
unsigned char nsegs)
{
const struct in6_addr *addr;
int i, ret = 0, found = 0;
struct inet6_ifaddr *ifp;
bool separated = false;
unsigned int hash;
bool hash_found;
rcu_read_lock();
for (i = 0; i < nsegs; i++) {
addr = &segs[i];
hash = inet6_addr_hash(net, addr);
hash_found = false;
hlist_for_each_entry_rcu(ifp, &net->ipv6.inet6_addr_lst[hash], addr_lst) {
if (ipv6_addr_equal(&ifp->addr, addr)) {
hash_found = true;
break;
}
}
if (hash_found) {
if (found > 1 && separated) {
ret = 1;
break;
}
separated = false;
found++;
} else {
separated = true;
}
}
rcu_read_unlock();
return ret;
}
/*
* Periodic address status verification
*/
static void addrconf_verify_rtnl(struct net *net)
{
unsigned long now, next, next_sec, next_sched;
struct inet6_ifaddr *ifp;
int i;
ASSERT_RTNL();
rcu_read_lock_bh();
now = jiffies;
next = round_jiffies_up(now + ADDR_CHECK_FREQUENCY);
cancel_delayed_work(&net->ipv6.addr_chk_work);
for (i = 0; i < IN6_ADDR_HSIZE; i++) {
restart:
hlist_for_each_entry_rcu_bh(ifp, &net->ipv6.inet6_addr_lst[i], addr_lst) {
unsigned long age;
/* When setting preferred_lft to a value not zero or
* infinity, while valid_lft is infinity
* IFA_F_PERMANENT has a non-infinity life time.
*/
if ((ifp->flags & IFA_F_PERMANENT) &&
(ifp->prefered_lft == INFINITY_LIFE_TIME))
continue;
spin_lock(&ifp->lock);
/* We try to batch several events at once. */
age = (now - ifp->tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ;
if ((ifp->flags&IFA_F_TEMPORARY) &&
!(ifp->flags&IFA_F_TENTATIVE) &&
ifp->prefered_lft != INFINITY_LIFE_TIME &&
!ifp->regen_count && ifp->ifpub) {
/* This is a non-regenerated temporary addr. */
unsigned long regen_advance = ifp->idev->cnf.regen_max_retry *
ifp->idev->cnf.dad_transmits *
max(NEIGH_VAR(ifp->idev->nd_parms, RETRANS_TIME), HZ/100) / HZ;
if (age + regen_advance >= ifp->prefered_lft) {
struct inet6_ifaddr *ifpub = ifp->ifpub;
if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next))
next = ifp->tstamp + ifp->prefered_lft * HZ;
ifp->regen_count++;
in6_ifa_hold(ifp);
in6_ifa_hold(ifpub);
spin_unlock(&ifp->lock);
spin_lock(&ifpub->lock);
ifpub->regen_count = 0;
spin_unlock(&ifpub->lock);
rcu_read_unlock_bh();
ipv6_create_tempaddr(ifpub, true);
in6_ifa_put(ifpub);
in6_ifa_put(ifp);
rcu_read_lock_bh();
goto restart;
} else if (time_before(ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ, next))
next = ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ;
}
if (ifp->valid_lft != INFINITY_LIFE_TIME &&
age >= ifp->valid_lft) {
spin_unlock(&ifp->lock);
in6_ifa_hold(ifp);
rcu_read_unlock_bh();
ipv6_del_addr(ifp);
rcu_read_lock_bh();
goto restart;
} else if (ifp->prefered_lft == INFINITY_LIFE_TIME) {
spin_unlock(&ifp->lock);
continue;
} else if (age >= ifp->prefered_lft) {
/* jiffies - ifp->tstamp > age >= ifp->prefered_lft */
int deprecate = 0;
if (!(ifp->flags&IFA_F_DEPRECATED)) {
deprecate = 1;
ifp->flags |= IFA_F_DEPRECATED;
}
if ((ifp->valid_lft != INFINITY_LIFE_TIME) &&
(time_before(ifp->tstamp + ifp->valid_lft * HZ, next)))
next = ifp->tstamp + ifp->valid_lft * HZ;
spin_unlock(&ifp->lock);
if (deprecate) {
in6_ifa_hold(ifp);
ipv6_ifa_notify(0, ifp);
in6_ifa_put(ifp);
goto restart;
}
} else {
/* ifp->prefered_lft <= ifp->valid_lft */
if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next))
next = ifp->tstamp + ifp->prefered_lft * HZ;
spin_unlock(&ifp->lock);
}
}
}
next_sec = round_jiffies_up(next);
next_sched = next;
/* If rounded timeout is accurate enough, accept it. */
if (time_before(next_sec, next + ADDRCONF_TIMER_FUZZ))
next_sched = next_sec;
/* And minimum interval is ADDRCONF_TIMER_FUZZ_MAX. */
if (time_before(next_sched, jiffies + ADDRCONF_TIMER_FUZZ_MAX))
next_sched = jiffies + ADDRCONF_TIMER_FUZZ_MAX;
pr_debug("now = %lu, schedule = %lu, rounded schedule = %lu => %lu\n",
now, next, next_sec, next_sched);
mod_delayed_work(addrconf_wq, &net->ipv6.addr_chk_work, next_sched - now);
rcu_read_unlock_bh();
}
static void addrconf_verify_work(struct work_struct *w)
{
struct net *net = container_of(to_delayed_work(w), struct net,
ipv6.addr_chk_work);
rtnl_lock();
addrconf_verify_rtnl(net);
rtnl_unlock();
}
static void addrconf_verify(struct net *net)
{
mod_delayed_work(addrconf_wq, &net->ipv6.addr_chk_work, 0);
}
static struct in6_addr *extract_addr(struct nlattr *addr, struct nlattr *local,
struct in6_addr **peer_pfx)
{
struct in6_addr *pfx = NULL;
*peer_pfx = NULL;
if (addr)
pfx = nla_data(addr);
if (local) {
if (pfx && nla_memcmp(local, pfx, sizeof(*pfx)))
*peer_pfx = pfx;
pfx = nla_data(local);
}
return pfx;
}
static const struct nla_policy ifa_ipv6_policy[IFA_MAX+1] = {
[IFA_ADDRESS] = { .len = sizeof(struct in6_addr) },
[IFA_LOCAL] = { .len = sizeof(struct in6_addr) },
[IFA_CACHEINFO] = { .len = sizeof(struct ifa_cacheinfo) },
[IFA_FLAGS] = { .len = sizeof(u32) },
[IFA_RT_PRIORITY] = { .len = sizeof(u32) },
[IFA_TARGET_NETNSID] = { .type = NLA_S32 },
[IFA_PROTO] = { .type = NLA_U8 },
};
static int
inet6_rtm_deladdr(struct sk_buff *skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(skb->sk);
struct ifaddrmsg *ifm;
struct nlattr *tb[IFA_MAX+1];
struct in6_addr *pfx, *peer_pfx;
u32 ifa_flags;
int err;
err = nlmsg_parse_deprecated(nlh, sizeof(*ifm), tb, IFA_MAX,
ifa_ipv6_policy, extack);
if (err < 0)
return err;
ifm = nlmsg_data(nlh);
pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer_pfx);
if (!pfx)
return -EINVAL;
ifa_flags = tb[IFA_FLAGS] ? nla_get_u32(tb[IFA_FLAGS]) : ifm->ifa_flags;
/* We ignore other flags so far. */
ifa_flags &= IFA_F_MANAGETEMPADDR;
return inet6_addr_del(net, ifm->ifa_index, ifa_flags, pfx,
ifm->ifa_prefixlen, extack);
}
static int modify_prefix_route(struct inet6_ifaddr *ifp,
unsigned long expires, u32 flags,
bool modify_peer)
{
struct fib6_info *f6i;
u32 prio;
f6i = addrconf_get_prefix_route(modify_peer ? &ifp->peer_addr : &ifp->addr,
ifp->prefix_len,
ifp->idev->dev, 0, RTF_DEFAULT, true);
if (!f6i)
return -ENOENT;
prio = ifp->rt_priority ? : IP6_RT_PRIO_ADDRCONF;
if (f6i->fib6_metric != prio) {
/* delete old one */
ip6_del_rt(dev_net(ifp->idev->dev), f6i, false);
/* add new one */
addrconf_prefix_route(modify_peer ? &ifp->peer_addr : &ifp->addr,
ifp->prefix_len,
ifp->rt_priority, ifp->idev->dev,
expires, flags, GFP_KERNEL);
} else {
if (!expires)
fib6_clean_expires(f6i);
else
fib6_set_expires(f6i, expires);
fib6_info_release(f6i);
}
return 0;
}
static int inet6_addr_modify(struct net *net, struct inet6_ifaddr *ifp,
struct ifa6_config *cfg)
{
u32 flags;
clock_t expires;
unsigned long timeout;
bool was_managetempaddr;
bool had_prefixroute;
bool new_peer = false;
ASSERT_RTNL();
if (!cfg->valid_lft || cfg->preferred_lft > cfg->valid_lft)
return -EINVAL;
if (cfg->ifa_flags & IFA_F_MANAGETEMPADDR &&
(ifp->flags & IFA_F_TEMPORARY || ifp->prefix_len != 64))
return -EINVAL;
if (!(ifp->flags & IFA_F_TENTATIVE) || ifp->flags & IFA_F_DADFAILED)
cfg->ifa_flags &= ~IFA_F_OPTIMISTIC;
timeout = addrconf_timeout_fixup(cfg->valid_lft, HZ);
if (addrconf_finite_timeout(timeout)) {
expires = jiffies_to_clock_t(timeout * HZ);
cfg->valid_lft = timeout;
flags = RTF_EXPIRES;
} else {
expires = 0;
flags = 0;
cfg->ifa_flags |= IFA_F_PERMANENT;
}
timeout = addrconf_timeout_fixup(cfg->preferred_lft, HZ);
if (addrconf_finite_timeout(timeout)) {
if (timeout == 0)
cfg->ifa_flags |= IFA_F_DEPRECATED;
cfg->preferred_lft = timeout;
}
if (cfg->peer_pfx &&
memcmp(&ifp->peer_addr, cfg->peer_pfx, sizeof(struct in6_addr))) {
if (!ipv6_addr_any(&ifp->peer_addr))
cleanup_prefix_route(ifp, expires, true, true);
new_peer = true;
}
spin_lock_bh(&ifp->lock);
was_managetempaddr = ifp->flags & IFA_F_MANAGETEMPADDR;
had_prefixroute = ifp->flags & IFA_F_PERMANENT &&
!(ifp->flags & IFA_F_NOPREFIXROUTE);
ifp->flags &= ~(IFA_F_DEPRECATED | IFA_F_PERMANENT | IFA_F_NODAD |
IFA_F_HOMEADDRESS | IFA_F_MANAGETEMPADDR |
IFA_F_NOPREFIXROUTE);
ifp->flags |= cfg->ifa_flags;
ifp->tstamp = jiffies;
ifp->valid_lft = cfg->valid_lft;
ifp->prefered_lft = cfg->preferred_lft;
ifp->ifa_proto = cfg->ifa_proto;
if (cfg->rt_priority && cfg->rt_priority != ifp->rt_priority)
ifp->rt_priority = cfg->rt_priority;
if (new_peer)
ifp->peer_addr = *cfg->peer_pfx;
spin_unlock_bh(&ifp->lock);
if (!(ifp->flags&IFA_F_TENTATIVE))
ipv6_ifa_notify(0, ifp);
if (!(cfg->ifa_flags & IFA_F_NOPREFIXROUTE)) {
int rc = -ENOENT;
if (had_prefixroute)
rc = modify_prefix_route(ifp, expires, flags, false);
/* prefix route could have been deleted; if so restore it */
if (rc == -ENOENT) {
addrconf_prefix_route(&ifp->addr, ifp->prefix_len,
ifp->rt_priority, ifp->idev->dev,
expires, flags, GFP_KERNEL);
}
if (had_prefixroute && !ipv6_addr_any(&ifp->peer_addr))
rc = modify_prefix_route(ifp, expires, flags, true);
if (rc == -ENOENT && !ipv6_addr_any(&ifp->peer_addr)) {
addrconf_prefix_route(&ifp->peer_addr, ifp->prefix_len,
ifp->rt_priority, ifp->idev->dev,
expires, flags, GFP_KERNEL);
}
} else if (had_prefixroute) {
enum cleanup_prefix_rt_t action;
unsigned long rt_expires;
write_lock_bh(&ifp->idev->lock);
action = check_cleanup_prefix_route(ifp, &rt_expires);
write_unlock_bh(&ifp->idev->lock);
if (action != CLEANUP_PREFIX_RT_NOP) {
cleanup_prefix_route(ifp, rt_expires,
action == CLEANUP_PREFIX_RT_DEL, false);
}
}
if (was_managetempaddr || ifp->flags & IFA_F_MANAGETEMPADDR) {
if (was_managetempaddr &&
!(ifp->flags & IFA_F_MANAGETEMPADDR)) {
cfg->valid_lft = 0;
cfg->preferred_lft = 0;
}
manage_tempaddrs(ifp->idev, ifp, cfg->valid_lft,
cfg->preferred_lft, !was_managetempaddr,
jiffies);
}
addrconf_verify_rtnl(net);
return 0;
}
static int
inet6_rtm_newaddr(struct sk_buff *skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(skb->sk);
struct ifaddrmsg *ifm;
struct nlattr *tb[IFA_MAX+1];
struct in6_addr *peer_pfx;
struct inet6_ifaddr *ifa;
struct net_device *dev;
struct inet6_dev *idev;
struct ifa6_config cfg;
int err;
err = nlmsg_parse_deprecated(nlh, sizeof(*ifm), tb, IFA_MAX,
ifa_ipv6_policy, extack);
if (err < 0)
return err;
memset(&cfg, 0, sizeof(cfg));
ifm = nlmsg_data(nlh);
cfg.pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer_pfx);
if (!cfg.pfx)
return -EINVAL;
cfg.peer_pfx = peer_pfx;
cfg.plen = ifm->ifa_prefixlen;
if (tb[IFA_RT_PRIORITY])
cfg.rt_priority = nla_get_u32(tb[IFA_RT_PRIORITY]);
if (tb[IFA_PROTO])
cfg.ifa_proto = nla_get_u8(tb[IFA_PROTO]);
cfg.valid_lft = INFINITY_LIFE_TIME;
cfg.preferred_lft = INFINITY_LIFE_TIME;
if (tb[IFA_CACHEINFO]) {
struct ifa_cacheinfo *ci;
ci = nla_data(tb[IFA_CACHEINFO]);
cfg.valid_lft = ci->ifa_valid;
cfg.preferred_lft = ci->ifa_prefered;
}
dev = __dev_get_by_index(net, ifm->ifa_index);
if (!dev) {
NL_SET_ERR_MSG_MOD(extack, "Unable to find the interface");
return -ENODEV;
}
if (tb[IFA_FLAGS])
cfg.ifa_flags = nla_get_u32(tb[IFA_FLAGS]);
else
cfg.ifa_flags = ifm->ifa_flags;
/* We ignore other flags so far. */
cfg.ifa_flags &= IFA_F_NODAD | IFA_F_HOMEADDRESS |
IFA_F_MANAGETEMPADDR | IFA_F_NOPREFIXROUTE |
IFA_F_MCAUTOJOIN | IFA_F_OPTIMISTIC;
idev = ipv6_find_idev(dev);
if (IS_ERR(idev))
return PTR_ERR(idev);
if (!ipv6_allow_optimistic_dad(net, idev))
cfg.ifa_flags &= ~IFA_F_OPTIMISTIC;
if (cfg.ifa_flags & IFA_F_NODAD &&
cfg.ifa_flags & IFA_F_OPTIMISTIC) {
NL_SET_ERR_MSG(extack, "IFA_F_NODAD and IFA_F_OPTIMISTIC are mutually exclusive");
return -EINVAL;
}
ifa = ipv6_get_ifaddr(net, cfg.pfx, dev, 1);
if (!ifa) {
/*
* It would be best to check for !NLM_F_CREATE here but
* userspace already relies on not having to provide this.
*/
return inet6_addr_add(net, ifm->ifa_index, &cfg, extack);
}
if (nlh->nlmsg_flags & NLM_F_EXCL ||
!(nlh->nlmsg_flags & NLM_F_REPLACE)) {
NL_SET_ERR_MSG_MOD(extack, "address already assigned");
err = -EEXIST;
} else {
err = inet6_addr_modify(net, ifa, &cfg);
}
in6_ifa_put(ifa);
return err;
}
static void put_ifaddrmsg(struct nlmsghdr *nlh, u8 prefixlen, u32 flags,
u8 scope, int ifindex)
{
struct ifaddrmsg *ifm;
ifm = nlmsg_data(nlh);
ifm->ifa_family = AF_INET6;
ifm->ifa_prefixlen = prefixlen;
ifm->ifa_flags = flags;
ifm->ifa_scope = scope;
ifm->ifa_index = ifindex;
}
static int put_cacheinfo(struct sk_buff *skb, unsigned long cstamp,
unsigned long tstamp, u32 preferred, u32 valid)
{
struct ifa_cacheinfo ci;
ci.cstamp = cstamp_delta(cstamp);
ci.tstamp = cstamp_delta(tstamp);
ci.ifa_prefered = preferred;
ci.ifa_valid = valid;
return nla_put(skb, IFA_CACHEINFO, sizeof(ci), &ci);
}
static inline int rt_scope(int ifa_scope)
{
if (ifa_scope & IFA_HOST)
return RT_SCOPE_HOST;
else if (ifa_scope & IFA_LINK)
return RT_SCOPE_LINK;
else if (ifa_scope & IFA_SITE)
return RT_SCOPE_SITE;
else
return RT_SCOPE_UNIVERSE;
}
static inline int inet6_ifaddr_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct ifaddrmsg))
+ nla_total_size(16) /* IFA_LOCAL */
+ nla_total_size(16) /* IFA_ADDRESS */
+ nla_total_size(sizeof(struct ifa_cacheinfo))
+ nla_total_size(4) /* IFA_FLAGS */
+ nla_total_size(1) /* IFA_PROTO */
+ nla_total_size(4) /* IFA_RT_PRIORITY */;
}
enum addr_type_t {
UNICAST_ADDR,
MULTICAST_ADDR,
ANYCAST_ADDR,
};
struct inet6_fill_args {
u32 portid;
u32 seq;
int event;
unsigned int flags;
int netnsid;
int ifindex;
enum addr_type_t type;
};
static int inet6_fill_ifaddr(struct sk_buff *skb, struct inet6_ifaddr *ifa,
struct inet6_fill_args *args)
{
struct nlmsghdr *nlh;
u32 preferred, valid;
nlh = nlmsg_put(skb, args->portid, args->seq, args->event,
sizeof(struct ifaddrmsg), args->flags);
if (!nlh)
return -EMSGSIZE;
put_ifaddrmsg(nlh, ifa->prefix_len, ifa->flags, rt_scope(ifa->scope),
ifa->idev->dev->ifindex);
if (args->netnsid >= 0 &&
nla_put_s32(skb, IFA_TARGET_NETNSID, args->netnsid))
goto error;
spin_lock_bh(&ifa->lock);
if (!((ifa->flags&IFA_F_PERMANENT) &&
(ifa->prefered_lft == INFINITY_LIFE_TIME))) {
preferred = ifa->prefered_lft;
valid = ifa->valid_lft;
if (preferred != INFINITY_LIFE_TIME) {
long tval = (jiffies - ifa->tstamp)/HZ;
if (preferred > tval)
preferred -= tval;
else
preferred = 0;
if (valid != INFINITY_LIFE_TIME) {
if (valid > tval)
valid -= tval;
else
valid = 0;
}
}
} else {
preferred = INFINITY_LIFE_TIME;
valid = INFINITY_LIFE_TIME;
}
spin_unlock_bh(&ifa->lock);
if (!ipv6_addr_any(&ifa->peer_addr)) {
if (nla_put_in6_addr(skb, IFA_LOCAL, &ifa->addr) < 0 ||
nla_put_in6_addr(skb, IFA_ADDRESS, &ifa->peer_addr) < 0)
goto error;
} else
if (nla_put_in6_addr(skb, IFA_ADDRESS, &ifa->addr) < 0)
goto error;
if (ifa->rt_priority &&
nla_put_u32(skb, IFA_RT_PRIORITY, ifa->rt_priority))
goto error;
if (put_cacheinfo(skb, ifa->cstamp, ifa->tstamp, preferred, valid) < 0)
goto error;
if (nla_put_u32(skb, IFA_FLAGS, ifa->flags) < 0)
goto error;
if (ifa->ifa_proto &&
nla_put_u8(skb, IFA_PROTO, ifa->ifa_proto))
goto error;
nlmsg_end(skb, nlh);
return 0;
error:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int inet6_fill_ifmcaddr(struct sk_buff *skb, struct ifmcaddr6 *ifmca,
struct inet6_fill_args *args)
{
struct nlmsghdr *nlh;
u8 scope = RT_SCOPE_UNIVERSE;
int ifindex = ifmca->idev->dev->ifindex;
if (ipv6_addr_scope(&ifmca->mca_addr) & IFA_SITE)
scope = RT_SCOPE_SITE;
nlh = nlmsg_put(skb, args->portid, args->seq, args->event,
sizeof(struct ifaddrmsg), args->flags);
if (!nlh)
return -EMSGSIZE;
if (args->netnsid >= 0 &&
nla_put_s32(skb, IFA_TARGET_NETNSID, args->netnsid)) {
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex);
if (nla_put_in6_addr(skb, IFA_MULTICAST, &ifmca->mca_addr) < 0 ||
put_cacheinfo(skb, ifmca->mca_cstamp, ifmca->mca_tstamp,
INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) {
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
nlmsg_end(skb, nlh);
return 0;
}
static int inet6_fill_ifacaddr(struct sk_buff *skb, struct ifacaddr6 *ifaca,
struct inet6_fill_args *args)
{
struct net_device *dev = fib6_info_nh_dev(ifaca->aca_rt);
int ifindex = dev ? dev->ifindex : 1;
struct nlmsghdr *nlh;
u8 scope = RT_SCOPE_UNIVERSE;
if (ipv6_addr_scope(&ifaca->aca_addr) & IFA_SITE)
scope = RT_SCOPE_SITE;
nlh = nlmsg_put(skb, args->portid, args->seq, args->event,
sizeof(struct ifaddrmsg), args->flags);
if (!nlh)
return -EMSGSIZE;
if (args->netnsid >= 0 &&
nla_put_s32(skb, IFA_TARGET_NETNSID, args->netnsid)) {
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex);
if (nla_put_in6_addr(skb, IFA_ANYCAST, &ifaca->aca_addr) < 0 ||
put_cacheinfo(skb, ifaca->aca_cstamp, ifaca->aca_tstamp,
INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) {
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
nlmsg_end(skb, nlh);
return 0;
}
/* called with rcu_read_lock() */
static int in6_dump_addrs(struct inet6_dev *idev, struct sk_buff *skb,
struct netlink_callback *cb, int s_ip_idx,
struct inet6_fill_args *fillargs)
{
struct ifmcaddr6 *ifmca;
struct ifacaddr6 *ifaca;
int ip_idx = 0;
int err = 1;
read_lock_bh(&idev->lock);
switch (fillargs->type) {
case UNICAST_ADDR: {
struct inet6_ifaddr *ifa;
fillargs->event = RTM_NEWADDR;
/* unicast address incl. temp addr */
list_for_each_entry(ifa, &idev->addr_list, if_list) {
if (ip_idx < s_ip_idx)
goto next;
err = inet6_fill_ifaddr(skb, ifa, fillargs);
if (err < 0)
break;
nl_dump_check_consistent(cb, nlmsg_hdr(skb));
next:
ip_idx++;
}
break;
}
case MULTICAST_ADDR:
read_unlock_bh(&idev->lock);
fillargs->event = RTM_GETMULTICAST;
/* multicast address */
for (ifmca = rtnl_dereference(idev->mc_list);
ifmca;
ifmca = rtnl_dereference(ifmca->next), ip_idx++) {
if (ip_idx < s_ip_idx)
continue;
err = inet6_fill_ifmcaddr(skb, ifmca, fillargs);
if (err < 0)
break;
}
read_lock_bh(&idev->lock);
break;
case ANYCAST_ADDR:
fillargs->event = RTM_GETANYCAST;
/* anycast address */
for (ifaca = idev->ac_list; ifaca;
ifaca = ifaca->aca_next, ip_idx++) {
if (ip_idx < s_ip_idx)
continue;
err = inet6_fill_ifacaddr(skb, ifaca, fillargs);
if (err < 0)
break;
}
break;
default:
break;
}
read_unlock_bh(&idev->lock);
cb->args[2] = ip_idx;
return err;
}
static int inet6_valid_dump_ifaddr_req(const struct nlmsghdr *nlh,
struct inet6_fill_args *fillargs,
struct net **tgt_net, struct sock *sk,
struct netlink_callback *cb)
{
struct netlink_ext_ack *extack = cb->extack;
struct nlattr *tb[IFA_MAX+1];
struct ifaddrmsg *ifm;
int err, i;
if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*ifm))) {
NL_SET_ERR_MSG_MOD(extack, "Invalid header for address dump request");
return -EINVAL;
}
ifm = nlmsg_data(nlh);
if (ifm->ifa_prefixlen || ifm->ifa_flags || ifm->ifa_scope) {
NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for address dump request");
return -EINVAL;
}
fillargs->ifindex = ifm->ifa_index;
if (fillargs->ifindex) {
cb->answer_flags |= NLM_F_DUMP_FILTERED;
fillargs->flags |= NLM_F_DUMP_FILTERED;
}
err = nlmsg_parse_deprecated_strict(nlh, sizeof(*ifm), tb, IFA_MAX,
ifa_ipv6_policy, extack);
if (err < 0)
return err;
for (i = 0; i <= IFA_MAX; ++i) {
if (!tb[i])
continue;
if (i == IFA_TARGET_NETNSID) {
struct net *net;
fillargs->netnsid = nla_get_s32(tb[i]);
net = rtnl_get_net_ns_capable(sk, fillargs->netnsid);
if (IS_ERR(net)) {
fillargs->netnsid = -1;
NL_SET_ERR_MSG_MOD(extack, "Invalid target network namespace id");
return PTR_ERR(net);
}
*tgt_net = net;
} else {
NL_SET_ERR_MSG_MOD(extack, "Unsupported attribute in dump request");
return -EINVAL;
}
}
return 0;
}
static int inet6_dump_addr(struct sk_buff *skb, struct netlink_callback *cb,
enum addr_type_t type)
{
const struct nlmsghdr *nlh = cb->nlh;
struct inet6_fill_args fillargs = {
.portid = NETLINK_CB(cb->skb).portid,
.seq = cb->nlh->nlmsg_seq,
.flags = NLM_F_MULTI,
.netnsid = -1,
.type = type,
};
struct net *tgt_net = sock_net(skb->sk);
int idx, s_idx, s_ip_idx;
int h, s_h;
struct net_device *dev;
struct inet6_dev *idev;
struct hlist_head *head;
int err = 0;
s_h = cb->args[0];
s_idx = idx = cb->args[1];
s_ip_idx = cb->args[2];
if (cb->strict_check) {
err = inet6_valid_dump_ifaddr_req(nlh, &fillargs, &tgt_net,
skb->sk, cb);
if (err < 0)
goto put_tgt_net;
err = 0;
if (fillargs.ifindex) {
dev = __dev_get_by_index(tgt_net, fillargs.ifindex);
if (!dev) {
err = -ENODEV;
goto put_tgt_net;
}
idev = __in6_dev_get(dev);
if (idev) {
err = in6_dump_addrs(idev, skb, cb, s_ip_idx,
&fillargs);
if (err > 0)
err = 0;
}
goto put_tgt_net;
}
}
rcu_read_lock();
cb->seq = atomic_read(&tgt_net->ipv6.dev_addr_genid) ^ tgt_net->dev_base_seq;
for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
idx = 0;
head = &tgt_net->dev_index_head[h];
hlist_for_each_entry_rcu(dev, head, index_hlist) {
if (idx < s_idx)
goto cont;
if (h > s_h || idx > s_idx)
s_ip_idx = 0;
idev = __in6_dev_get(dev);
if (!idev)
goto cont;
if (in6_dump_addrs(idev, skb, cb, s_ip_idx,
&fillargs) < 0)
goto done;
cont:
idx++;
}
}
done:
rcu_read_unlock();
cb->args[0] = h;
cb->args[1] = idx;
put_tgt_net:
if (fillargs.netnsid >= 0)
put_net(tgt_net);
return skb->len ? : err;
}
static int inet6_dump_ifaddr(struct sk_buff *skb, struct netlink_callback *cb)
{
enum addr_type_t type = UNICAST_ADDR;
return inet6_dump_addr(skb, cb, type);
}
static int inet6_dump_ifmcaddr(struct sk_buff *skb, struct netlink_callback *cb)
{
enum addr_type_t type = MULTICAST_ADDR;
return inet6_dump_addr(skb, cb, type);
}
static int inet6_dump_ifacaddr(struct sk_buff *skb, struct netlink_callback *cb)
{
enum addr_type_t type = ANYCAST_ADDR;
return inet6_dump_addr(skb, cb, type);
}
static int inet6_rtm_valid_getaddr_req(struct sk_buff *skb,
const struct nlmsghdr *nlh,
struct nlattr **tb,
struct netlink_ext_ack *extack)
{
struct ifaddrmsg *ifm;
int i, err;
if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*ifm))) {
NL_SET_ERR_MSG_MOD(extack, "Invalid header for get address request");
return -EINVAL;
}
if (!netlink_strict_get_check(skb))
return nlmsg_parse_deprecated(nlh, sizeof(*ifm), tb, IFA_MAX,
ifa_ipv6_policy, extack);
ifm = nlmsg_data(nlh);
if (ifm->ifa_prefixlen || ifm->ifa_flags || ifm->ifa_scope) {
NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for get address request");
return -EINVAL;
}
err = nlmsg_parse_deprecated_strict(nlh, sizeof(*ifm), tb, IFA_MAX,
ifa_ipv6_policy, extack);
if (err)
return err;
for (i = 0; i <= IFA_MAX; i++) {
if (!tb[i])
continue;
switch (i) {
case IFA_TARGET_NETNSID:
case IFA_ADDRESS:
case IFA_LOCAL:
break;
default:
NL_SET_ERR_MSG_MOD(extack, "Unsupported attribute in get address request");
return -EINVAL;
}
}
return 0;
}
static int inet6_rtm_getaddr(struct sk_buff *in_skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *tgt_net = sock_net(in_skb->sk);
struct inet6_fill_args fillargs = {
.portid = NETLINK_CB(in_skb).portid,
.seq = nlh->nlmsg_seq,
.event = RTM_NEWADDR,
.flags = 0,
.netnsid = -1,
};
struct ifaddrmsg *ifm;
struct nlattr *tb[IFA_MAX+1];
struct in6_addr *addr = NULL, *peer;
struct net_device *dev = NULL;
struct inet6_ifaddr *ifa;
struct sk_buff *skb;
int err;
err = inet6_rtm_valid_getaddr_req(in_skb, nlh, tb, extack);
if (err < 0)
return err;
if (tb[IFA_TARGET_NETNSID]) {
fillargs.netnsid = nla_get_s32(tb[IFA_TARGET_NETNSID]);
tgt_net = rtnl_get_net_ns_capable(NETLINK_CB(in_skb).sk,
fillargs.netnsid);
if (IS_ERR(tgt_net))
return PTR_ERR(tgt_net);
}
addr = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer);
if (!addr)
return -EINVAL;
ifm = nlmsg_data(nlh);
if (ifm->ifa_index)
dev = dev_get_by_index(tgt_net, ifm->ifa_index);
ifa = ipv6_get_ifaddr(tgt_net, addr, dev, 1);
if (!ifa) {
err = -EADDRNOTAVAIL;
goto errout;
}
skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_KERNEL);
if (!skb) {
err = -ENOBUFS;
goto errout_ifa;
}
err = inet6_fill_ifaddr(skb, ifa, &fillargs);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout_ifa;
}
err = rtnl_unicast(skb, tgt_net, NETLINK_CB(in_skb).portid);
errout_ifa:
in6_ifa_put(ifa);
errout:
dev_put(dev);
if (fillargs.netnsid >= 0)
put_net(tgt_net);
return err;
}
static void inet6_ifa_notify(int event, struct inet6_ifaddr *ifa)
{
struct sk_buff *skb;
struct net *net = dev_net(ifa->idev->dev);
struct inet6_fill_args fillargs = {
.portid = 0,
.seq = 0,
.event = event,
.flags = 0,
.netnsid = -1,
};
int err = -ENOBUFS;
skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_ATOMIC);
if (!skb)
goto errout;
err = inet6_fill_ifaddr(skb, ifa, &fillargs);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFADDR, NULL, GFP_ATOMIC);
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_IPV6_IFADDR, err);
}
static inline void ipv6_store_devconf(struct ipv6_devconf *cnf,
__s32 *array, int bytes)
{
BUG_ON(bytes < (DEVCONF_MAX * 4));
memset(array, 0, bytes);
array[DEVCONF_FORWARDING] = cnf->forwarding;
array[DEVCONF_HOPLIMIT] = cnf->hop_limit;
array[DEVCONF_MTU6] = cnf->mtu6;
array[DEVCONF_ACCEPT_RA] = cnf->accept_ra;
array[DEVCONF_ACCEPT_REDIRECTS] = cnf->accept_redirects;
array[DEVCONF_AUTOCONF] = cnf->autoconf;
array[DEVCONF_DAD_TRANSMITS] = cnf->dad_transmits;
array[DEVCONF_RTR_SOLICITS] = cnf->rtr_solicits;
array[DEVCONF_RTR_SOLICIT_INTERVAL] =
jiffies_to_msecs(cnf->rtr_solicit_interval);
array[DEVCONF_RTR_SOLICIT_MAX_INTERVAL] =
jiffies_to_msecs(cnf->rtr_solicit_max_interval);
array[DEVCONF_RTR_SOLICIT_DELAY] =
jiffies_to_msecs(cnf->rtr_solicit_delay);
array[DEVCONF_FORCE_MLD_VERSION] = cnf->force_mld_version;
array[DEVCONF_MLDV1_UNSOLICITED_REPORT_INTERVAL] =
jiffies_to_msecs(cnf->mldv1_unsolicited_report_interval);
array[DEVCONF_MLDV2_UNSOLICITED_REPORT_INTERVAL] =
jiffies_to_msecs(cnf->mldv2_unsolicited_report_interval);
array[DEVCONF_USE_TEMPADDR] = cnf->use_tempaddr;
array[DEVCONF_TEMP_VALID_LFT] = cnf->temp_valid_lft;
array[DEVCONF_TEMP_PREFERED_LFT] = cnf->temp_prefered_lft;
array[DEVCONF_REGEN_MAX_RETRY] = cnf->regen_max_retry;
array[DEVCONF_MAX_DESYNC_FACTOR] = cnf->max_desync_factor;
array[DEVCONF_MAX_ADDRESSES] = cnf->max_addresses;
array[DEVCONF_ACCEPT_RA_DEFRTR] = cnf->accept_ra_defrtr;
array[DEVCONF_RA_DEFRTR_METRIC] = cnf->ra_defrtr_metric;
array[DEVCONF_ACCEPT_RA_MIN_HOP_LIMIT] = cnf->accept_ra_min_hop_limit;
array[DEVCONF_ACCEPT_RA_PINFO] = cnf->accept_ra_pinfo;
#ifdef CONFIG_IPV6_ROUTER_PREF
array[DEVCONF_ACCEPT_RA_RTR_PREF] = cnf->accept_ra_rtr_pref;
array[DEVCONF_RTR_PROBE_INTERVAL] =
jiffies_to_msecs(cnf->rtr_probe_interval);
#ifdef CONFIG_IPV6_ROUTE_INFO
array[DEVCONF_ACCEPT_RA_RT_INFO_MIN_PLEN] = cnf->accept_ra_rt_info_min_plen;
array[DEVCONF_ACCEPT_RA_RT_INFO_MAX_PLEN] = cnf->accept_ra_rt_info_max_plen;
#endif
#endif
array[DEVCONF_PROXY_NDP] = cnf->proxy_ndp;
array[DEVCONF_ACCEPT_SOURCE_ROUTE] = cnf->accept_source_route;
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
array[DEVCONF_OPTIMISTIC_DAD] = cnf->optimistic_dad;
array[DEVCONF_USE_OPTIMISTIC] = cnf->use_optimistic;
#endif
#ifdef CONFIG_IPV6_MROUTE
array[DEVCONF_MC_FORWARDING] = atomic_read(&cnf->mc_forwarding);
#endif
array[DEVCONF_DISABLE_IPV6] = cnf->disable_ipv6;
array[DEVCONF_ACCEPT_DAD] = cnf->accept_dad;
array[DEVCONF_FORCE_TLLAO] = cnf->force_tllao;
array[DEVCONF_NDISC_NOTIFY] = cnf->ndisc_notify;
array[DEVCONF_SUPPRESS_FRAG_NDISC] = cnf->suppress_frag_ndisc;
array[DEVCONF_ACCEPT_RA_FROM_LOCAL] = cnf->accept_ra_from_local;
array[DEVCONF_ACCEPT_RA_MTU] = cnf->accept_ra_mtu;
array[DEVCONF_IGNORE_ROUTES_WITH_LINKDOWN] = cnf->ignore_routes_with_linkdown;
/* we omit DEVCONF_STABLE_SECRET for now */
array[DEVCONF_USE_OIF_ADDRS_ONLY] = cnf->use_oif_addrs_only;
array[DEVCONF_DROP_UNICAST_IN_L2_MULTICAST] = cnf->drop_unicast_in_l2_multicast;
array[DEVCONF_DROP_UNSOLICITED_NA] = cnf->drop_unsolicited_na;
array[DEVCONF_KEEP_ADDR_ON_DOWN] = cnf->keep_addr_on_down;
array[DEVCONF_SEG6_ENABLED] = cnf->seg6_enabled;
#ifdef CONFIG_IPV6_SEG6_HMAC
array[DEVCONF_SEG6_REQUIRE_HMAC] = cnf->seg6_require_hmac;
#endif
array[DEVCONF_ENHANCED_DAD] = cnf->enhanced_dad;
array[DEVCONF_ADDR_GEN_MODE] = cnf->addr_gen_mode;
array[DEVCONF_DISABLE_POLICY] = cnf->disable_policy;
array[DEVCONF_NDISC_TCLASS] = cnf->ndisc_tclass;
array[DEVCONF_RPL_SEG_ENABLED] = cnf->rpl_seg_enabled;
array[DEVCONF_IOAM6_ENABLED] = cnf->ioam6_enabled;
array[DEVCONF_IOAM6_ID] = cnf->ioam6_id;
array[DEVCONF_IOAM6_ID_WIDE] = cnf->ioam6_id_wide;
array[DEVCONF_NDISC_EVICT_NOCARRIER] = cnf->ndisc_evict_nocarrier;
array[DEVCONF_ACCEPT_UNTRACKED_NA] = cnf->accept_untracked_na;
array[DEVCONF_ACCEPT_RA_MIN_LFT] = cnf->accept_ra_min_lft;
}
static inline size_t inet6_ifla6_size(void)
{
return nla_total_size(4) /* IFLA_INET6_FLAGS */
+ nla_total_size(sizeof(struct ifla_cacheinfo))
+ nla_total_size(DEVCONF_MAX * 4) /* IFLA_INET6_CONF */
+ nla_total_size(IPSTATS_MIB_MAX * 8) /* IFLA_INET6_STATS */
+ nla_total_size(ICMP6_MIB_MAX * 8) /* IFLA_INET6_ICMP6STATS */
+ nla_total_size(sizeof(struct in6_addr)) /* IFLA_INET6_TOKEN */
+ nla_total_size(1) /* IFLA_INET6_ADDR_GEN_MODE */
+ nla_total_size(4) /* IFLA_INET6_RA_MTU */
+ 0;
}
static inline size_t inet6_if_nlmsg_size(void)
{
return NLMSG_ALIGN(sizeof(struct ifinfomsg))
+ nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */
+ nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */
+ nla_total_size(4) /* IFLA_MTU */
+ nla_total_size(4) /* IFLA_LINK */
+ nla_total_size(1) /* IFLA_OPERSTATE */
+ nla_total_size(inet6_ifla6_size()); /* IFLA_PROTINFO */
}
static inline void __snmp6_fill_statsdev(u64 *stats, atomic_long_t *mib,
int bytes)
{
int i;
int pad = bytes - sizeof(u64) * ICMP6_MIB_MAX;
BUG_ON(pad < 0);
/* Use put_unaligned() because stats may not be aligned for u64. */
put_unaligned(ICMP6_MIB_MAX, &stats[0]);
for (i = 1; i < ICMP6_MIB_MAX; i++)
put_unaligned(atomic_long_read(&mib[i]), &stats[i]);
memset(&stats[ICMP6_MIB_MAX], 0, pad);
}
static inline void __snmp6_fill_stats64(u64 *stats, void __percpu *mib,
int bytes, size_t syncpoff)
{
int i, c;
u64 buff[IPSTATS_MIB_MAX];
int pad = bytes - sizeof(u64) * IPSTATS_MIB_MAX;
BUG_ON(pad < 0);
memset(buff, 0, sizeof(buff));
buff[0] = IPSTATS_MIB_MAX;
for_each_possible_cpu(c) {
for (i = 1; i < IPSTATS_MIB_MAX; i++)
buff[i] += snmp_get_cpu_field64(mib, c, i, syncpoff);
}
memcpy(stats, buff, IPSTATS_MIB_MAX * sizeof(u64));
memset(&stats[IPSTATS_MIB_MAX], 0, pad);
}
static void snmp6_fill_stats(u64 *stats, struct inet6_dev *idev, int attrtype,
int bytes)
{
switch (attrtype) {
case IFLA_INET6_STATS:
__snmp6_fill_stats64(stats, idev->stats.ipv6, bytes,
offsetof(struct ipstats_mib, syncp));
break;
case IFLA_INET6_ICMP6STATS:
__snmp6_fill_statsdev(stats, idev->stats.icmpv6dev->mibs, bytes);
break;
}
}
static int inet6_fill_ifla6_attrs(struct sk_buff *skb, struct inet6_dev *idev,
u32 ext_filter_mask)
{
struct nlattr *nla;
struct ifla_cacheinfo ci;
if (nla_put_u32(skb, IFLA_INET6_FLAGS, idev->if_flags))
goto nla_put_failure;
ci.max_reasm_len = IPV6_MAXPLEN;
ci.tstamp = cstamp_delta(idev->tstamp);
ci.reachable_time = jiffies_to_msecs(idev->nd_parms->reachable_time);
ci.retrans_time = jiffies_to_msecs(NEIGH_VAR(idev->nd_parms, RETRANS_TIME));
if (nla_put(skb, IFLA_INET6_CACHEINFO, sizeof(ci), &ci))
goto nla_put_failure;
nla = nla_reserve(skb, IFLA_INET6_CONF, DEVCONF_MAX * sizeof(s32));
if (!nla)
goto nla_put_failure;
ipv6_store_devconf(&idev->cnf, nla_data(nla), nla_len(nla));
/* XXX - MC not implemented */
if (ext_filter_mask & RTEXT_FILTER_SKIP_STATS)
return 0;
nla = nla_reserve(skb, IFLA_INET6_STATS, IPSTATS_MIB_MAX * sizeof(u64));
if (!nla)
goto nla_put_failure;
snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_STATS, nla_len(nla));
nla = nla_reserve(skb, IFLA_INET6_ICMP6STATS, ICMP6_MIB_MAX * sizeof(u64));
if (!nla)
goto nla_put_failure;
snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_ICMP6STATS, nla_len(nla));
nla = nla_reserve(skb, IFLA_INET6_TOKEN, sizeof(struct in6_addr));
if (!nla)
goto nla_put_failure;
read_lock_bh(&idev->lock);
memcpy(nla_data(nla), idev->token.s6_addr, nla_len(nla));
read_unlock_bh(&idev->lock);
if (nla_put_u8(skb, IFLA_INET6_ADDR_GEN_MODE, idev->cnf.addr_gen_mode))
goto nla_put_failure;
if (idev->ra_mtu &&
nla_put_u32(skb, IFLA_INET6_RA_MTU, idev->ra_mtu))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
static size_t inet6_get_link_af_size(const struct net_device *dev,
u32 ext_filter_mask)
{
if (!__in6_dev_get(dev))
return 0;
return inet6_ifla6_size();
}
static int inet6_fill_link_af(struct sk_buff *skb, const struct net_device *dev,
u32 ext_filter_mask)
{
struct inet6_dev *idev = __in6_dev_get(dev);
if (!idev)
return -ENODATA;
if (inet6_fill_ifla6_attrs(skb, idev, ext_filter_mask) < 0)
return -EMSGSIZE;
return 0;
}
static int inet6_set_iftoken(struct inet6_dev *idev, struct in6_addr *token,
struct netlink_ext_ack *extack)
{
struct inet6_ifaddr *ifp;
struct net_device *dev = idev->dev;
bool clear_token, update_rs = false;
struct in6_addr ll_addr;
ASSERT_RTNL();
if (!token)
return -EINVAL;
if (dev->flags & IFF_LOOPBACK) {
NL_SET_ERR_MSG_MOD(extack, "Device is loopback");
return -EINVAL;
}
if (dev->flags & IFF_NOARP) {
NL_SET_ERR_MSG_MOD(extack,
"Device does not do neighbour discovery");
return -EINVAL;
}
if (!ipv6_accept_ra(idev)) {
NL_SET_ERR_MSG_MOD(extack,
"Router advertisement is disabled on device");
return -EINVAL;
}
if (idev->cnf.rtr_solicits == 0) {
NL_SET_ERR_MSG(extack,
"Router solicitation is disabled on device");
return -EINVAL;
}
write_lock_bh(&idev->lock);
BUILD_BUG_ON(sizeof(token->s6_addr) != 16);
memcpy(idev->token.s6_addr + 8, token->s6_addr + 8, 8);
write_unlock_bh(&idev->lock);
clear_token = ipv6_addr_any(token);
if (clear_token)
goto update_lft;
if (!idev->dead && (idev->if_flags & IF_READY) &&
!ipv6_get_lladdr(dev, &ll_addr, IFA_F_TENTATIVE |
IFA_F_OPTIMISTIC)) {
/* If we're not ready, then normal ifup will take care
* of this. Otherwise, we need to request our rs here.
*/
ndisc_send_rs(dev, &ll_addr, &in6addr_linklocal_allrouters);
update_rs = true;
}
update_lft:
write_lock_bh(&idev->lock);
if (update_rs) {
idev->if_flags |= IF_RS_SENT;
idev->rs_interval = rfc3315_s14_backoff_init(
idev->cnf.rtr_solicit_interval);
idev->rs_probes = 1;
addrconf_mod_rs_timer(idev, idev->rs_interval);
}
/* Well, that's kinda nasty ... */
list_for_each_entry(ifp, &idev->addr_list, if_list) {
spin_lock(&ifp->lock);
if (ifp->tokenized) {
ifp->valid_lft = 0;
ifp->prefered_lft = 0;
}
spin_unlock(&ifp->lock);
}
write_unlock_bh(&idev->lock);
inet6_ifinfo_notify(RTM_NEWLINK, idev);
addrconf_verify_rtnl(dev_net(dev));
return 0;
}
static const struct nla_policy inet6_af_policy[IFLA_INET6_MAX + 1] = {
[IFLA_INET6_ADDR_GEN_MODE] = { .type = NLA_U8 },
[IFLA_INET6_TOKEN] = { .len = sizeof(struct in6_addr) },
[IFLA_INET6_RA_MTU] = { .type = NLA_REJECT,
.reject_message =
"IFLA_INET6_RA_MTU can not be set" },
};
static int check_addr_gen_mode(int mode)
{
if (mode != IN6_ADDR_GEN_MODE_EUI64 &&
mode != IN6_ADDR_GEN_MODE_NONE &&
mode != IN6_ADDR_GEN_MODE_STABLE_PRIVACY &&
mode != IN6_ADDR_GEN_MODE_RANDOM)
return -EINVAL;
return 1;
}
static int check_stable_privacy(struct inet6_dev *idev, struct net *net,
int mode)
{
if (mode == IN6_ADDR_GEN_MODE_STABLE_PRIVACY &&
!idev->cnf.stable_secret.initialized &&
!net->ipv6.devconf_dflt->stable_secret.initialized)
return -EINVAL;
return 1;
}
static int inet6_validate_link_af(const struct net_device *dev,
const struct nlattr *nla,
struct netlink_ext_ack *extack)
{
struct nlattr *tb[IFLA_INET6_MAX + 1];
struct inet6_dev *idev = NULL;
int err;
if (dev) {
idev = __in6_dev_get(dev);
if (!idev)
return -EAFNOSUPPORT;
}
err = nla_parse_nested_deprecated(tb, IFLA_INET6_MAX, nla,
inet6_af_policy, extack);
if (err)
return err;
if (!tb[IFLA_INET6_TOKEN] && !tb[IFLA_INET6_ADDR_GEN_MODE])
return -EINVAL;
if (tb[IFLA_INET6_ADDR_GEN_MODE]) {
u8 mode = nla_get_u8(tb[IFLA_INET6_ADDR_GEN_MODE]);
if (check_addr_gen_mode(mode) < 0)
return -EINVAL;
if (dev && check_stable_privacy(idev, dev_net(dev), mode) < 0)
return -EINVAL;
}
return 0;
}
static int inet6_set_link_af(struct net_device *dev, const struct nlattr *nla,
struct netlink_ext_ack *extack)
{
struct inet6_dev *idev = __in6_dev_get(dev);
struct nlattr *tb[IFLA_INET6_MAX + 1];
int err;
if (!idev)
return -EAFNOSUPPORT;
if (nla_parse_nested_deprecated(tb, IFLA_INET6_MAX, nla, NULL, NULL) < 0)
return -EINVAL;
if (tb[IFLA_INET6_TOKEN]) {
err = inet6_set_iftoken(idev, nla_data(tb[IFLA_INET6_TOKEN]),
extack);
if (err)
return err;
}
if (tb[IFLA_INET6_ADDR_GEN_MODE]) {
u8 mode = nla_get_u8(tb[IFLA_INET6_ADDR_GEN_MODE]);
idev->cnf.addr_gen_mode = mode;
}
return 0;
}
static int inet6_fill_ifinfo(struct sk_buff *skb, struct inet6_dev *idev,
u32 portid, u32 seq, int event, unsigned int flags)
{
struct net_device *dev = idev->dev;
struct ifinfomsg *hdr;
struct nlmsghdr *nlh;
void *protoinfo;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*hdr), flags);
if (!nlh)
return -EMSGSIZE;
hdr = nlmsg_data(nlh);
hdr->ifi_family = AF_INET6;
hdr->__ifi_pad = 0;
hdr->ifi_type = dev->type;
hdr->ifi_index = dev->ifindex;
hdr->ifi_flags = dev_get_flags(dev);
hdr->ifi_change = 0;
if (nla_put_string(skb, IFLA_IFNAME, dev->name) ||
(dev->addr_len &&
nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr)) ||
nla_put_u32(skb, IFLA_MTU, dev->mtu) ||
(dev->ifindex != dev_get_iflink(dev) &&
nla_put_u32(skb, IFLA_LINK, dev_get_iflink(dev))) ||
nla_put_u8(skb, IFLA_OPERSTATE,
netif_running(dev) ? dev->operstate : IF_OPER_DOWN))
goto nla_put_failure;
protoinfo = nla_nest_start_noflag(skb, IFLA_PROTINFO);
if (!protoinfo)
goto nla_put_failure;
if (inet6_fill_ifla6_attrs(skb, idev, 0) < 0)
goto nla_put_failure;
nla_nest_end(skb, protoinfo);
nlmsg_end(skb, nlh);
return 0;
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int inet6_valid_dump_ifinfo(const struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct ifinfomsg *ifm;
if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*ifm))) {
NL_SET_ERR_MSG_MOD(extack, "Invalid header for link dump request");
return -EINVAL;
}
if (nlmsg_attrlen(nlh, sizeof(*ifm))) {
NL_SET_ERR_MSG_MOD(extack, "Invalid data after header");
return -EINVAL;
}
ifm = nlmsg_data(nlh);
if (ifm->__ifi_pad || ifm->ifi_type || ifm->ifi_flags ||
ifm->ifi_change || ifm->ifi_index) {
NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for dump request");
return -EINVAL;
}
return 0;
}
static int inet6_dump_ifinfo(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
int h, s_h;
int idx = 0, s_idx;
struct net_device *dev;
struct inet6_dev *idev;
struct hlist_head *head;
/* only requests using strict checking can pass data to
* influence the dump
*/
if (cb->strict_check) {
int err = inet6_valid_dump_ifinfo(cb->nlh, cb->extack);
if (err < 0)
return err;
}
s_h = cb->args[0];
s_idx = cb->args[1];
rcu_read_lock();
for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
idx = 0;
head = &net->dev_index_head[h];
hlist_for_each_entry_rcu(dev, head, index_hlist) {
if (idx < s_idx)
goto cont;
idev = __in6_dev_get(dev);
if (!idev)
goto cont;
if (inet6_fill_ifinfo(skb, idev,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
RTM_NEWLINK, NLM_F_MULTI) < 0)
goto out;
cont:
idx++;
}
}
out:
rcu_read_unlock();
cb->args[1] = idx;
cb->args[0] = h;
return skb->len;
}
void inet6_ifinfo_notify(int event, struct inet6_dev *idev)
{
struct sk_buff *skb;
struct net *net = dev_net(idev->dev);
int err = -ENOBUFS;
skb = nlmsg_new(inet6_if_nlmsg_size(), GFP_ATOMIC);
if (!skb)
goto errout;
err = inet6_fill_ifinfo(skb, idev, 0, 0, event, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_if_nlmsg_size() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFINFO, NULL, GFP_ATOMIC);
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_IPV6_IFINFO, err);
}
static inline size_t inet6_prefix_nlmsg_size(void)
{
return NLMSG_ALIGN(sizeof(struct prefixmsg))
+ nla_total_size(sizeof(struct in6_addr))
+ nla_total_size(sizeof(struct prefix_cacheinfo));
}
static int inet6_fill_prefix(struct sk_buff *skb, struct inet6_dev *idev,
struct prefix_info *pinfo, u32 portid, u32 seq,
int event, unsigned int flags)
{
struct prefixmsg *pmsg;
struct nlmsghdr *nlh;
struct prefix_cacheinfo ci;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*pmsg), flags);
if (!nlh)
return -EMSGSIZE;
pmsg = nlmsg_data(nlh);
pmsg->prefix_family = AF_INET6;
pmsg->prefix_pad1 = 0;
pmsg->prefix_pad2 = 0;
pmsg->prefix_ifindex = idev->dev->ifindex;
pmsg->prefix_len = pinfo->prefix_len;
pmsg->prefix_type = pinfo->type;
pmsg->prefix_pad3 = 0;
pmsg->prefix_flags = 0;
if (pinfo->onlink)
pmsg->prefix_flags |= IF_PREFIX_ONLINK;
if (pinfo->autoconf)
pmsg->prefix_flags |= IF_PREFIX_AUTOCONF;
if (nla_put(skb, PREFIX_ADDRESS, sizeof(pinfo->prefix), &pinfo->prefix))
goto nla_put_failure;
ci.preferred_time = ntohl(pinfo->prefered);
ci.valid_time = ntohl(pinfo->valid);
if (nla_put(skb, PREFIX_CACHEINFO, sizeof(ci), &ci))
goto nla_put_failure;
nlmsg_end(skb, nlh);
return 0;
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static void inet6_prefix_notify(int event, struct inet6_dev *idev,
struct prefix_info *pinfo)
{
struct sk_buff *skb;
struct net *net = dev_net(idev->dev);
int err = -ENOBUFS;
skb = nlmsg_new(inet6_prefix_nlmsg_size(), GFP_ATOMIC);
if (!skb)
goto errout;
err = inet6_fill_prefix(skb, idev, pinfo, 0, 0, event, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_prefix_nlmsg_size() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_IPV6_PREFIX, NULL, GFP_ATOMIC);
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_IPV6_PREFIX, err);
}
static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp)
{
struct net *net = dev_net(ifp->idev->dev);
if (event)
ASSERT_RTNL();
inet6_ifa_notify(event ? : RTM_NEWADDR, ifp);
switch (event) {
case RTM_NEWADDR:
/*
* If the address was optimistic we inserted the route at the
* start of our DAD process, so we don't need to do it again.
* If the device was taken down in the middle of the DAD
* cycle there is a race where we could get here without a
* host route, so nothing to insert. That will be fixed when
* the device is brought up.
*/
if (ifp->rt && !rcu_access_pointer(ifp->rt->fib6_node)) {
ip6_ins_rt(net, ifp->rt);
} else if (!ifp->rt && (ifp->idev->dev->flags & IFF_UP)) {
pr_warn("BUG: Address %pI6c on device %s is missing its host route.\n",
&ifp->addr, ifp->idev->dev->name);
}
if (ifp->idev->cnf.forwarding)
addrconf_join_anycast(ifp);
if (!ipv6_addr_any(&ifp->peer_addr))
addrconf_prefix_route(&ifp->peer_addr, 128,
ifp->rt_priority, ifp->idev->dev,
0, 0, GFP_ATOMIC);
break;
case RTM_DELADDR:
if (ifp->idev->cnf.forwarding)
addrconf_leave_anycast(ifp);
addrconf_leave_solict(ifp->idev, &ifp->addr);
if (!ipv6_addr_any(&ifp->peer_addr)) {
struct fib6_info *rt;
rt = addrconf_get_prefix_route(&ifp->peer_addr, 128,
ifp->idev->dev, 0, 0,
false);
if (rt)
ip6_del_rt(net, rt, false);
}
if (ifp->rt) {
ip6_del_rt(net, ifp->rt, false);
ifp->rt = NULL;
}
rt_genid_bump_ipv6(net);
break;
}
atomic_inc(&net->ipv6.dev_addr_genid);
}
static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp)
{
if (likely(ifp->idev->dead == 0))
__ipv6_ifa_notify(event, ifp);
}
#ifdef CONFIG_SYSCTL
static int addrconf_sysctl_forward(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
int *valp = ctl->data;
int val = *valp;
loff_t pos = *ppos;
struct ctl_table lctl;
int ret;
/*
* ctl->data points to idev->cnf.forwarding, we should
* not modify it until we get the rtnl lock.
*/
lctl = *ctl;
lctl.data = &val;
ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
if (write)
ret = addrconf_fixup_forwarding(ctl, valp, val);
if (ret)
*ppos = pos;
return ret;
}
static int addrconf_sysctl_mtu(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
struct inet6_dev *idev = ctl->extra1;
int min_mtu = IPV6_MIN_MTU;
struct ctl_table lctl;
lctl = *ctl;
lctl.extra1 = &min_mtu;
lctl.extra2 = idev ? &idev->dev->mtu : NULL;
return proc_dointvec_minmax(&lctl, write, buffer, lenp, ppos);
}
static void dev_disable_change(struct inet6_dev *idev)
{
struct netdev_notifier_info info;
if (!idev || !idev->dev)
return;
netdev_notifier_info_init(&info, idev->dev);
if (idev->cnf.disable_ipv6)
addrconf_notify(NULL, NETDEV_DOWN, &info);
else
addrconf_notify(NULL, NETDEV_UP, &info);
}
static void addrconf_disable_change(struct net *net, __s32 newf)
{
struct net_device *dev;
struct inet6_dev *idev;
for_each_netdev(net, dev) {
idev = __in6_dev_get(dev);
if (idev) {
int changed = (!idev->cnf.disable_ipv6) ^ (!newf);
idev->cnf.disable_ipv6 = newf;
if (changed)
dev_disable_change(idev);
}
}
}
static int addrconf_disable_ipv6(struct ctl_table *table, int *p, int newf)
{
struct net *net;
int old;
if (!rtnl_trylock())
return restart_syscall();
net = (struct net *)table->extra2;
old = *p;
*p = newf;
if (p == &net->ipv6.devconf_dflt->disable_ipv6) {
rtnl_unlock();
return 0;
}
if (p == &net->ipv6.devconf_all->disable_ipv6) {
net->ipv6.devconf_dflt->disable_ipv6 = newf;
addrconf_disable_change(net, newf);
} else if ((!newf) ^ (!old))
dev_disable_change((struct inet6_dev *)table->extra1);
rtnl_unlock();
return 0;
}
static int addrconf_sysctl_disable(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
int *valp = ctl->data;
int val = *valp;
loff_t pos = *ppos;
struct ctl_table lctl;
int ret;
/*
* ctl->data points to idev->cnf.disable_ipv6, we should
* not modify it until we get the rtnl lock.
*/
lctl = *ctl;
lctl.data = &val;
ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
if (write)
ret = addrconf_disable_ipv6(ctl, valp, val);
if (ret)
*ppos = pos;
return ret;
}
static int addrconf_sysctl_proxy_ndp(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
int *valp = ctl->data;
int ret;
int old, new;
old = *valp;
ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
new = *valp;
if (write && old != new) {
struct net *net = ctl->extra2;
if (!rtnl_trylock())
return restart_syscall();
if (valp == &net->ipv6.devconf_dflt->proxy_ndp)
inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
NETCONFA_PROXY_NEIGH,
NETCONFA_IFINDEX_DEFAULT,
net->ipv6.devconf_dflt);
else if (valp == &net->ipv6.devconf_all->proxy_ndp)
inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
NETCONFA_PROXY_NEIGH,
NETCONFA_IFINDEX_ALL,
net->ipv6.devconf_all);
else {
struct inet6_dev *idev = ctl->extra1;
inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
NETCONFA_PROXY_NEIGH,
idev->dev->ifindex,
&idev->cnf);
}
rtnl_unlock();
}
return ret;
}
static int addrconf_sysctl_addr_gen_mode(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp,
loff_t *ppos)
{
int ret = 0;
u32 new_val;
struct inet6_dev *idev = (struct inet6_dev *)ctl->extra1;
struct net *net = (struct net *)ctl->extra2;
struct ctl_table tmp = {
.data = &new_val,
.maxlen = sizeof(new_val),
.mode = ctl->mode,
};
if (!rtnl_trylock())
return restart_syscall();
new_val = *((u32 *)ctl->data);
ret = proc_douintvec(&tmp, write, buffer, lenp, ppos);
if (ret != 0)
goto out;
if (write) {
if (check_addr_gen_mode(new_val) < 0) {
ret = -EINVAL;
goto out;
}
if (idev) {
if (check_stable_privacy(idev, net, new_val) < 0) {
ret = -EINVAL;
goto out;
}
if (idev->cnf.addr_gen_mode != new_val) {
idev->cnf.addr_gen_mode = new_val;
addrconf_init_auto_addrs(idev->dev);
}
} else if (&net->ipv6.devconf_all->addr_gen_mode == ctl->data) {
struct net_device *dev;
net->ipv6.devconf_dflt->addr_gen_mode = new_val;
for_each_netdev(net, dev) {
idev = __in6_dev_get(dev);
if (idev &&
idev->cnf.addr_gen_mode != new_val) {
idev->cnf.addr_gen_mode = new_val;
addrconf_init_auto_addrs(idev->dev);
}
}
}
*((u32 *)ctl->data) = new_val;
}
out:
rtnl_unlock();
return ret;
}
static int addrconf_sysctl_stable_secret(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp,
loff_t *ppos)
{
int err;
struct in6_addr addr;
char str[IPV6_MAX_STRLEN];
struct ctl_table lctl = *ctl;
struct net *net = ctl->extra2;
struct ipv6_stable_secret *secret = ctl->data;
if (&net->ipv6.devconf_all->stable_secret == ctl->data)
return -EIO;
lctl.maxlen = IPV6_MAX_STRLEN;
lctl.data = str;
if (!rtnl_trylock())
return restart_syscall();
if (!write && !secret->initialized) {
err = -EIO;
goto out;
}
err = snprintf(str, sizeof(str), "%pI6", &secret->secret);
if (err >= sizeof(str)) {
err = -EIO;
goto out;
}
err = proc_dostring(&lctl, write, buffer, lenp, ppos);
if (err || !write)
goto out;
if (in6_pton(str, -1, addr.in6_u.u6_addr8, -1, NULL) != 1) {
err = -EIO;
goto out;
}
secret->initialized = true;
secret->secret = addr;
if (&net->ipv6.devconf_dflt->stable_secret == ctl->data) {
struct net_device *dev;
for_each_netdev(net, dev) {
struct inet6_dev *idev = __in6_dev_get(dev);
if (idev) {
idev->cnf.addr_gen_mode =
IN6_ADDR_GEN_MODE_STABLE_PRIVACY;
}
}
} else {
struct inet6_dev *idev = ctl->extra1;
idev->cnf.addr_gen_mode = IN6_ADDR_GEN_MODE_STABLE_PRIVACY;
}
out:
rtnl_unlock();
return err;
}
static
int addrconf_sysctl_ignore_routes_with_linkdown(struct ctl_table *ctl,
int write, void *buffer,
size_t *lenp,
loff_t *ppos)
{
int *valp = ctl->data;
int val = *valp;
loff_t pos = *ppos;
struct ctl_table lctl;
int ret;
/* ctl->data points to idev->cnf.ignore_routes_when_linkdown
* we should not modify it until we get the rtnl lock.
*/
lctl = *ctl;
lctl.data = &val;
ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
if (write)
ret = addrconf_fixup_linkdown(ctl, valp, val);
if (ret)
*ppos = pos;
return ret;
}
static
void addrconf_set_nopolicy(struct rt6_info *rt, int action)
{
if (rt) {
if (action)
rt->dst.flags |= DST_NOPOLICY;
else
rt->dst.flags &= ~DST_NOPOLICY;
}
}
static
void addrconf_disable_policy_idev(struct inet6_dev *idev, int val)
{
struct inet6_ifaddr *ifa;
read_lock_bh(&idev->lock);
list_for_each_entry(ifa, &idev->addr_list, if_list) {
spin_lock(&ifa->lock);
if (ifa->rt) {
/* host routes only use builtin fib6_nh */
struct fib6_nh *nh = ifa->rt->fib6_nh;
int cpu;
rcu_read_lock();
ifa->rt->dst_nopolicy = val ? true : false;
if (nh->rt6i_pcpu) {
for_each_possible_cpu(cpu) {
struct rt6_info **rtp;
rtp = per_cpu_ptr(nh->rt6i_pcpu, cpu);
addrconf_set_nopolicy(*rtp, val);
}
}
rcu_read_unlock();
}
spin_unlock(&ifa->lock);
}
read_unlock_bh(&idev->lock);
}
static
int addrconf_disable_policy(struct ctl_table *ctl, int *valp, int val)
{
struct inet6_dev *idev;
struct net *net;
if (!rtnl_trylock())
return restart_syscall();
*valp = val;
net = (struct net *)ctl->extra2;
if (valp == &net->ipv6.devconf_dflt->disable_policy) {
rtnl_unlock();
return 0;
}
if (valp == &net->ipv6.devconf_all->disable_policy) {
struct net_device *dev;
for_each_netdev(net, dev) {
idev = __in6_dev_get(dev);
if (idev)
addrconf_disable_policy_idev(idev, val);
}
} else {
idev = (struct inet6_dev *)ctl->extra1;
addrconf_disable_policy_idev(idev, val);
}
rtnl_unlock();
return 0;
}
static int addrconf_sysctl_disable_policy(struct ctl_table *ctl, int write,
void *buffer, size_t *lenp, loff_t *ppos)
{
int *valp = ctl->data;
int val = *valp;
loff_t pos = *ppos;
struct ctl_table lctl;
int ret;
lctl = *ctl;
lctl.data = &val;
ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
if (write && (*valp != val))
ret = addrconf_disable_policy(ctl, valp, val);
if (ret)
*ppos = pos;
return ret;
}
static int minus_one = -1;
static const int two_five_five = 255;
static u32 ioam6_if_id_max = U16_MAX;
static const struct ctl_table addrconf_sysctl[] = {
{
.procname = "forwarding",
.data = &ipv6_devconf.forwarding,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = addrconf_sysctl_forward,
},
{
.procname = "hop_limit",
.data = &ipv6_devconf.hop_limit,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = (void *)SYSCTL_ONE,
.extra2 = (void *)&two_five_five,
},
{
.procname = "mtu",
.data = &ipv6_devconf.mtu6,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = addrconf_sysctl_mtu,
},
{
.procname = "accept_ra",
.data = &ipv6_devconf.accept_ra,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_redirects",
.data = &ipv6_devconf.accept_redirects,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "autoconf",
.data = &ipv6_devconf.autoconf,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "dad_transmits",
.data = &ipv6_devconf.dad_transmits,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "router_solicitations",
.data = &ipv6_devconf.rtr_solicits,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &minus_one,
},
{
.procname = "router_solicitation_interval",
.data = &ipv6_devconf.rtr_solicit_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "router_solicitation_max_interval",
.data = &ipv6_devconf.rtr_solicit_max_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "router_solicitation_delay",
.data = &ipv6_devconf.rtr_solicit_delay,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "force_mld_version",
.data = &ipv6_devconf.force_mld_version,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "mldv1_unsolicited_report_interval",
.data =
&ipv6_devconf.mldv1_unsolicited_report_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_ms_jiffies,
},
{
.procname = "mldv2_unsolicited_report_interval",
.data =
&ipv6_devconf.mldv2_unsolicited_report_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_ms_jiffies,
},
{
.procname = "use_tempaddr",
.data = &ipv6_devconf.use_tempaddr,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "temp_valid_lft",
.data = &ipv6_devconf.temp_valid_lft,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "temp_prefered_lft",
.data = &ipv6_devconf.temp_prefered_lft,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "regen_max_retry",
.data = &ipv6_devconf.regen_max_retry,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "max_desync_factor",
.data = &ipv6_devconf.max_desync_factor,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "max_addresses",
.data = &ipv6_devconf.max_addresses,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_ra_defrtr",
.data = &ipv6_devconf.accept_ra_defrtr,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "ra_defrtr_metric",
.data = &ipv6_devconf.ra_defrtr_metric,
.maxlen = sizeof(u32),
.mode = 0644,
.proc_handler = proc_douintvec_minmax,
.extra1 = (void *)SYSCTL_ONE,
},
{
.procname = "accept_ra_min_hop_limit",
.data = &ipv6_devconf.accept_ra_min_hop_limit,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_ra_min_lft",
.data = &ipv6_devconf.accept_ra_min_lft,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_ra_pinfo",
.data = &ipv6_devconf.accept_ra_pinfo,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
#ifdef CONFIG_IPV6_ROUTER_PREF
{
.procname = "accept_ra_rtr_pref",
.data = &ipv6_devconf.accept_ra_rtr_pref,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "router_probe_interval",
.data = &ipv6_devconf.rtr_probe_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
#ifdef CONFIG_IPV6_ROUTE_INFO
{
.procname = "accept_ra_rt_info_min_plen",
.data = &ipv6_devconf.accept_ra_rt_info_min_plen,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_ra_rt_info_max_plen",
.data = &ipv6_devconf.accept_ra_rt_info_max_plen,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
#endif
#endif
{
.procname = "proxy_ndp",
.data = &ipv6_devconf.proxy_ndp,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = addrconf_sysctl_proxy_ndp,
},
{
.procname = "accept_source_route",
.data = &ipv6_devconf.accept_source_route,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
{
.procname = "optimistic_dad",
.data = &ipv6_devconf.optimistic_dad,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "use_optimistic",
.data = &ipv6_devconf.use_optimistic,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
#endif
#ifdef CONFIG_IPV6_MROUTE
{
.procname = "mc_forwarding",
.data = &ipv6_devconf.mc_forwarding,
.maxlen = sizeof(int),
.mode = 0444,
.proc_handler = proc_dointvec,
},
#endif
{
.procname = "disable_ipv6",
.data = &ipv6_devconf.disable_ipv6,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = addrconf_sysctl_disable,
},
{
.procname = "accept_dad",
.data = &ipv6_devconf.accept_dad,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "force_tllao",
.data = &ipv6_devconf.force_tllao,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec
},
{
.procname = "ndisc_notify",
.data = &ipv6_devconf.ndisc_notify,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec
},
{
.procname = "suppress_frag_ndisc",
.data = &ipv6_devconf.suppress_frag_ndisc,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec
},
{
.procname = "accept_ra_from_local",
.data = &ipv6_devconf.accept_ra_from_local,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "accept_ra_mtu",
.data = &ipv6_devconf.accept_ra_mtu,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "stable_secret",
.data = &ipv6_devconf.stable_secret,
.maxlen = IPV6_MAX_STRLEN,
.mode = 0600,
.proc_handler = addrconf_sysctl_stable_secret,
},
{
.procname = "use_oif_addrs_only",
.data = &ipv6_devconf.use_oif_addrs_only,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "ignore_routes_with_linkdown",
.data = &ipv6_devconf.ignore_routes_with_linkdown,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = addrconf_sysctl_ignore_routes_with_linkdown,
},
{
.procname = "drop_unicast_in_l2_multicast",
.data = &ipv6_devconf.drop_unicast_in_l2_multicast,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "drop_unsolicited_na",
.data = &ipv6_devconf.drop_unsolicited_na,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "keep_addr_on_down",
.data = &ipv6_devconf.keep_addr_on_down,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "seg6_enabled",
.data = &ipv6_devconf.seg6_enabled,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
#ifdef CONFIG_IPV6_SEG6_HMAC
{
.procname = "seg6_require_hmac",
.data = &ipv6_devconf.seg6_require_hmac,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
#endif
{
.procname = "enhanced_dad",
.data = &ipv6_devconf.enhanced_dad,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "addr_gen_mode",
.data = &ipv6_devconf.addr_gen_mode,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = addrconf_sysctl_addr_gen_mode,
},
{
.procname = "disable_policy",
.data = &ipv6_devconf.disable_policy,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = addrconf_sysctl_disable_policy,
},
{
.procname = "ndisc_tclass",
.data = &ipv6_devconf.ndisc_tclass,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = (void *)SYSCTL_ZERO,
.extra2 = (void *)&two_five_five,
},
{
.procname = "rpl_seg_enabled",
.data = &ipv6_devconf.rpl_seg_enabled,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "ioam6_enabled",
.data = &ipv6_devconf.ioam6_enabled,
.maxlen = sizeof(u8),
.mode = 0644,
.proc_handler = proc_dou8vec_minmax,
.extra1 = (void *)SYSCTL_ZERO,
.extra2 = (void *)SYSCTL_ONE,
},
{
.procname = "ioam6_id",
.data = &ipv6_devconf.ioam6_id,
.maxlen = sizeof(u32),
.mode = 0644,
.proc_handler = proc_douintvec_minmax,
.extra1 = (void *)SYSCTL_ZERO,
.extra2 = (void *)&ioam6_if_id_max,
},
{
.procname = "ioam6_id_wide",
.data = &ipv6_devconf.ioam6_id_wide,
.maxlen = sizeof(u32),
.mode = 0644,
.proc_handler = proc_douintvec,
},
{
.procname = "ndisc_evict_nocarrier",
.data = &ipv6_devconf.ndisc_evict_nocarrier,
.maxlen = sizeof(u8),
.mode = 0644,
.proc_handler = proc_dou8vec_minmax,
.extra1 = (void *)SYSCTL_ZERO,
.extra2 = (void *)SYSCTL_ONE,
},
{
.procname = "accept_untracked_na",
.data = &ipv6_devconf.accept_untracked_na,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ZERO,
.extra2 = SYSCTL_TWO,
},
{
/* sentinel */
}
};
static int __addrconf_sysctl_register(struct net *net, char *dev_name,
struct inet6_dev *idev, struct ipv6_devconf *p)
{
int i, ifindex;
struct ctl_table *table;
char path[sizeof("net/ipv6/conf/") + IFNAMSIZ];
table = kmemdup(addrconf_sysctl, sizeof(addrconf_sysctl), GFP_KERNEL_ACCOUNT);
if (!table)
goto out;
for (i = 0; table[i].data; i++) {
table[i].data += (char *)p - (char *)&ipv6_devconf;
/* If one of these is already set, then it is not safe to
* overwrite either of them: this makes proc_dointvec_minmax
* usable.
*/
if (!table[i].extra1 && !table[i].extra2) {
table[i].extra1 = idev; /* embedded; no ref */
table[i].extra2 = net;
}
}
snprintf(path, sizeof(path), "net/ipv6/conf/%s", dev_name);
p->sysctl_header = register_net_sysctl_sz(net, path, table,
ARRAY_SIZE(addrconf_sysctl));
if (!p->sysctl_header)
goto free;
if (!strcmp(dev_name, "all"))
ifindex = NETCONFA_IFINDEX_ALL;
else if (!strcmp(dev_name, "default"))
ifindex = NETCONFA_IFINDEX_DEFAULT;
else
ifindex = idev->dev->ifindex;
inet6_netconf_notify_devconf(net, RTM_NEWNETCONF, NETCONFA_ALL,
ifindex, p);
return 0;
free:
kfree(table);
out:
return -ENOBUFS;
}
static void __addrconf_sysctl_unregister(struct net *net,
struct ipv6_devconf *p, int ifindex)
{
struct ctl_table *table;
if (!p->sysctl_header)
return;
table = p->sysctl_header->ctl_table_arg;
unregister_net_sysctl_table(p->sysctl_header);
p->sysctl_header = NULL;
kfree(table);
inet6_netconf_notify_devconf(net, RTM_DELNETCONF, 0, ifindex, NULL);
}
static int addrconf_sysctl_register(struct inet6_dev *idev)
{
int err;
if (!sysctl_dev_name_is_allowed(idev->dev->name))
return -EINVAL;
err = neigh_sysctl_register(idev->dev, idev->nd_parms,
&ndisc_ifinfo_sysctl_change);
if (err)
return err;
err = __addrconf_sysctl_register(dev_net(idev->dev), idev->dev->name,
idev, &idev->cnf);
if (err)
neigh_sysctl_unregister(idev->nd_parms);
return err;
}
static void addrconf_sysctl_unregister(struct inet6_dev *idev)
{
__addrconf_sysctl_unregister(dev_net(idev->dev), &idev->cnf,
idev->dev->ifindex);
neigh_sysctl_unregister(idev->nd_parms);
}
#endif
static int __net_init addrconf_init_net(struct net *net)
{
int err = -ENOMEM;
struct ipv6_devconf *all, *dflt;
spin_lock_init(&net->ipv6.addrconf_hash_lock);
INIT_DEFERRABLE_WORK(&net->ipv6.addr_chk_work, addrconf_verify_work);
net->ipv6.inet6_addr_lst = kcalloc(IN6_ADDR_HSIZE,
sizeof(struct hlist_head),
GFP_KERNEL);
if (!net->ipv6.inet6_addr_lst)
goto err_alloc_addr;
all = kmemdup(&ipv6_devconf, sizeof(ipv6_devconf), GFP_KERNEL);
if (!all)
goto err_alloc_all;
dflt = kmemdup(&ipv6_devconf_dflt, sizeof(ipv6_devconf_dflt), GFP_KERNEL);
if (!dflt)
goto err_alloc_dflt;
if (!net_eq(net, &init_net)) {
switch (net_inherit_devconf()) {
case 1: /* copy from init_net */
memcpy(all, init_net.ipv6.devconf_all,
sizeof(ipv6_devconf));
memcpy(dflt, init_net.ipv6.devconf_dflt,
sizeof(ipv6_devconf_dflt));
break;
case 3: /* copy from the current netns */
memcpy(all, current->nsproxy->net_ns->ipv6.devconf_all,
sizeof(ipv6_devconf));
memcpy(dflt,
current->nsproxy->net_ns->ipv6.devconf_dflt,
sizeof(ipv6_devconf_dflt));
break;
case 0:
case 2:
/* use compiled values */
break;
}
}
/* these will be inherited by all namespaces */
dflt->autoconf = ipv6_defaults.autoconf;
dflt->disable_ipv6 = ipv6_defaults.disable_ipv6;
dflt->stable_secret.initialized = false;
all->stable_secret.initialized = false;
net->ipv6.devconf_all = all;
net->ipv6.devconf_dflt = dflt;
#ifdef CONFIG_SYSCTL
err = __addrconf_sysctl_register(net, "all", NULL, all);
if (err < 0)
goto err_reg_all;
err = __addrconf_sysctl_register(net, "default", NULL, dflt);
if (err < 0)
goto err_reg_dflt;
#endif
return 0;
#ifdef CONFIG_SYSCTL
err_reg_dflt:
__addrconf_sysctl_unregister(net, all, NETCONFA_IFINDEX_ALL);
err_reg_all:
kfree(dflt);
net->ipv6.devconf_dflt = NULL;
#endif
err_alloc_dflt:
kfree(all);
net->ipv6.devconf_all = NULL;
err_alloc_all:
kfree(net->ipv6.inet6_addr_lst);
err_alloc_addr:
return err;
}
static void __net_exit addrconf_exit_net(struct net *net)
{
int i;
#ifdef CONFIG_SYSCTL
__addrconf_sysctl_unregister(net, net->ipv6.devconf_dflt,
NETCONFA_IFINDEX_DEFAULT);
__addrconf_sysctl_unregister(net, net->ipv6.devconf_all,
NETCONFA_IFINDEX_ALL);
#endif
kfree(net->ipv6.devconf_dflt);
net->ipv6.devconf_dflt = NULL;
kfree(net->ipv6.devconf_all);
net->ipv6.devconf_all = NULL;
cancel_delayed_work_sync(&net->ipv6.addr_chk_work);
/*
* Check hash table, then free it.
*/
for (i = 0; i < IN6_ADDR_HSIZE; i++)
WARN_ON_ONCE(!hlist_empty(&net->ipv6.inet6_addr_lst[i]));
kfree(net->ipv6.inet6_addr_lst);
net->ipv6.inet6_addr_lst = NULL;
}
static struct pernet_operations addrconf_ops = {
.init = addrconf_init_net,
.exit = addrconf_exit_net,
};
static struct rtnl_af_ops inet6_ops __read_mostly = {
.family = AF_INET6,
.fill_link_af = inet6_fill_link_af,
.get_link_af_size = inet6_get_link_af_size,
.validate_link_af = inet6_validate_link_af,
.set_link_af = inet6_set_link_af,
};
/*
* Init / cleanup code
*/
int __init addrconf_init(void)
{
struct inet6_dev *idev;
int err;
err = ipv6_addr_label_init();
if (err < 0) {
pr_crit("%s: cannot initialize default policy table: %d\n",
__func__, err);
goto out;
}
err = register_pernet_subsys(&addrconf_ops);
if (err < 0)
goto out_addrlabel;
addrconf_wq = create_workqueue("ipv6_addrconf");
if (!addrconf_wq) {
err = -ENOMEM;
goto out_nowq;
}
rtnl_lock();
idev = ipv6_add_dev(blackhole_netdev);
rtnl_unlock();
if (IS_ERR(idev)) {
err = PTR_ERR(idev);
goto errlo;
}
ip6_route_init_special_entries();
register_netdevice_notifier(&ipv6_dev_notf);
addrconf_verify(&init_net);
rtnl_af_register(&inet6_ops);
err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETLINK,
NULL, inet6_dump_ifinfo, 0);
if (err < 0)
goto errout;
err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_NEWADDR,
inet6_rtm_newaddr, NULL, 0);
if (err < 0)
goto errout;
err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_DELADDR,
inet6_rtm_deladdr, NULL, 0);
if (err < 0)
goto errout;
err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETADDR,
inet6_rtm_getaddr, inet6_dump_ifaddr,
RTNL_FLAG_DOIT_UNLOCKED);
if (err < 0)
goto errout;
err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETMULTICAST,
NULL, inet6_dump_ifmcaddr, 0);
if (err < 0)
goto errout;
err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETANYCAST,
NULL, inet6_dump_ifacaddr, 0);
if (err < 0)
goto errout;
err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETNETCONF,
inet6_netconf_get_devconf,
inet6_netconf_dump_devconf,
RTNL_FLAG_DOIT_UNLOCKED);
if (err < 0)
goto errout;
err = ipv6_addr_label_rtnl_register();
if (err < 0)
goto errout;
return 0;
errout:
rtnl_unregister_all(PF_INET6);
rtnl_af_unregister(&inet6_ops);
unregister_netdevice_notifier(&ipv6_dev_notf);
errlo:
destroy_workqueue(addrconf_wq);
out_nowq:
unregister_pernet_subsys(&addrconf_ops);
out_addrlabel:
ipv6_addr_label_cleanup();
out:
return err;
}
void addrconf_cleanup(void)
{
struct net_device *dev;
unregister_netdevice_notifier(&ipv6_dev_notf);
unregister_pernet_subsys(&addrconf_ops);
ipv6_addr_label_cleanup();
rtnl_af_unregister(&inet6_ops);
rtnl_lock();
/* clean dev list */
for_each_netdev(&init_net, dev) {
if (__in6_dev_get(dev) == NULL)
continue;
addrconf_ifdown(dev, true);
}
addrconf_ifdown(init_net.loopback_dev, true);
rtnl_unlock();
destroy_workqueue(addrconf_wq);
}
| linux-master | net/ipv6/addrconf.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* UDPLITEv6 An implementation of the UDP-Lite protocol over IPv6.
* See also net/ipv4/udplite.c
*
* Authors: Gerrit Renker <[email protected]>
*
* Changes:
* Fixes:
*/
#define pr_fmt(fmt) "UDPLite6: " fmt
#include <linux/export.h>
#include <linux/proc_fs.h>
#include "udp_impl.h"
static int udplitev6_sk_init(struct sock *sk)
{
udpv6_init_sock(sk);
udp_sk(sk)->pcflag = UDPLITE_BIT;
pr_warn_once("UDP-Lite is deprecated and scheduled to be removed in 2025, "
"please contact the netdev mailing list\n");
return 0;
}
static int udplitev6_rcv(struct sk_buff *skb)
{
return __udp6_lib_rcv(skb, &udplite_table, IPPROTO_UDPLITE);
}
static int udplitev6_err(struct sk_buff *skb,
struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
return __udp6_lib_err(skb, opt, type, code, offset, info,
&udplite_table);
}
static const struct inet6_protocol udplitev6_protocol = {
.handler = udplitev6_rcv,
.err_handler = udplitev6_err,
.flags = INET6_PROTO_NOPOLICY|INET6_PROTO_FINAL,
};
struct proto udplitev6_prot = {
.name = "UDPLITEv6",
.owner = THIS_MODULE,
.close = udp_lib_close,
.connect = ip6_datagram_connect,
.disconnect = udp_disconnect,
.ioctl = udp_ioctl,
.init = udplitev6_sk_init,
.destroy = udpv6_destroy_sock,
.setsockopt = udpv6_setsockopt,
.getsockopt = udpv6_getsockopt,
.sendmsg = udpv6_sendmsg,
.recvmsg = udpv6_recvmsg,
.hash = udp_lib_hash,
.unhash = udp_lib_unhash,
.rehash = udp_v6_rehash,
.get_port = udp_v6_get_port,
.memory_allocated = &udp_memory_allocated,
.per_cpu_fw_alloc = &udp_memory_per_cpu_fw_alloc,
.sysctl_mem = sysctl_udp_mem,
.sysctl_wmem_offset = offsetof(struct net, ipv4.sysctl_udp_wmem_min),
.sysctl_rmem_offset = offsetof(struct net, ipv4.sysctl_udp_rmem_min),
.obj_size = sizeof(struct udp6_sock),
.ipv6_pinfo_offset = offsetof(struct udp6_sock, inet6),
.h.udp_table = &udplite_table,
};
static struct inet_protosw udplite6_protosw = {
.type = SOCK_DGRAM,
.protocol = IPPROTO_UDPLITE,
.prot = &udplitev6_prot,
.ops = &inet6_dgram_ops,
.flags = INET_PROTOSW_PERMANENT,
};
int __init udplitev6_init(void)
{
int ret;
ret = inet6_add_protocol(&udplitev6_protocol, IPPROTO_UDPLITE);
if (ret)
goto out;
ret = inet6_register_protosw(&udplite6_protosw);
if (ret)
goto out_udplitev6_protocol;
out:
return ret;
out_udplitev6_protocol:
inet6_del_protocol(&udplitev6_protocol, IPPROTO_UDPLITE);
goto out;
}
void udplitev6_exit(void)
{
inet6_unregister_protosw(&udplite6_protosw);
inet6_del_protocol(&udplitev6_protocol, IPPROTO_UDPLITE);
}
#ifdef CONFIG_PROC_FS
static struct udp_seq_afinfo udplite6_seq_afinfo = {
.family = AF_INET6,
.udp_table = &udplite_table,
};
static int __net_init udplite6_proc_init_net(struct net *net)
{
if (!proc_create_net_data("udplite6", 0444, net->proc_net,
&udp6_seq_ops, sizeof(struct udp_iter_state),
&udplite6_seq_afinfo))
return -ENOMEM;
return 0;
}
static void __net_exit udplite6_proc_exit_net(struct net *net)
{
remove_proc_entry("udplite6", net->proc_net);
}
static struct pernet_operations udplite6_net_ops = {
.init = udplite6_proc_init_net,
.exit = udplite6_proc_exit_net,
};
int __init udplite6_proc_init(void)
{
return register_pernet_subsys(&udplite6_net_ops);
}
void udplite6_proc_exit(void)
{
unregister_pernet_subsys(&udplite6_net_ops);
}
#endif
| linux-master | net/ipv6/udplite.c |
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/socket.h>
#include <linux/udp.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/in6.h>
#include <net/udp.h>
#include <net/udp_tunnel.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/ip6_tunnel.h>
#include <net/ip6_checksum.h>
int udp_sock_create6(struct net *net, struct udp_port_cfg *cfg,
struct socket **sockp)
{
struct sockaddr_in6 udp6_addr = {};
int err;
struct socket *sock = NULL;
err = sock_create_kern(net, AF_INET6, SOCK_DGRAM, 0, &sock);
if (err < 0)
goto error;
if (cfg->ipv6_v6only) {
err = ip6_sock_set_v6only(sock->sk);
if (err < 0)
goto error;
}
if (cfg->bind_ifindex) {
err = sock_bindtoindex(sock->sk, cfg->bind_ifindex, true);
if (err < 0)
goto error;
}
udp6_addr.sin6_family = AF_INET6;
memcpy(&udp6_addr.sin6_addr, &cfg->local_ip6,
sizeof(udp6_addr.sin6_addr));
udp6_addr.sin6_port = cfg->local_udp_port;
err = kernel_bind(sock, (struct sockaddr *)&udp6_addr,
sizeof(udp6_addr));
if (err < 0)
goto error;
if (cfg->peer_udp_port) {
memset(&udp6_addr, 0, sizeof(udp6_addr));
udp6_addr.sin6_family = AF_INET6;
memcpy(&udp6_addr.sin6_addr, &cfg->peer_ip6,
sizeof(udp6_addr.sin6_addr));
udp6_addr.sin6_port = cfg->peer_udp_port;
err = kernel_connect(sock,
(struct sockaddr *)&udp6_addr,
sizeof(udp6_addr), 0);
}
if (err < 0)
goto error;
udp_set_no_check6_tx(sock->sk, !cfg->use_udp6_tx_checksums);
udp_set_no_check6_rx(sock->sk, !cfg->use_udp6_rx_checksums);
*sockp = sock;
return 0;
error:
if (sock) {
kernel_sock_shutdown(sock, SHUT_RDWR);
sock_release(sock);
}
*sockp = NULL;
return err;
}
EXPORT_SYMBOL_GPL(udp_sock_create6);
int udp_tunnel6_xmit_skb(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb,
struct net_device *dev, struct in6_addr *saddr,
struct in6_addr *daddr,
__u8 prio, __u8 ttl, __be32 label,
__be16 src_port, __be16 dst_port, bool nocheck)
{
struct udphdr *uh;
struct ipv6hdr *ip6h;
__skb_push(skb, sizeof(*uh));
skb_reset_transport_header(skb);
uh = udp_hdr(skb);
uh->dest = dst_port;
uh->source = src_port;
uh->len = htons(skb->len);
skb_dst_set(skb, dst);
udp6_set_csum(nocheck, skb, saddr, daddr, skb->len);
__skb_push(skb, sizeof(*ip6h));
skb_reset_network_header(skb);
ip6h = ipv6_hdr(skb);
ip6_flow_hdr(ip6h, prio, label);
ip6h->payload_len = htons(skb->len);
ip6h->nexthdr = IPPROTO_UDP;
ip6h->hop_limit = ttl;
ip6h->daddr = *daddr;
ip6h->saddr = *saddr;
ip6tunnel_xmit(sk, skb, dev);
return 0;
}
EXPORT_SYMBOL_GPL(udp_tunnel6_xmit_skb);
MODULE_LICENSE("GPL");
| linux-master | net/ipv6/ip6_udp_tunnel.c |
// SPDX-License-Identifier: GPL-2.0-only
/*
* IPv6 library code, needed by static components when full IPv6 support is
* not configured or static.
*/
#include <linux/export.h>
#include <net/ipv6.h>
/*
* find out if nexthdr is a well-known extension header or a protocol
*/
bool ipv6_ext_hdr(u8 nexthdr)
{
/*
* find out if nexthdr is an extension header or a protocol
*/
return (nexthdr == NEXTHDR_HOP) ||
(nexthdr == NEXTHDR_ROUTING) ||
(nexthdr == NEXTHDR_FRAGMENT) ||
(nexthdr == NEXTHDR_AUTH) ||
(nexthdr == NEXTHDR_NONE) ||
(nexthdr == NEXTHDR_DEST);
}
EXPORT_SYMBOL(ipv6_ext_hdr);
/*
* Skip any extension headers. This is used by the ICMP module.
*
* Note that strictly speaking this conflicts with RFC 2460 4.0:
* ...The contents and semantics of each extension header determine whether
* or not to proceed to the next header. Therefore, extension headers must
* be processed strictly in the order they appear in the packet; a
* receiver must not, for example, scan through a packet looking for a
* particular kind of extension header and process that header prior to
* processing all preceding ones.
*
* We do exactly this. This is a protocol bug. We can't decide after a
* seeing an unknown discard-with-error flavour TLV option if it's a
* ICMP error message or not (errors should never be send in reply to
* ICMP error messages).
*
* But I see no other way to do this. This might need to be reexamined
* when Linux implements ESP (and maybe AUTH) headers.
* --AK
*
* This function parses (probably truncated) exthdr set "hdr".
* "nexthdrp" initially points to some place,
* where type of the first header can be found.
*
* It skips all well-known exthdrs, and returns pointer to the start
* of unparsable area i.e. the first header with unknown type.
* If it is not NULL *nexthdr is updated by type/protocol of this header.
*
* NOTES: - if packet terminated with NEXTHDR_NONE it returns NULL.
* - it may return pointer pointing beyond end of packet,
* if the last recognized header is truncated in the middle.
* - if packet is truncated, so that all parsed headers are skipped,
* it returns NULL.
* - First fragment header is skipped, not-first ones
* are considered as unparsable.
* - Reports the offset field of the final fragment header so it is
* possible to tell whether this is a first fragment, later fragment,
* or not fragmented.
* - ESP is unparsable for now and considered like
* normal payload protocol.
* - Note also special handling of AUTH header. Thanks to IPsec wizards.
*
* --ANK (980726)
*/
int ipv6_skip_exthdr(const struct sk_buff *skb, int start, u8 *nexthdrp,
__be16 *frag_offp)
{
u8 nexthdr = *nexthdrp;
*frag_offp = 0;
while (ipv6_ext_hdr(nexthdr)) {
struct ipv6_opt_hdr _hdr, *hp;
int hdrlen;
if (nexthdr == NEXTHDR_NONE)
return -1;
hp = skb_header_pointer(skb, start, sizeof(_hdr), &_hdr);
if (!hp)
return -1;
if (nexthdr == NEXTHDR_FRAGMENT) {
__be16 _frag_off, *fp;
fp = skb_header_pointer(skb,
start+offsetof(struct frag_hdr,
frag_off),
sizeof(_frag_off),
&_frag_off);
if (!fp)
return -1;
*frag_offp = *fp;
if (ntohs(*frag_offp) & ~0x7)
break;
hdrlen = 8;
} else if (nexthdr == NEXTHDR_AUTH)
hdrlen = ipv6_authlen(hp);
else
hdrlen = ipv6_optlen(hp);
nexthdr = hp->nexthdr;
start += hdrlen;
}
*nexthdrp = nexthdr;
return start;
}
EXPORT_SYMBOL(ipv6_skip_exthdr);
int ipv6_find_tlv(const struct sk_buff *skb, int offset, int type)
{
const unsigned char *nh = skb_network_header(skb);
int packet_len = skb_tail_pointer(skb) - skb_network_header(skb);
struct ipv6_opt_hdr *hdr;
int len;
if (offset + 2 > packet_len)
goto bad;
hdr = (struct ipv6_opt_hdr *)(nh + offset);
len = ((hdr->hdrlen + 1) << 3);
if (offset + len > packet_len)
goto bad;
offset += 2;
len -= 2;
while (len > 0) {
int opttype = nh[offset];
int optlen;
if (opttype == type)
return offset;
switch (opttype) {
case IPV6_TLV_PAD1:
optlen = 1;
break;
default:
if (len < 2)
goto bad;
optlen = nh[offset + 1] + 2;
if (optlen > len)
goto bad;
break;
}
offset += optlen;
len -= optlen;
}
/* not_found */
bad:
return -1;
}
EXPORT_SYMBOL_GPL(ipv6_find_tlv);
/*
* find the offset to specified header or the protocol number of last header
* if target < 0. "last header" is transport protocol header, ESP, or
* "No next header".
*
* Note that *offset is used as input/output parameter, and if it is not zero,
* then it must be a valid offset to an inner IPv6 header. This can be used
* to explore inner IPv6 header, eg. ICMPv6 error messages.
*
* If target header is found, its offset is set in *offset and return protocol
* number. Otherwise, return -1.
*
* If the first fragment doesn't contain the final protocol header or
* NEXTHDR_NONE it is considered invalid.
*
* Note that non-1st fragment is special case that "the protocol number
* of last header" is "next header" field in Fragment header. In this case,
* *offset is meaningless and fragment offset is stored in *fragoff if fragoff
* isn't NULL.
*
* if flags is not NULL and it's a fragment, then the frag flag
* IP6_FH_F_FRAG will be set. If it's an AH header, the
* IP6_FH_F_AUTH flag is set and target < 0, then this function will
* stop at the AH header. If IP6_FH_F_SKIP_RH flag was passed, then this
* function will skip all those routing headers, where segements_left was 0.
*/
int ipv6_find_hdr(const struct sk_buff *skb, unsigned int *offset,
int target, unsigned short *fragoff, int *flags)
{
unsigned int start = skb_network_offset(skb) + sizeof(struct ipv6hdr);
u8 nexthdr = ipv6_hdr(skb)->nexthdr;
bool found;
if (fragoff)
*fragoff = 0;
if (*offset) {
struct ipv6hdr _ip6, *ip6;
ip6 = skb_header_pointer(skb, *offset, sizeof(_ip6), &_ip6);
if (!ip6 || (ip6->version != 6))
return -EBADMSG;
start = *offset + sizeof(struct ipv6hdr);
nexthdr = ip6->nexthdr;
}
do {
struct ipv6_opt_hdr _hdr, *hp;
unsigned int hdrlen;
found = (nexthdr == target);
if ((!ipv6_ext_hdr(nexthdr)) || nexthdr == NEXTHDR_NONE) {
if (target < 0 || found)
break;
return -ENOENT;
}
hp = skb_header_pointer(skb, start, sizeof(_hdr), &_hdr);
if (!hp)
return -EBADMSG;
if (nexthdr == NEXTHDR_ROUTING) {
struct ipv6_rt_hdr _rh, *rh;
rh = skb_header_pointer(skb, start, sizeof(_rh),
&_rh);
if (!rh)
return -EBADMSG;
if (flags && (*flags & IP6_FH_F_SKIP_RH) &&
rh->segments_left == 0)
found = false;
}
if (nexthdr == NEXTHDR_FRAGMENT) {
unsigned short _frag_off;
__be16 *fp;
if (flags) /* Indicate that this is a fragment */
*flags |= IP6_FH_F_FRAG;
fp = skb_header_pointer(skb,
start+offsetof(struct frag_hdr,
frag_off),
sizeof(_frag_off),
&_frag_off);
if (!fp)
return -EBADMSG;
_frag_off = ntohs(*fp) & ~0x7;
if (_frag_off) {
if (target < 0 &&
((!ipv6_ext_hdr(hp->nexthdr)) ||
hp->nexthdr == NEXTHDR_NONE)) {
if (fragoff)
*fragoff = _frag_off;
return hp->nexthdr;
}
if (!found)
return -ENOENT;
if (fragoff)
*fragoff = _frag_off;
break;
}
hdrlen = 8;
} else if (nexthdr == NEXTHDR_AUTH) {
if (flags && (*flags & IP6_FH_F_AUTH) && (target < 0))
break;
hdrlen = ipv6_authlen(hp);
} else
hdrlen = ipv6_optlen(hp);
if (!found) {
nexthdr = hp->nexthdr;
start += hdrlen;
}
} while (!found);
*offset = start;
return nexthdr;
}
EXPORT_SYMBOL(ipv6_find_hdr);
| linux-master | net/ipv6/exthdrs_core.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/* xfrm6_protocol.c - Generic xfrm protocol multiplexer for ipv6.
*
* Copyright (C) 2013 secunet Security Networks AG
*
* Author:
* Steffen Klassert <[email protected]>
*
* Based on:
* net/ipv4/xfrm4_protocol.c
*/
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/skbuff.h>
#include <linux/icmpv6.h>
#include <net/ip6_route.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <net/xfrm.h>
static struct xfrm6_protocol __rcu *esp6_handlers __read_mostly;
static struct xfrm6_protocol __rcu *ah6_handlers __read_mostly;
static struct xfrm6_protocol __rcu *ipcomp6_handlers __read_mostly;
static DEFINE_MUTEX(xfrm6_protocol_mutex);
static inline struct xfrm6_protocol __rcu **proto_handlers(u8 protocol)
{
switch (protocol) {
case IPPROTO_ESP:
return &esp6_handlers;
case IPPROTO_AH:
return &ah6_handlers;
case IPPROTO_COMP:
return &ipcomp6_handlers;
}
return NULL;
}
#define for_each_protocol_rcu(head, handler) \
for (handler = rcu_dereference(head); \
handler != NULL; \
handler = rcu_dereference(handler->next)) \
static int xfrm6_rcv_cb(struct sk_buff *skb, u8 protocol, int err)
{
int ret;
struct xfrm6_protocol *handler;
struct xfrm6_protocol __rcu **head = proto_handlers(protocol);
if (!head)
return 0;
for_each_protocol_rcu(*proto_handlers(protocol), handler)
if ((ret = handler->cb_handler(skb, err)) <= 0)
return ret;
return 0;
}
int xfrm6_rcv_encap(struct sk_buff *skb, int nexthdr, __be32 spi,
int encap_type)
{
int ret;
struct xfrm6_protocol *handler;
struct xfrm6_protocol __rcu **head = proto_handlers(nexthdr);
XFRM_TUNNEL_SKB_CB(skb)->tunnel.ip6 = NULL;
XFRM_SPI_SKB_CB(skb)->family = AF_INET6;
XFRM_SPI_SKB_CB(skb)->daddroff = offsetof(struct ipv6hdr, daddr);
if (!head)
goto out;
if (!skb_dst(skb)) {
const struct ipv6hdr *ip6h = ipv6_hdr(skb);
int flags = RT6_LOOKUP_F_HAS_SADDR;
struct dst_entry *dst;
struct flowi6 fl6 = {
.flowi6_iif = skb->dev->ifindex,
.daddr = ip6h->daddr,
.saddr = ip6h->saddr,
.flowlabel = ip6_flowinfo(ip6h),
.flowi6_mark = skb->mark,
.flowi6_proto = ip6h->nexthdr,
};
dst = ip6_route_input_lookup(dev_net(skb->dev), skb->dev, &fl6,
skb, flags);
if (dst->error)
goto drop;
skb_dst_set(skb, dst);
}
for_each_protocol_rcu(*head, handler)
if ((ret = handler->input_handler(skb, nexthdr, spi, encap_type)) != -EINVAL)
return ret;
out:
icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_PORT_UNREACH, 0);
drop:
kfree_skb(skb);
return 0;
}
EXPORT_SYMBOL(xfrm6_rcv_encap);
static int xfrm6_esp_rcv(struct sk_buff *skb)
{
int ret;
struct xfrm6_protocol *handler;
XFRM_TUNNEL_SKB_CB(skb)->tunnel.ip6 = NULL;
for_each_protocol_rcu(esp6_handlers, handler)
if ((ret = handler->handler(skb)) != -EINVAL)
return ret;
icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_PORT_UNREACH, 0);
kfree_skb(skb);
return 0;
}
static int xfrm6_esp_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
struct xfrm6_protocol *handler;
for_each_protocol_rcu(esp6_handlers, handler)
if (!handler->err_handler(skb, opt, type, code, offset, info))
return 0;
return -ENOENT;
}
static int xfrm6_ah_rcv(struct sk_buff *skb)
{
int ret;
struct xfrm6_protocol *handler;
XFRM_TUNNEL_SKB_CB(skb)->tunnel.ip6 = NULL;
for_each_protocol_rcu(ah6_handlers, handler)
if ((ret = handler->handler(skb)) != -EINVAL)
return ret;
icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_PORT_UNREACH, 0);
kfree_skb(skb);
return 0;
}
static int xfrm6_ah_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
struct xfrm6_protocol *handler;
for_each_protocol_rcu(ah6_handlers, handler)
if (!handler->err_handler(skb, opt, type, code, offset, info))
return 0;
return -ENOENT;
}
static int xfrm6_ipcomp_rcv(struct sk_buff *skb)
{
int ret;
struct xfrm6_protocol *handler;
XFRM_TUNNEL_SKB_CB(skb)->tunnel.ip6 = NULL;
for_each_protocol_rcu(ipcomp6_handlers, handler)
if ((ret = handler->handler(skb)) != -EINVAL)
return ret;
icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_PORT_UNREACH, 0);
kfree_skb(skb);
return 0;
}
static int xfrm6_ipcomp_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
struct xfrm6_protocol *handler;
for_each_protocol_rcu(ipcomp6_handlers, handler)
if (!handler->err_handler(skb, opt, type, code, offset, info))
return 0;
return -ENOENT;
}
static const struct inet6_protocol esp6_protocol = {
.handler = xfrm6_esp_rcv,
.err_handler = xfrm6_esp_err,
.flags = INET6_PROTO_NOPOLICY,
};
static const struct inet6_protocol ah6_protocol = {
.handler = xfrm6_ah_rcv,
.err_handler = xfrm6_ah_err,
.flags = INET6_PROTO_NOPOLICY,
};
static const struct inet6_protocol ipcomp6_protocol = {
.handler = xfrm6_ipcomp_rcv,
.err_handler = xfrm6_ipcomp_err,
.flags = INET6_PROTO_NOPOLICY,
};
static const struct xfrm_input_afinfo xfrm6_input_afinfo = {
.family = AF_INET6,
.callback = xfrm6_rcv_cb,
};
static inline const struct inet6_protocol *netproto(unsigned char protocol)
{
switch (protocol) {
case IPPROTO_ESP:
return &esp6_protocol;
case IPPROTO_AH:
return &ah6_protocol;
case IPPROTO_COMP:
return &ipcomp6_protocol;
}
return NULL;
}
int xfrm6_protocol_register(struct xfrm6_protocol *handler,
unsigned char protocol)
{
struct xfrm6_protocol __rcu **pprev;
struct xfrm6_protocol *t;
bool add_netproto = false;
int ret = -EEXIST;
int priority = handler->priority;
if (!proto_handlers(protocol) || !netproto(protocol))
return -EINVAL;
mutex_lock(&xfrm6_protocol_mutex);
if (!rcu_dereference_protected(*proto_handlers(protocol),
lockdep_is_held(&xfrm6_protocol_mutex)))
add_netproto = true;
for (pprev = proto_handlers(protocol);
(t = rcu_dereference_protected(*pprev,
lockdep_is_held(&xfrm6_protocol_mutex))) != NULL;
pprev = &t->next) {
if (t->priority < priority)
break;
if (t->priority == priority)
goto err;
}
handler->next = *pprev;
rcu_assign_pointer(*pprev, handler);
ret = 0;
err:
mutex_unlock(&xfrm6_protocol_mutex);
if (add_netproto) {
if (inet6_add_protocol(netproto(protocol), protocol)) {
pr_err("%s: can't add protocol\n", __func__);
ret = -EAGAIN;
}
}
return ret;
}
EXPORT_SYMBOL(xfrm6_protocol_register);
int xfrm6_protocol_deregister(struct xfrm6_protocol *handler,
unsigned char protocol)
{
struct xfrm6_protocol __rcu **pprev;
struct xfrm6_protocol *t;
int ret = -ENOENT;
if (!proto_handlers(protocol) || !netproto(protocol))
return -EINVAL;
mutex_lock(&xfrm6_protocol_mutex);
for (pprev = proto_handlers(protocol);
(t = rcu_dereference_protected(*pprev,
lockdep_is_held(&xfrm6_protocol_mutex))) != NULL;
pprev = &t->next) {
if (t == handler) {
*pprev = handler->next;
ret = 0;
break;
}
}
if (!rcu_dereference_protected(*proto_handlers(protocol),
lockdep_is_held(&xfrm6_protocol_mutex))) {
if (inet6_del_protocol(netproto(protocol), protocol) < 0) {
pr_err("%s: can't remove protocol\n", __func__);
ret = -EAGAIN;
}
}
mutex_unlock(&xfrm6_protocol_mutex);
synchronize_net();
return ret;
}
EXPORT_SYMBOL(xfrm6_protocol_deregister);
int __init xfrm6_protocol_init(void)
{
return xfrm_input_register_afinfo(&xfrm6_input_afinfo);
}
void xfrm6_protocol_fini(void)
{
xfrm_input_unregister_afinfo(&xfrm6_input_afinfo);
}
| linux-master | net/ipv6/xfrm6_protocol.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* IPV6 GSO/GRO offload support
* Linux INET6 implementation
*
* UDPv6 GSO support
*/
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/indirect_call_wrapper.h>
#include <net/protocol.h>
#include <net/ipv6.h>
#include <net/udp.h>
#include <net/ip6_checksum.h>
#include "ip6_offload.h"
#include <net/gro.h>
#include <net/gso.h>
static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
unsigned int mss;
unsigned int unfrag_ip6hlen, unfrag_len;
struct frag_hdr *fptr;
u8 *packet_start, *prevhdr;
u8 nexthdr;
u8 frag_hdr_sz = sizeof(struct frag_hdr);
__wsum csum;
int tnl_hlen;
int err;
if (skb->encapsulation && skb_shinfo(skb)->gso_type &
(SKB_GSO_UDP_TUNNEL|SKB_GSO_UDP_TUNNEL_CSUM))
segs = skb_udp_tunnel_segment(skb, features, true);
else {
const struct ipv6hdr *ipv6h;
struct udphdr *uh;
if (!(skb_shinfo(skb)->gso_type & (SKB_GSO_UDP | SKB_GSO_UDP_L4)))
goto out;
if (!pskb_may_pull(skb, sizeof(struct udphdr)))
goto out;
if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4)
return __udp_gso_segment(skb, features, true);
mss = skb_shinfo(skb)->gso_size;
if (unlikely(skb->len <= mss))
goto out;
/* Do software UFO. Complete and fill in the UDP checksum as HW cannot
* do checksum of UDP packets sent as multiple IP fragments.
*/
uh = udp_hdr(skb);
ipv6h = ipv6_hdr(skb);
uh->check = 0;
csum = skb_checksum(skb, 0, skb->len, 0);
uh->check = udp_v6_check(skb->len, &ipv6h->saddr,
&ipv6h->daddr, csum);
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
skb->ip_summed = CHECKSUM_UNNECESSARY;
/* If there is no outer header we can fake a checksum offload
* due to the fact that we have already done the checksum in
* software prior to segmenting the frame.
*/
if (!skb->encap_hdr_csum)
features |= NETIF_F_HW_CSUM;
/* Check if there is enough headroom to insert fragment header. */
tnl_hlen = skb_tnl_header_len(skb);
if (skb->mac_header < (tnl_hlen + frag_hdr_sz)) {
if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz))
goto out;
}
/* Find the unfragmentable header and shift it left by frag_hdr_sz
* bytes to insert fragment header.
*/
err = ip6_find_1stfragopt(skb, &prevhdr);
if (err < 0)
return ERR_PTR(err);
unfrag_ip6hlen = err;
nexthdr = *prevhdr;
*prevhdr = NEXTHDR_FRAGMENT;
unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) +
unfrag_ip6hlen + tnl_hlen;
packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset;
memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len);
SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz;
skb->mac_header -= frag_hdr_sz;
skb->network_header -= frag_hdr_sz;
fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);
fptr->nexthdr = nexthdr;
fptr->reserved = 0;
fptr->identification = ipv6_proxy_select_ident(dev_net(skb->dev), skb);
/* Fragment the skb. ipv6 header and the remaining fields of the
* fragment header are updated in ipv6_gso_segment()
*/
segs = skb_segment(skb, features);
}
out:
return segs;
}
static struct sock *udp6_gro_lookup_skb(struct sk_buff *skb, __be16 sport,
__be16 dport)
{
const struct ipv6hdr *iph = skb_gro_network_header(skb);
struct net *net = dev_net(skb->dev);
int iif, sdif;
inet6_get_iif_sdif(skb, &iif, &sdif);
return __udp6_lib_lookup(net, &iph->saddr, sport,
&iph->daddr, dport, iif,
sdif, net->ipv4.udp_table, NULL);
}
INDIRECT_CALLABLE_SCOPE
struct sk_buff *udp6_gro_receive(struct list_head *head, struct sk_buff *skb)
{
struct udphdr *uh = udp_gro_udphdr(skb);
struct sock *sk = NULL;
struct sk_buff *pp;
if (unlikely(!uh))
goto flush;
/* Don't bother verifying checksum if we're going to flush anyway. */
if (NAPI_GRO_CB(skb)->flush)
goto skip;
if (skb_gro_checksum_validate_zero_check(skb, IPPROTO_UDP, uh->check,
ip6_gro_compute_pseudo))
goto flush;
else if (uh->check)
skb_gro_checksum_try_convert(skb, IPPROTO_UDP,
ip6_gro_compute_pseudo);
skip:
NAPI_GRO_CB(skb)->is_ipv6 = 1;
if (static_branch_unlikely(&udpv6_encap_needed_key))
sk = udp6_gro_lookup_skb(skb, uh->source, uh->dest);
pp = udp_gro_receive(head, skb, uh, sk);
return pp;
flush:
NAPI_GRO_CB(skb)->flush = 1;
return NULL;
}
INDIRECT_CALLABLE_SCOPE int udp6_gro_complete(struct sk_buff *skb, int nhoff)
{
const struct ipv6hdr *ipv6h = ipv6_hdr(skb);
struct udphdr *uh = (struct udphdr *)(skb->data + nhoff);
/* do fraglist only if there is no outer UDP encap (or we already processed it) */
if (NAPI_GRO_CB(skb)->is_flist && !NAPI_GRO_CB(skb)->encap_mark) {
uh->len = htons(skb->len - nhoff);
skb_shinfo(skb)->gso_type |= (SKB_GSO_FRAGLIST|SKB_GSO_UDP_L4);
skb_shinfo(skb)->gso_segs = NAPI_GRO_CB(skb)->count;
if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
if (skb->csum_level < SKB_MAX_CSUM_LEVEL)
skb->csum_level++;
} else {
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb->csum_level = 0;
}
return 0;
}
if (uh->check)
uh->check = ~udp_v6_check(skb->len - nhoff, &ipv6h->saddr,
&ipv6h->daddr, 0);
return udp_gro_complete(skb, nhoff, udp6_lib_lookup_skb);
}
static const struct net_offload udpv6_offload = {
.callbacks = {
.gso_segment = udp6_ufo_fragment,
.gro_receive = udp6_gro_receive,
.gro_complete = udp6_gro_complete,
},
};
int udpv6_offload_init(void)
{
return inet6_add_offload(&udpv6_offload, IPPROTO_UDP);
}
int udpv6_offload_exit(void)
{
return inet6_del_offload(&udpv6_offload, IPPROTO_UDP);
}
| linux-master | net/ipv6/udp_offload.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* xfrm6_output.c - Common IPsec encapsulation code for IPv6.
* Copyright (C) 2002 USAGI/WIDE Project
* Copyright (c) 2004 Herbert Xu <[email protected]>
*/
#include <linux/if_ether.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/icmpv6.h>
#include <linux/netfilter_ipv6.h>
#include <net/dst.h>
#include <net/ipv6.h>
#include <net/ip6_route.h>
#include <net/xfrm.h>
void xfrm6_local_rxpmtu(struct sk_buff *skb, u32 mtu)
{
struct flowi6 fl6;
struct sock *sk = skb->sk;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.daddr = ipv6_hdr(skb)->daddr;
ipv6_local_rxpmtu(sk, &fl6, mtu);
}
void xfrm6_local_error(struct sk_buff *skb, u32 mtu)
{
struct flowi6 fl6;
const struct ipv6hdr *hdr;
struct sock *sk = skb->sk;
hdr = skb->encapsulation ? inner_ipv6_hdr(skb) : ipv6_hdr(skb);
fl6.fl6_dport = inet_sk(sk)->inet_dport;
fl6.daddr = hdr->daddr;
ipv6_local_error(sk, EMSGSIZE, &fl6, mtu);
}
static int __xfrm6_output_finish(struct net *net, struct sock *sk, struct sk_buff *skb)
{
return xfrm_output(sk, skb);
}
static int xfrm6_noneed_fragment(struct sk_buff *skb)
{
struct frag_hdr *fh;
u8 prevhdr = ipv6_hdr(skb)->nexthdr;
if (prevhdr != NEXTHDR_FRAGMENT)
return 0;
fh = (struct frag_hdr *)(skb->data + sizeof(struct ipv6hdr));
if (fh->nexthdr == NEXTHDR_ESP || fh->nexthdr == NEXTHDR_AUTH)
return 1;
return 0;
}
static int __xfrm6_output(struct net *net, struct sock *sk, struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct xfrm_state *x = dst->xfrm;
unsigned int mtu;
bool toobig;
#ifdef CONFIG_NETFILTER
if (!x) {
IP6CB(skb)->flags |= IP6SKB_REROUTED;
return dst_output(net, sk, skb);
}
#endif
if (x->props.mode != XFRM_MODE_TUNNEL)
goto skip_frag;
if (skb->protocol == htons(ETH_P_IPV6))
mtu = ip6_skb_dst_mtu(skb);
else
mtu = dst_mtu(skb_dst(skb));
toobig = skb->len > mtu && !skb_is_gso(skb);
if (toobig && xfrm6_local_dontfrag(skb->sk)) {
xfrm6_local_rxpmtu(skb, mtu);
kfree_skb(skb);
return -EMSGSIZE;
} else if (toobig && xfrm6_noneed_fragment(skb)) {
skb->ignore_df = 1;
goto skip_frag;
} else if (!skb->ignore_df && toobig && skb->sk) {
xfrm_local_error(skb, mtu);
kfree_skb(skb);
return -EMSGSIZE;
}
if (toobig || dst_allfrag(skb_dst(skb)))
return ip6_fragment(net, sk, skb,
__xfrm6_output_finish);
skip_frag:
return xfrm_output(sk, skb);
}
int xfrm6_output(struct net *net, struct sock *sk, struct sk_buff *skb)
{
return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING,
net, sk, skb, skb->dev, skb_dst(skb)->dev,
__xfrm6_output,
!(IP6CB(skb)->flags & IP6SKB_REROUTED));
}
| linux-master | net/ipv6/xfrm6_output.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (C)2003,2004 USAGI/WIDE Project
*
* Authors Mitsuru KANDA <[email protected]>
* YOSHIFUJI Hideaki <[email protected]>
*
* Based on net/ipv4/xfrm4_tunnel.c
*/
#include <linux/module.h>
#include <linux/xfrm.h>
#include <linux/slab.h>
#include <linux/rculist.h>
#include <net/ip.h>
#include <net/xfrm.h>
#include <net/ipv6.h>
#include <linux/ipv6.h>
#include <linux/icmpv6.h>
#include <linux/mutex.h>
#include <net/netns/generic.h>
#define XFRM6_TUNNEL_SPI_BYADDR_HSIZE 256
#define XFRM6_TUNNEL_SPI_BYSPI_HSIZE 256
#define XFRM6_TUNNEL_SPI_MIN 1
#define XFRM6_TUNNEL_SPI_MAX 0xffffffff
struct xfrm6_tunnel_net {
struct hlist_head spi_byaddr[XFRM6_TUNNEL_SPI_BYADDR_HSIZE];
struct hlist_head spi_byspi[XFRM6_TUNNEL_SPI_BYSPI_HSIZE];
u32 spi;
};
static unsigned int xfrm6_tunnel_net_id __read_mostly;
static inline struct xfrm6_tunnel_net *xfrm6_tunnel_pernet(struct net *net)
{
return net_generic(net, xfrm6_tunnel_net_id);
}
/*
* xfrm_tunnel_spi things are for allocating unique id ("spi")
* per xfrm_address_t.
*/
struct xfrm6_tunnel_spi {
struct hlist_node list_byaddr;
struct hlist_node list_byspi;
xfrm_address_t addr;
u32 spi;
refcount_t refcnt;
struct rcu_head rcu_head;
};
static DEFINE_SPINLOCK(xfrm6_tunnel_spi_lock);
static struct kmem_cache *xfrm6_tunnel_spi_kmem __read_mostly;
static inline unsigned int xfrm6_tunnel_spi_hash_byaddr(const xfrm_address_t *addr)
{
unsigned int h;
h = ipv6_addr_hash((const struct in6_addr *)addr);
h ^= h >> 16;
h ^= h >> 8;
h &= XFRM6_TUNNEL_SPI_BYADDR_HSIZE - 1;
return h;
}
static inline unsigned int xfrm6_tunnel_spi_hash_byspi(u32 spi)
{
return spi % XFRM6_TUNNEL_SPI_BYSPI_HSIZE;
}
static struct xfrm6_tunnel_spi *__xfrm6_tunnel_spi_lookup(struct net *net, const xfrm_address_t *saddr)
{
struct xfrm6_tunnel_net *xfrm6_tn = xfrm6_tunnel_pernet(net);
struct xfrm6_tunnel_spi *x6spi;
hlist_for_each_entry_rcu(x6spi,
&xfrm6_tn->spi_byaddr[xfrm6_tunnel_spi_hash_byaddr(saddr)],
list_byaddr, lockdep_is_held(&xfrm6_tunnel_spi_lock)) {
if (xfrm6_addr_equal(&x6spi->addr, saddr))
return x6spi;
}
return NULL;
}
__be32 xfrm6_tunnel_spi_lookup(struct net *net, const xfrm_address_t *saddr)
{
struct xfrm6_tunnel_spi *x6spi;
u32 spi;
rcu_read_lock_bh();
x6spi = __xfrm6_tunnel_spi_lookup(net, saddr);
spi = x6spi ? x6spi->spi : 0;
rcu_read_unlock_bh();
return htonl(spi);
}
EXPORT_SYMBOL(xfrm6_tunnel_spi_lookup);
static int __xfrm6_tunnel_spi_check(struct net *net, u32 spi)
{
struct xfrm6_tunnel_net *xfrm6_tn = xfrm6_tunnel_pernet(net);
struct xfrm6_tunnel_spi *x6spi;
int index = xfrm6_tunnel_spi_hash_byspi(spi);
hlist_for_each_entry(x6spi,
&xfrm6_tn->spi_byspi[index],
list_byspi) {
if (x6spi->spi == spi)
return -1;
}
return index;
}
static u32 __xfrm6_tunnel_alloc_spi(struct net *net, xfrm_address_t *saddr)
{
struct xfrm6_tunnel_net *xfrm6_tn = xfrm6_tunnel_pernet(net);
u32 spi;
struct xfrm6_tunnel_spi *x6spi;
int index;
if (xfrm6_tn->spi < XFRM6_TUNNEL_SPI_MIN ||
xfrm6_tn->spi >= XFRM6_TUNNEL_SPI_MAX)
xfrm6_tn->spi = XFRM6_TUNNEL_SPI_MIN;
else
xfrm6_tn->spi++;
for (spi = xfrm6_tn->spi; spi <= XFRM6_TUNNEL_SPI_MAX; spi++) {
index = __xfrm6_tunnel_spi_check(net, spi);
if (index >= 0)
goto alloc_spi;
if (spi == XFRM6_TUNNEL_SPI_MAX)
break;
}
for (spi = XFRM6_TUNNEL_SPI_MIN; spi < xfrm6_tn->spi; spi++) {
index = __xfrm6_tunnel_spi_check(net, spi);
if (index >= 0)
goto alloc_spi;
}
spi = 0;
goto out;
alloc_spi:
xfrm6_tn->spi = spi;
x6spi = kmem_cache_alloc(xfrm6_tunnel_spi_kmem, GFP_ATOMIC);
if (!x6spi)
goto out;
memcpy(&x6spi->addr, saddr, sizeof(x6spi->addr));
x6spi->spi = spi;
refcount_set(&x6spi->refcnt, 1);
hlist_add_head_rcu(&x6spi->list_byspi, &xfrm6_tn->spi_byspi[index]);
index = xfrm6_tunnel_spi_hash_byaddr(saddr);
hlist_add_head_rcu(&x6spi->list_byaddr, &xfrm6_tn->spi_byaddr[index]);
out:
return spi;
}
__be32 xfrm6_tunnel_alloc_spi(struct net *net, xfrm_address_t *saddr)
{
struct xfrm6_tunnel_spi *x6spi;
u32 spi;
spin_lock_bh(&xfrm6_tunnel_spi_lock);
x6spi = __xfrm6_tunnel_spi_lookup(net, saddr);
if (x6spi) {
refcount_inc(&x6spi->refcnt);
spi = x6spi->spi;
} else
spi = __xfrm6_tunnel_alloc_spi(net, saddr);
spin_unlock_bh(&xfrm6_tunnel_spi_lock);
return htonl(spi);
}
EXPORT_SYMBOL(xfrm6_tunnel_alloc_spi);
static void x6spi_destroy_rcu(struct rcu_head *head)
{
kmem_cache_free(xfrm6_tunnel_spi_kmem,
container_of(head, struct xfrm6_tunnel_spi, rcu_head));
}
static void xfrm6_tunnel_free_spi(struct net *net, xfrm_address_t *saddr)
{
struct xfrm6_tunnel_net *xfrm6_tn = xfrm6_tunnel_pernet(net);
struct xfrm6_tunnel_spi *x6spi;
struct hlist_node *n;
spin_lock_bh(&xfrm6_tunnel_spi_lock);
hlist_for_each_entry_safe(x6spi, n,
&xfrm6_tn->spi_byaddr[xfrm6_tunnel_spi_hash_byaddr(saddr)],
list_byaddr)
{
if (xfrm6_addr_equal(&x6spi->addr, saddr)) {
if (refcount_dec_and_test(&x6spi->refcnt)) {
hlist_del_rcu(&x6spi->list_byaddr);
hlist_del_rcu(&x6spi->list_byspi);
call_rcu(&x6spi->rcu_head, x6spi_destroy_rcu);
break;
}
}
}
spin_unlock_bh(&xfrm6_tunnel_spi_lock);
}
static int xfrm6_tunnel_output(struct xfrm_state *x, struct sk_buff *skb)
{
skb_push(skb, -skb_network_offset(skb));
return 0;
}
static int xfrm6_tunnel_input(struct xfrm_state *x, struct sk_buff *skb)
{
return skb_network_header(skb)[IP6CB(skb)->nhoff];
}
static int xfrm6_tunnel_rcv(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
const struct ipv6hdr *iph = ipv6_hdr(skb);
__be32 spi;
spi = xfrm6_tunnel_spi_lookup(net, (const xfrm_address_t *)&iph->saddr);
return xfrm6_rcv_spi(skb, IPPROTO_IPV6, spi, NULL);
}
static int xfrm6_tunnel_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
/* xfrm6_tunnel native err handling */
switch (type) {
case ICMPV6_DEST_UNREACH:
switch (code) {
case ICMPV6_NOROUTE:
case ICMPV6_ADM_PROHIBITED:
case ICMPV6_NOT_NEIGHBOUR:
case ICMPV6_ADDR_UNREACH:
case ICMPV6_PORT_UNREACH:
default:
break;
}
break;
case ICMPV6_PKT_TOOBIG:
break;
case ICMPV6_TIME_EXCEED:
switch (code) {
case ICMPV6_EXC_HOPLIMIT:
break;
case ICMPV6_EXC_FRAGTIME:
default:
break;
}
break;
case ICMPV6_PARAMPROB:
switch (code) {
case ICMPV6_HDR_FIELD: break;
case ICMPV6_UNK_NEXTHDR: break;
case ICMPV6_UNK_OPTION: break;
}
break;
default:
break;
}
return 0;
}
static int xfrm6_tunnel_init_state(struct xfrm_state *x, struct netlink_ext_ack *extack)
{
if (x->props.mode != XFRM_MODE_TUNNEL) {
NL_SET_ERR_MSG(extack, "IPv6 tunnel can only be used with tunnel mode");
return -EINVAL;
}
if (x->encap) {
NL_SET_ERR_MSG(extack, "IPv6 tunnel is not compatible with encapsulation");
return -EINVAL;
}
x->props.header_len = sizeof(struct ipv6hdr);
return 0;
}
static void xfrm6_tunnel_destroy(struct xfrm_state *x)
{
struct net *net = xs_net(x);
xfrm6_tunnel_free_spi(net, (xfrm_address_t *)&x->props.saddr);
}
static const struct xfrm_type xfrm6_tunnel_type = {
.owner = THIS_MODULE,
.proto = IPPROTO_IPV6,
.init_state = xfrm6_tunnel_init_state,
.destructor = xfrm6_tunnel_destroy,
.input = xfrm6_tunnel_input,
.output = xfrm6_tunnel_output,
};
static struct xfrm6_tunnel xfrm6_tunnel_handler __read_mostly = {
.handler = xfrm6_tunnel_rcv,
.err_handler = xfrm6_tunnel_err,
.priority = 3,
};
static struct xfrm6_tunnel xfrm46_tunnel_handler __read_mostly = {
.handler = xfrm6_tunnel_rcv,
.err_handler = xfrm6_tunnel_err,
.priority = 3,
};
static int __net_init xfrm6_tunnel_net_init(struct net *net)
{
struct xfrm6_tunnel_net *xfrm6_tn = xfrm6_tunnel_pernet(net);
unsigned int i;
for (i = 0; i < XFRM6_TUNNEL_SPI_BYADDR_HSIZE; i++)
INIT_HLIST_HEAD(&xfrm6_tn->spi_byaddr[i]);
for (i = 0; i < XFRM6_TUNNEL_SPI_BYSPI_HSIZE; i++)
INIT_HLIST_HEAD(&xfrm6_tn->spi_byspi[i]);
xfrm6_tn->spi = 0;
return 0;
}
static void __net_exit xfrm6_tunnel_net_exit(struct net *net)
{
struct xfrm6_tunnel_net *xfrm6_tn = xfrm6_tunnel_pernet(net);
unsigned int i;
xfrm_flush_gc();
xfrm_state_flush(net, 0, false, true);
for (i = 0; i < XFRM6_TUNNEL_SPI_BYADDR_HSIZE; i++)
WARN_ON_ONCE(!hlist_empty(&xfrm6_tn->spi_byaddr[i]));
for (i = 0; i < XFRM6_TUNNEL_SPI_BYSPI_HSIZE; i++)
WARN_ON_ONCE(!hlist_empty(&xfrm6_tn->spi_byspi[i]));
}
static struct pernet_operations xfrm6_tunnel_net_ops = {
.init = xfrm6_tunnel_net_init,
.exit = xfrm6_tunnel_net_exit,
.id = &xfrm6_tunnel_net_id,
.size = sizeof(struct xfrm6_tunnel_net),
};
static int __init xfrm6_tunnel_init(void)
{
int rv;
xfrm6_tunnel_spi_kmem = kmem_cache_create("xfrm6_tunnel_spi",
sizeof(struct xfrm6_tunnel_spi),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!xfrm6_tunnel_spi_kmem)
return -ENOMEM;
rv = register_pernet_subsys(&xfrm6_tunnel_net_ops);
if (rv < 0)
goto out_pernet;
rv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6);
if (rv < 0)
goto out_type;
rv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6);
if (rv < 0)
goto out_xfrm6;
rv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET);
if (rv < 0)
goto out_xfrm46;
return 0;
out_xfrm46:
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
out_xfrm6:
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
out_type:
unregister_pernet_subsys(&xfrm6_tunnel_net_ops);
out_pernet:
kmem_cache_destroy(xfrm6_tunnel_spi_kmem);
return rv;
}
static void __exit xfrm6_tunnel_fini(void)
{
xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
unregister_pernet_subsys(&xfrm6_tunnel_net_ops);
/* Someone maybe has gotten the xfrm6_tunnel_spi.
* So need to wait it.
*/
rcu_barrier();
kmem_cache_destroy(xfrm6_tunnel_spi_kmem);
}
module_init(xfrm6_tunnel_init);
module_exit(xfrm6_tunnel_fini);
MODULE_LICENSE("GPL");
MODULE_ALIAS_XFRM_TYPE(AF_INET6, XFRM_PROTO_IPV6);
| linux-master | net/ipv6/xfrm6_tunnel.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Linux INET6 implementation
* Forwarding Information Database
*
* Authors:
* Pedro Roque <[email protected]>
*
* Changes:
* Yuji SEKIYA @USAGI: Support default route on router node;
* remove ip6_null_entry from the top of
* routing table.
* Ville Nuorvala: Fixed routing subtrees.
*/
#define pr_fmt(fmt) "IPv6: " fmt
#include <linux/bpf.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/net.h>
#include <linux/route.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/addrconf.h>
#include <net/lwtunnel.h>
#include <net/fib_notifier.h>
#include <net/ip_fib.h>
#include <net/ip6_fib.h>
#include <net/ip6_route.h>
static struct kmem_cache *fib6_node_kmem __read_mostly;
struct fib6_cleaner {
struct fib6_walker w;
struct net *net;
int (*func)(struct fib6_info *, void *arg);
int sernum;
void *arg;
bool skip_notify;
};
#ifdef CONFIG_IPV6_SUBTREES
#define FWS_INIT FWS_S
#else
#define FWS_INIT FWS_L
#endif
static struct fib6_info *fib6_find_prefix(struct net *net,
struct fib6_table *table,
struct fib6_node *fn);
static struct fib6_node *fib6_repair_tree(struct net *net,
struct fib6_table *table,
struct fib6_node *fn);
static int fib6_walk(struct net *net, struct fib6_walker *w);
static int fib6_walk_continue(struct fib6_walker *w);
/*
* A routing update causes an increase of the serial number on the
* affected subtree. This allows for cached routes to be asynchronously
* tested when modifications are made to the destination cache as a
* result of redirects, path MTU changes, etc.
*/
static void fib6_gc_timer_cb(struct timer_list *t);
#define FOR_WALKERS(net, w) \
list_for_each_entry(w, &(net)->ipv6.fib6_walkers, lh)
static void fib6_walker_link(struct net *net, struct fib6_walker *w)
{
write_lock_bh(&net->ipv6.fib6_walker_lock);
list_add(&w->lh, &net->ipv6.fib6_walkers);
write_unlock_bh(&net->ipv6.fib6_walker_lock);
}
static void fib6_walker_unlink(struct net *net, struct fib6_walker *w)
{
write_lock_bh(&net->ipv6.fib6_walker_lock);
list_del(&w->lh);
write_unlock_bh(&net->ipv6.fib6_walker_lock);
}
static int fib6_new_sernum(struct net *net)
{
int new, old = atomic_read(&net->ipv6.fib6_sernum);
do {
new = old < INT_MAX ? old + 1 : 1;
} while (!atomic_try_cmpxchg(&net->ipv6.fib6_sernum, &old, new));
return new;
}
enum {
FIB6_NO_SERNUM_CHANGE = 0,
};
void fib6_update_sernum(struct net *net, struct fib6_info *f6i)
{
struct fib6_node *fn;
fn = rcu_dereference_protected(f6i->fib6_node,
lockdep_is_held(&f6i->fib6_table->tb6_lock));
if (fn)
WRITE_ONCE(fn->fn_sernum, fib6_new_sernum(net));
}
/*
* Auxiliary address test functions for the radix tree.
*
* These assume a 32bit processor (although it will work on
* 64bit processors)
*/
/*
* test bit
*/
#if defined(__LITTLE_ENDIAN)
# define BITOP_BE32_SWIZZLE (0x1F & ~7)
#else
# define BITOP_BE32_SWIZZLE 0
#endif
static __be32 addr_bit_set(const void *token, int fn_bit)
{
const __be32 *addr = token;
/*
* Here,
* 1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)
* is optimized version of
* htonl(1 << ((~fn_bit)&0x1F))
* See include/asm-generic/bitops/le.h.
*/
return (__force __be32)(1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)) &
addr[fn_bit >> 5];
}
struct fib6_info *fib6_info_alloc(gfp_t gfp_flags, bool with_fib6_nh)
{
struct fib6_info *f6i;
size_t sz = sizeof(*f6i);
if (with_fib6_nh)
sz += sizeof(struct fib6_nh);
f6i = kzalloc(sz, gfp_flags);
if (!f6i)
return NULL;
/* fib6_siblings is a union with nh_list, so this initializes both */
INIT_LIST_HEAD(&f6i->fib6_siblings);
refcount_set(&f6i->fib6_ref, 1);
INIT_HLIST_NODE(&f6i->gc_link);
return f6i;
}
void fib6_info_destroy_rcu(struct rcu_head *head)
{
struct fib6_info *f6i = container_of(head, struct fib6_info, rcu);
WARN_ON(f6i->fib6_node);
if (f6i->nh)
nexthop_put(f6i->nh);
else
fib6_nh_release(f6i->fib6_nh);
ip_fib_metrics_put(f6i->fib6_metrics);
kfree(f6i);
}
EXPORT_SYMBOL_GPL(fib6_info_destroy_rcu);
static struct fib6_node *node_alloc(struct net *net)
{
struct fib6_node *fn;
fn = kmem_cache_zalloc(fib6_node_kmem, GFP_ATOMIC);
if (fn)
net->ipv6.rt6_stats->fib_nodes++;
return fn;
}
static void node_free_immediate(struct net *net, struct fib6_node *fn)
{
kmem_cache_free(fib6_node_kmem, fn);
net->ipv6.rt6_stats->fib_nodes--;
}
static void node_free_rcu(struct rcu_head *head)
{
struct fib6_node *fn = container_of(head, struct fib6_node, rcu);
kmem_cache_free(fib6_node_kmem, fn);
}
static void node_free(struct net *net, struct fib6_node *fn)
{
call_rcu(&fn->rcu, node_free_rcu);
net->ipv6.rt6_stats->fib_nodes--;
}
static void fib6_free_table(struct fib6_table *table)
{
inetpeer_invalidate_tree(&table->tb6_peers);
kfree(table);
}
static void fib6_link_table(struct net *net, struct fib6_table *tb)
{
unsigned int h;
/*
* Initialize table lock at a single place to give lockdep a key,
* tables aren't visible prior to being linked to the list.
*/
spin_lock_init(&tb->tb6_lock);
h = tb->tb6_id & (FIB6_TABLE_HASHSZ - 1);
/*
* No protection necessary, this is the only list mutatation
* operation, tables never disappear once they exist.
*/
hlist_add_head_rcu(&tb->tb6_hlist, &net->ipv6.fib_table_hash[h]);
}
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
static struct fib6_table *fib6_alloc_table(struct net *net, u32 id)
{
struct fib6_table *table;
table = kzalloc(sizeof(*table), GFP_ATOMIC);
if (table) {
table->tb6_id = id;
rcu_assign_pointer(table->tb6_root.leaf,
net->ipv6.fib6_null_entry);
table->tb6_root.fn_flags = RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
inet_peer_base_init(&table->tb6_peers);
INIT_HLIST_HEAD(&table->tb6_gc_hlist);
}
return table;
}
struct fib6_table *fib6_new_table(struct net *net, u32 id)
{
struct fib6_table *tb;
if (id == 0)
id = RT6_TABLE_MAIN;
tb = fib6_get_table(net, id);
if (tb)
return tb;
tb = fib6_alloc_table(net, id);
if (tb)
fib6_link_table(net, tb);
return tb;
}
EXPORT_SYMBOL_GPL(fib6_new_table);
struct fib6_table *fib6_get_table(struct net *net, u32 id)
{
struct fib6_table *tb;
struct hlist_head *head;
unsigned int h;
if (id == 0)
id = RT6_TABLE_MAIN;
h = id & (FIB6_TABLE_HASHSZ - 1);
rcu_read_lock();
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
if (tb->tb6_id == id) {
rcu_read_unlock();
return tb;
}
}
rcu_read_unlock();
return NULL;
}
EXPORT_SYMBOL_GPL(fib6_get_table);
static void __net_init fib6_tables_init(struct net *net)
{
fib6_link_table(net, net->ipv6.fib6_main_tbl);
fib6_link_table(net, net->ipv6.fib6_local_tbl);
}
#else
struct fib6_table *fib6_new_table(struct net *net, u32 id)
{
return fib6_get_table(net, id);
}
struct fib6_table *fib6_get_table(struct net *net, u32 id)
{
return net->ipv6.fib6_main_tbl;
}
struct dst_entry *fib6_rule_lookup(struct net *net, struct flowi6 *fl6,
const struct sk_buff *skb,
int flags, pol_lookup_t lookup)
{
struct rt6_info *rt;
rt = pol_lookup_func(lookup,
net, net->ipv6.fib6_main_tbl, fl6, skb, flags);
if (rt->dst.error == -EAGAIN) {
ip6_rt_put_flags(rt, flags);
rt = net->ipv6.ip6_null_entry;
if (!(flags & RT6_LOOKUP_F_DST_NOREF))
dst_hold(&rt->dst);
}
return &rt->dst;
}
/* called with rcu lock held; no reference taken on fib6_info */
int fib6_lookup(struct net *net, int oif, struct flowi6 *fl6,
struct fib6_result *res, int flags)
{
return fib6_table_lookup(net, net->ipv6.fib6_main_tbl, oif, fl6,
res, flags);
}
static void __net_init fib6_tables_init(struct net *net)
{
fib6_link_table(net, net->ipv6.fib6_main_tbl);
}
#endif
unsigned int fib6_tables_seq_read(struct net *net)
{
unsigned int h, fib_seq = 0;
rcu_read_lock();
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
struct hlist_head *head = &net->ipv6.fib_table_hash[h];
struct fib6_table *tb;
hlist_for_each_entry_rcu(tb, head, tb6_hlist)
fib_seq += tb->fib_seq;
}
rcu_read_unlock();
return fib_seq;
}
static int call_fib6_entry_notifier(struct notifier_block *nb,
enum fib_event_type event_type,
struct fib6_info *rt,
struct netlink_ext_ack *extack)
{
struct fib6_entry_notifier_info info = {
.info.extack = extack,
.rt = rt,
};
return call_fib6_notifier(nb, event_type, &info.info);
}
static int call_fib6_multipath_entry_notifier(struct notifier_block *nb,
enum fib_event_type event_type,
struct fib6_info *rt,
unsigned int nsiblings,
struct netlink_ext_ack *extack)
{
struct fib6_entry_notifier_info info = {
.info.extack = extack,
.rt = rt,
.nsiblings = nsiblings,
};
return call_fib6_notifier(nb, event_type, &info.info);
}
int call_fib6_entry_notifiers(struct net *net,
enum fib_event_type event_type,
struct fib6_info *rt,
struct netlink_ext_ack *extack)
{
struct fib6_entry_notifier_info info = {
.info.extack = extack,
.rt = rt,
};
rt->fib6_table->fib_seq++;
return call_fib6_notifiers(net, event_type, &info.info);
}
int call_fib6_multipath_entry_notifiers(struct net *net,
enum fib_event_type event_type,
struct fib6_info *rt,
unsigned int nsiblings,
struct netlink_ext_ack *extack)
{
struct fib6_entry_notifier_info info = {
.info.extack = extack,
.rt = rt,
.nsiblings = nsiblings,
};
rt->fib6_table->fib_seq++;
return call_fib6_notifiers(net, event_type, &info.info);
}
int call_fib6_entry_notifiers_replace(struct net *net, struct fib6_info *rt)
{
struct fib6_entry_notifier_info info = {
.rt = rt,
.nsiblings = rt->fib6_nsiblings,
};
rt->fib6_table->fib_seq++;
return call_fib6_notifiers(net, FIB_EVENT_ENTRY_REPLACE, &info.info);
}
struct fib6_dump_arg {
struct net *net;
struct notifier_block *nb;
struct netlink_ext_ack *extack;
};
static int fib6_rt_dump(struct fib6_info *rt, struct fib6_dump_arg *arg)
{
enum fib_event_type fib_event = FIB_EVENT_ENTRY_REPLACE;
int err;
if (!rt || rt == arg->net->ipv6.fib6_null_entry)
return 0;
if (rt->fib6_nsiblings)
err = call_fib6_multipath_entry_notifier(arg->nb, fib_event,
rt,
rt->fib6_nsiblings,
arg->extack);
else
err = call_fib6_entry_notifier(arg->nb, fib_event, rt,
arg->extack);
return err;
}
static int fib6_node_dump(struct fib6_walker *w)
{
int err;
err = fib6_rt_dump(w->leaf, w->args);
w->leaf = NULL;
return err;
}
static int fib6_table_dump(struct net *net, struct fib6_table *tb,
struct fib6_walker *w)
{
int err;
w->root = &tb->tb6_root;
spin_lock_bh(&tb->tb6_lock);
err = fib6_walk(net, w);
spin_unlock_bh(&tb->tb6_lock);
return err;
}
/* Called with rcu_read_lock() */
int fib6_tables_dump(struct net *net, struct notifier_block *nb,
struct netlink_ext_ack *extack)
{
struct fib6_dump_arg arg;
struct fib6_walker *w;
unsigned int h;
int err = 0;
w = kzalloc(sizeof(*w), GFP_ATOMIC);
if (!w)
return -ENOMEM;
w->func = fib6_node_dump;
arg.net = net;
arg.nb = nb;
arg.extack = extack;
w->args = &arg;
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
struct hlist_head *head = &net->ipv6.fib_table_hash[h];
struct fib6_table *tb;
hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
err = fib6_table_dump(net, tb, w);
if (err)
goto out;
}
}
out:
kfree(w);
/* The tree traversal function should never return a positive value. */
return err > 0 ? -EINVAL : err;
}
static int fib6_dump_node(struct fib6_walker *w)
{
int res;
struct fib6_info *rt;
for_each_fib6_walker_rt(w) {
res = rt6_dump_route(rt, w->args, w->skip_in_node);
if (res >= 0) {
/* Frame is full, suspend walking */
w->leaf = rt;
/* We'll restart from this node, so if some routes were
* already dumped, skip them next time.
*/
w->skip_in_node += res;
return 1;
}
w->skip_in_node = 0;
/* Multipath routes are dumped in one route with the
* RTA_MULTIPATH attribute. Jump 'rt' to point to the
* last sibling of this route (no need to dump the
* sibling routes again)
*/
if (rt->fib6_nsiblings)
rt = list_last_entry(&rt->fib6_siblings,
struct fib6_info,
fib6_siblings);
}
w->leaf = NULL;
return 0;
}
static void fib6_dump_end(struct netlink_callback *cb)
{
struct net *net = sock_net(cb->skb->sk);
struct fib6_walker *w = (void *)cb->args[2];
if (w) {
if (cb->args[4]) {
cb->args[4] = 0;
fib6_walker_unlink(net, w);
}
cb->args[2] = 0;
kfree(w);
}
cb->done = (void *)cb->args[3];
cb->args[1] = 3;
}
static int fib6_dump_done(struct netlink_callback *cb)
{
fib6_dump_end(cb);
return cb->done ? cb->done(cb) : 0;
}
static int fib6_dump_table(struct fib6_table *table, struct sk_buff *skb,
struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct fib6_walker *w;
int res;
w = (void *)cb->args[2];
w->root = &table->tb6_root;
if (cb->args[4] == 0) {
w->count = 0;
w->skip = 0;
w->skip_in_node = 0;
spin_lock_bh(&table->tb6_lock);
res = fib6_walk(net, w);
spin_unlock_bh(&table->tb6_lock);
if (res > 0) {
cb->args[4] = 1;
cb->args[5] = READ_ONCE(w->root->fn_sernum);
}
} else {
int sernum = READ_ONCE(w->root->fn_sernum);
if (cb->args[5] != sernum) {
/* Begin at the root if the tree changed */
cb->args[5] = sernum;
w->state = FWS_INIT;
w->node = w->root;
w->skip = w->count;
w->skip_in_node = 0;
} else
w->skip = 0;
spin_lock_bh(&table->tb6_lock);
res = fib6_walk_continue(w);
spin_unlock_bh(&table->tb6_lock);
if (res <= 0) {
fib6_walker_unlink(net, w);
cb->args[4] = 0;
}
}
return res;
}
static int inet6_dump_fib(struct sk_buff *skb, struct netlink_callback *cb)
{
struct rt6_rtnl_dump_arg arg = { .filter.dump_exceptions = true,
.filter.dump_routes = true };
const struct nlmsghdr *nlh = cb->nlh;
struct net *net = sock_net(skb->sk);
unsigned int h, s_h;
unsigned int e = 0, s_e;
struct fib6_walker *w;
struct fib6_table *tb;
struct hlist_head *head;
int res = 0;
if (cb->strict_check) {
int err;
err = ip_valid_fib_dump_req(net, nlh, &arg.filter, cb);
if (err < 0)
return err;
} else if (nlmsg_len(nlh) >= sizeof(struct rtmsg)) {
struct rtmsg *rtm = nlmsg_data(nlh);
if (rtm->rtm_flags & RTM_F_PREFIX)
arg.filter.flags = RTM_F_PREFIX;
}
w = (void *)cb->args[2];
if (!w) {
/* New dump:
*
* 1. hook callback destructor.
*/
cb->args[3] = (long)cb->done;
cb->done = fib6_dump_done;
/*
* 2. allocate and initialize walker.
*/
w = kzalloc(sizeof(*w), GFP_ATOMIC);
if (!w)
return -ENOMEM;
w->func = fib6_dump_node;
cb->args[2] = (long)w;
}
arg.skb = skb;
arg.cb = cb;
arg.net = net;
w->args = &arg;
if (arg.filter.table_id) {
tb = fib6_get_table(net, arg.filter.table_id);
if (!tb) {
if (rtnl_msg_family(cb->nlh) != PF_INET6)
goto out;
NL_SET_ERR_MSG_MOD(cb->extack, "FIB table does not exist");
return -ENOENT;
}
if (!cb->args[0]) {
res = fib6_dump_table(tb, skb, cb);
if (!res)
cb->args[0] = 1;
}
goto out;
}
s_h = cb->args[0];
s_e = cb->args[1];
rcu_read_lock();
for (h = s_h; h < FIB6_TABLE_HASHSZ; h++, s_e = 0) {
e = 0;
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
if (e < s_e)
goto next;
res = fib6_dump_table(tb, skb, cb);
if (res != 0)
goto out_unlock;
next:
e++;
}
}
out_unlock:
rcu_read_unlock();
cb->args[1] = e;
cb->args[0] = h;
out:
res = res < 0 ? res : skb->len;
if (res <= 0)
fib6_dump_end(cb);
return res;
}
void fib6_metric_set(struct fib6_info *f6i, int metric, u32 val)
{
if (!f6i)
return;
if (f6i->fib6_metrics == &dst_default_metrics) {
struct dst_metrics *p = kzalloc(sizeof(*p), GFP_ATOMIC);
if (!p)
return;
refcount_set(&p->refcnt, 1);
f6i->fib6_metrics = p;
}
f6i->fib6_metrics->metrics[metric - 1] = val;
}
/*
* Routing Table
*
* return the appropriate node for a routing tree "add" operation
* by either creating and inserting or by returning an existing
* node.
*/
static struct fib6_node *fib6_add_1(struct net *net,
struct fib6_table *table,
struct fib6_node *root,
struct in6_addr *addr, int plen,
int offset, int allow_create,
int replace_required,
struct netlink_ext_ack *extack)
{
struct fib6_node *fn, *in, *ln;
struct fib6_node *pn = NULL;
struct rt6key *key;
int bit;
__be32 dir = 0;
RT6_TRACE("fib6_add_1\n");
/* insert node in tree */
fn = root;
do {
struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&table->tb6_lock));
key = (struct rt6key *)((u8 *)leaf + offset);
/*
* Prefix match
*/
if (plen < fn->fn_bit ||
!ipv6_prefix_equal(&key->addr, addr, fn->fn_bit)) {
if (!allow_create) {
if (replace_required) {
NL_SET_ERR_MSG(extack,
"Can not replace route - no match found");
pr_warn("Can't replace route, no match found\n");
return ERR_PTR(-ENOENT);
}
pr_warn("NLM_F_CREATE should be set when creating new route\n");
}
goto insert_above;
}
/*
* Exact match ?
*/
if (plen == fn->fn_bit) {
/* clean up an intermediate node */
if (!(fn->fn_flags & RTN_RTINFO)) {
RCU_INIT_POINTER(fn->leaf, NULL);
fib6_info_release(leaf);
/* remove null_entry in the root node */
} else if (fn->fn_flags & RTN_TL_ROOT &&
rcu_access_pointer(fn->leaf) ==
net->ipv6.fib6_null_entry) {
RCU_INIT_POINTER(fn->leaf, NULL);
}
return fn;
}
/*
* We have more bits to go
*/
/* Try to walk down on tree. */
dir = addr_bit_set(addr, fn->fn_bit);
pn = fn;
fn = dir ?
rcu_dereference_protected(fn->right,
lockdep_is_held(&table->tb6_lock)) :
rcu_dereference_protected(fn->left,
lockdep_is_held(&table->tb6_lock));
} while (fn);
if (!allow_create) {
/* We should not create new node because
* NLM_F_REPLACE was specified without NLM_F_CREATE
* I assume it is safe to require NLM_F_CREATE when
* REPLACE flag is used! Later we may want to remove the
* check for replace_required, because according
* to netlink specification, NLM_F_CREATE
* MUST be specified if new route is created.
* That would keep IPv6 consistent with IPv4
*/
if (replace_required) {
NL_SET_ERR_MSG(extack,
"Can not replace route - no match found");
pr_warn("Can't replace route, no match found\n");
return ERR_PTR(-ENOENT);
}
pr_warn("NLM_F_CREATE should be set when creating new route\n");
}
/*
* We walked to the bottom of tree.
* Create new leaf node without children.
*/
ln = node_alloc(net);
if (!ln)
return ERR_PTR(-ENOMEM);
ln->fn_bit = plen;
RCU_INIT_POINTER(ln->parent, pn);
if (dir)
rcu_assign_pointer(pn->right, ln);
else
rcu_assign_pointer(pn->left, ln);
return ln;
insert_above:
/*
* split since we don't have a common prefix anymore or
* we have a less significant route.
* we've to insert an intermediate node on the list
* this new node will point to the one we need to create
* and the current
*/
pn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&table->tb6_lock));
/* find 1st bit in difference between the 2 addrs.
See comment in __ipv6_addr_diff: bit may be an invalid value,
but if it is >= plen, the value is ignored in any case.
*/
bit = __ipv6_addr_diff(addr, &key->addr, sizeof(*addr));
/*
* (intermediate)[in]
* / \
* (new leaf node)[ln] (old node)[fn]
*/
if (plen > bit) {
in = node_alloc(net);
ln = node_alloc(net);
if (!in || !ln) {
if (in)
node_free_immediate(net, in);
if (ln)
node_free_immediate(net, ln);
return ERR_PTR(-ENOMEM);
}
/*
* new intermediate node.
* RTN_RTINFO will
* be off since that an address that chooses one of
* the branches would not match less specific routes
* in the other branch
*/
in->fn_bit = bit;
RCU_INIT_POINTER(in->parent, pn);
in->leaf = fn->leaf;
fib6_info_hold(rcu_dereference_protected(in->leaf,
lockdep_is_held(&table->tb6_lock)));
/* update parent pointer */
if (dir)
rcu_assign_pointer(pn->right, in);
else
rcu_assign_pointer(pn->left, in);
ln->fn_bit = plen;
RCU_INIT_POINTER(ln->parent, in);
rcu_assign_pointer(fn->parent, in);
if (addr_bit_set(addr, bit)) {
rcu_assign_pointer(in->right, ln);
rcu_assign_pointer(in->left, fn);
} else {
rcu_assign_pointer(in->left, ln);
rcu_assign_pointer(in->right, fn);
}
} else { /* plen <= bit */
/*
* (new leaf node)[ln]
* / \
* (old node)[fn] NULL
*/
ln = node_alloc(net);
if (!ln)
return ERR_PTR(-ENOMEM);
ln->fn_bit = plen;
RCU_INIT_POINTER(ln->parent, pn);
if (addr_bit_set(&key->addr, plen))
RCU_INIT_POINTER(ln->right, fn);
else
RCU_INIT_POINTER(ln->left, fn);
rcu_assign_pointer(fn->parent, ln);
if (dir)
rcu_assign_pointer(pn->right, ln);
else
rcu_assign_pointer(pn->left, ln);
}
return ln;
}
static void __fib6_drop_pcpu_from(struct fib6_nh *fib6_nh,
const struct fib6_info *match,
const struct fib6_table *table)
{
int cpu;
if (!fib6_nh->rt6i_pcpu)
return;
/* release the reference to this fib entry from
* all of its cached pcpu routes
*/
for_each_possible_cpu(cpu) {
struct rt6_info **ppcpu_rt;
struct rt6_info *pcpu_rt;
ppcpu_rt = per_cpu_ptr(fib6_nh->rt6i_pcpu, cpu);
pcpu_rt = *ppcpu_rt;
/* only dropping the 'from' reference if the cached route
* is using 'match'. The cached pcpu_rt->from only changes
* from a fib6_info to NULL (ip6_dst_destroy); it can never
* change from one fib6_info reference to another
*/
if (pcpu_rt && rcu_access_pointer(pcpu_rt->from) == match) {
struct fib6_info *from;
from = xchg((__force struct fib6_info **)&pcpu_rt->from, NULL);
fib6_info_release(from);
}
}
}
struct fib6_nh_pcpu_arg {
struct fib6_info *from;
const struct fib6_table *table;
};
static int fib6_nh_drop_pcpu_from(struct fib6_nh *nh, void *_arg)
{
struct fib6_nh_pcpu_arg *arg = _arg;
__fib6_drop_pcpu_from(nh, arg->from, arg->table);
return 0;
}
static void fib6_drop_pcpu_from(struct fib6_info *f6i,
const struct fib6_table *table)
{
/* Make sure rt6_make_pcpu_route() wont add other percpu routes
* while we are cleaning them here.
*/
f6i->fib6_destroying = 1;
mb(); /* paired with the cmpxchg() in rt6_make_pcpu_route() */
if (f6i->nh) {
struct fib6_nh_pcpu_arg arg = {
.from = f6i,
.table = table
};
nexthop_for_each_fib6_nh(f6i->nh, fib6_nh_drop_pcpu_from,
&arg);
} else {
struct fib6_nh *fib6_nh;
fib6_nh = f6i->fib6_nh;
__fib6_drop_pcpu_from(fib6_nh, f6i, table);
}
}
static void fib6_purge_rt(struct fib6_info *rt, struct fib6_node *fn,
struct net *net)
{
struct fib6_table *table = rt->fib6_table;
/* Flush all cached dst in exception table */
rt6_flush_exceptions(rt);
fib6_drop_pcpu_from(rt, table);
if (rt->nh && !list_empty(&rt->nh_list))
list_del_init(&rt->nh_list);
if (refcount_read(&rt->fib6_ref) != 1) {
/* This route is used as dummy address holder in some split
* nodes. It is not leaked, but it still holds other resources,
* which must be released in time. So, scan ascendant nodes
* and replace dummy references to this route with references
* to still alive ones.
*/
while (fn) {
struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *new_leaf;
if (!(fn->fn_flags & RTN_RTINFO) && leaf == rt) {
new_leaf = fib6_find_prefix(net, table, fn);
fib6_info_hold(new_leaf);
rcu_assign_pointer(fn->leaf, new_leaf);
fib6_info_release(rt);
}
fn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&table->tb6_lock));
}
}
fib6_clean_expires_locked(rt);
}
/*
* Insert routing information in a node.
*/
static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt,
struct nl_info *info,
struct netlink_ext_ack *extack)
{
struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&rt->fib6_table->tb6_lock));
struct fib6_info *iter = NULL;
struct fib6_info __rcu **ins;
struct fib6_info __rcu **fallback_ins = NULL;
int replace = (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_REPLACE));
int add = (!info->nlh ||
(info->nlh->nlmsg_flags & NLM_F_CREATE));
int found = 0;
bool rt_can_ecmp = rt6_qualify_for_ecmp(rt);
bool notify_sibling_rt = false;
u16 nlflags = NLM_F_EXCL;
int err;
if (info->nlh && (info->nlh->nlmsg_flags & NLM_F_APPEND))
nlflags |= NLM_F_APPEND;
ins = &fn->leaf;
for (iter = leaf; iter;
iter = rcu_dereference_protected(iter->fib6_next,
lockdep_is_held(&rt->fib6_table->tb6_lock))) {
/*
* Search for duplicates
*/
if (iter->fib6_metric == rt->fib6_metric) {
/*
* Same priority level
*/
if (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_EXCL))
return -EEXIST;
nlflags &= ~NLM_F_EXCL;
if (replace) {
if (rt_can_ecmp == rt6_qualify_for_ecmp(iter)) {
found++;
break;
}
fallback_ins = fallback_ins ?: ins;
goto next_iter;
}
if (rt6_duplicate_nexthop(iter, rt)) {
if (rt->fib6_nsiblings)
rt->fib6_nsiblings = 0;
if (!(iter->fib6_flags & RTF_EXPIRES))
return -EEXIST;
if (!(rt->fib6_flags & RTF_EXPIRES))
fib6_clean_expires_locked(iter);
else
fib6_set_expires_locked(iter,
rt->expires);
if (rt->fib6_pmtu)
fib6_metric_set(iter, RTAX_MTU,
rt->fib6_pmtu);
return -EEXIST;
}
/* If we have the same destination and the same metric,
* but not the same gateway, then the route we try to
* add is sibling to this route, increment our counter
* of siblings, and later we will add our route to the
* list.
* Only static routes (which don't have flag
* RTF_EXPIRES) are used for ECMPv6.
*
* To avoid long list, we only had siblings if the
* route have a gateway.
*/
if (rt_can_ecmp &&
rt6_qualify_for_ecmp(iter))
rt->fib6_nsiblings++;
}
if (iter->fib6_metric > rt->fib6_metric)
break;
next_iter:
ins = &iter->fib6_next;
}
if (fallback_ins && !found) {
/* No matching route with same ecmp-able-ness found, replace
* first matching route
*/
ins = fallback_ins;
iter = rcu_dereference_protected(*ins,
lockdep_is_held(&rt->fib6_table->tb6_lock));
found++;
}
/* Reset round-robin state, if necessary */
if (ins == &fn->leaf)
fn->rr_ptr = NULL;
/* Link this route to others same route. */
if (rt->fib6_nsiblings) {
unsigned int fib6_nsiblings;
struct fib6_info *sibling, *temp_sibling;
/* Find the first route that have the same metric */
sibling = leaf;
notify_sibling_rt = true;
while (sibling) {
if (sibling->fib6_metric == rt->fib6_metric &&
rt6_qualify_for_ecmp(sibling)) {
list_add_tail(&rt->fib6_siblings,
&sibling->fib6_siblings);
break;
}
sibling = rcu_dereference_protected(sibling->fib6_next,
lockdep_is_held(&rt->fib6_table->tb6_lock));
notify_sibling_rt = false;
}
/* For each sibling in the list, increment the counter of
* siblings. BUG() if counters does not match, list of siblings
* is broken!
*/
fib6_nsiblings = 0;
list_for_each_entry_safe(sibling, temp_sibling,
&rt->fib6_siblings, fib6_siblings) {
sibling->fib6_nsiblings++;
BUG_ON(sibling->fib6_nsiblings != rt->fib6_nsiblings);
fib6_nsiblings++;
}
BUG_ON(fib6_nsiblings != rt->fib6_nsiblings);
rt6_multipath_rebalance(temp_sibling);
}
/*
* insert node
*/
if (!replace) {
if (!add)
pr_warn("NLM_F_CREATE should be set when creating new route\n");
add:
nlflags |= NLM_F_CREATE;
/* The route should only be notified if it is the first
* route in the node or if it is added as a sibling
* route to the first route in the node.
*/
if (!info->skip_notify_kernel &&
(notify_sibling_rt || ins == &fn->leaf)) {
enum fib_event_type fib_event;
if (notify_sibling_rt)
fib_event = FIB_EVENT_ENTRY_APPEND;
else
fib_event = FIB_EVENT_ENTRY_REPLACE;
err = call_fib6_entry_notifiers(info->nl_net,
fib_event, rt,
extack);
if (err) {
struct fib6_info *sibling, *next_sibling;
/* If the route has siblings, then it first
* needs to be unlinked from them.
*/
if (!rt->fib6_nsiblings)
return err;
list_for_each_entry_safe(sibling, next_sibling,
&rt->fib6_siblings,
fib6_siblings)
sibling->fib6_nsiblings--;
rt->fib6_nsiblings = 0;
list_del_init(&rt->fib6_siblings);
rt6_multipath_rebalance(next_sibling);
return err;
}
}
rcu_assign_pointer(rt->fib6_next, iter);
fib6_info_hold(rt);
rcu_assign_pointer(rt->fib6_node, fn);
rcu_assign_pointer(*ins, rt);
if (!info->skip_notify)
inet6_rt_notify(RTM_NEWROUTE, rt, info, nlflags);
info->nl_net->ipv6.rt6_stats->fib_rt_entries++;
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
} else {
int nsiblings;
if (!found) {
if (add)
goto add;
pr_warn("NLM_F_REPLACE set, but no existing node found!\n");
return -ENOENT;
}
if (!info->skip_notify_kernel && ins == &fn->leaf) {
err = call_fib6_entry_notifiers(info->nl_net,
FIB_EVENT_ENTRY_REPLACE,
rt, extack);
if (err)
return err;
}
fib6_info_hold(rt);
rcu_assign_pointer(rt->fib6_node, fn);
rt->fib6_next = iter->fib6_next;
rcu_assign_pointer(*ins, rt);
if (!info->skip_notify)
inet6_rt_notify(RTM_NEWROUTE, rt, info, NLM_F_REPLACE);
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
nsiblings = iter->fib6_nsiblings;
iter->fib6_node = NULL;
fib6_purge_rt(iter, fn, info->nl_net);
if (rcu_access_pointer(fn->rr_ptr) == iter)
fn->rr_ptr = NULL;
fib6_info_release(iter);
if (nsiblings) {
/* Replacing an ECMP route, remove all siblings */
ins = &rt->fib6_next;
iter = rcu_dereference_protected(*ins,
lockdep_is_held(&rt->fib6_table->tb6_lock));
while (iter) {
if (iter->fib6_metric > rt->fib6_metric)
break;
if (rt6_qualify_for_ecmp(iter)) {
*ins = iter->fib6_next;
iter->fib6_node = NULL;
fib6_purge_rt(iter, fn, info->nl_net);
if (rcu_access_pointer(fn->rr_ptr) == iter)
fn->rr_ptr = NULL;
fib6_info_release(iter);
nsiblings--;
info->nl_net->ipv6.rt6_stats->fib_rt_entries--;
} else {
ins = &iter->fib6_next;
}
iter = rcu_dereference_protected(*ins,
lockdep_is_held(&rt->fib6_table->tb6_lock));
}
WARN_ON(nsiblings != 0);
}
}
return 0;
}
static void fib6_start_gc(struct net *net, struct fib6_info *rt)
{
if (!timer_pending(&net->ipv6.ip6_fib_timer) &&
(rt->fib6_flags & RTF_EXPIRES))
mod_timer(&net->ipv6.ip6_fib_timer,
jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
}
void fib6_force_start_gc(struct net *net)
{
if (!timer_pending(&net->ipv6.ip6_fib_timer))
mod_timer(&net->ipv6.ip6_fib_timer,
jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
}
static void __fib6_update_sernum_upto_root(struct fib6_info *rt,
int sernum)
{
struct fib6_node *fn = rcu_dereference_protected(rt->fib6_node,
lockdep_is_held(&rt->fib6_table->tb6_lock));
/* paired with smp_rmb() in fib6_get_cookie_safe() */
smp_wmb();
while (fn) {
WRITE_ONCE(fn->fn_sernum, sernum);
fn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&rt->fib6_table->tb6_lock));
}
}
void fib6_update_sernum_upto_root(struct net *net, struct fib6_info *rt)
{
__fib6_update_sernum_upto_root(rt, fib6_new_sernum(net));
}
/* allow ipv4 to update sernum via ipv6_stub */
void fib6_update_sernum_stub(struct net *net, struct fib6_info *f6i)
{
spin_lock_bh(&f6i->fib6_table->tb6_lock);
fib6_update_sernum_upto_root(net, f6i);
spin_unlock_bh(&f6i->fib6_table->tb6_lock);
}
/*
* Add routing information to the routing tree.
* <destination addr>/<source addr>
* with source addr info in sub-trees
* Need to own table->tb6_lock
*/
int fib6_add(struct fib6_node *root, struct fib6_info *rt,
struct nl_info *info, struct netlink_ext_ack *extack)
{
struct fib6_table *table = rt->fib6_table;
struct fib6_node *fn, *pn = NULL;
int err = -ENOMEM;
int allow_create = 1;
int replace_required = 0;
if (info->nlh) {
if (!(info->nlh->nlmsg_flags & NLM_F_CREATE))
allow_create = 0;
if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
replace_required = 1;
}
if (!allow_create && !replace_required)
pr_warn("RTM_NEWROUTE with no NLM_F_CREATE or NLM_F_REPLACE\n");
fn = fib6_add_1(info->nl_net, table, root,
&rt->fib6_dst.addr, rt->fib6_dst.plen,
offsetof(struct fib6_info, fib6_dst), allow_create,
replace_required, extack);
if (IS_ERR(fn)) {
err = PTR_ERR(fn);
fn = NULL;
goto out;
}
pn = fn;
#ifdef CONFIG_IPV6_SUBTREES
if (rt->fib6_src.plen) {
struct fib6_node *sn;
if (!rcu_access_pointer(fn->subtree)) {
struct fib6_node *sfn;
/*
* Create subtree.
*
* fn[main tree]
* |
* sfn[subtree root]
* \
* sn[new leaf node]
*/
/* Create subtree root node */
sfn = node_alloc(info->nl_net);
if (!sfn)
goto failure;
fib6_info_hold(info->nl_net->ipv6.fib6_null_entry);
rcu_assign_pointer(sfn->leaf,
info->nl_net->ipv6.fib6_null_entry);
sfn->fn_flags = RTN_ROOT;
/* Now add the first leaf node to new subtree */
sn = fib6_add_1(info->nl_net, table, sfn,
&rt->fib6_src.addr, rt->fib6_src.plen,
offsetof(struct fib6_info, fib6_src),
allow_create, replace_required, extack);
if (IS_ERR(sn)) {
/* If it is failed, discard just allocated
root, and then (in failure) stale node
in main tree.
*/
node_free_immediate(info->nl_net, sfn);
err = PTR_ERR(sn);
goto failure;
}
/* Now link new subtree to main tree */
rcu_assign_pointer(sfn->parent, fn);
rcu_assign_pointer(fn->subtree, sfn);
} else {
sn = fib6_add_1(info->nl_net, table, FIB6_SUBTREE(fn),
&rt->fib6_src.addr, rt->fib6_src.plen,
offsetof(struct fib6_info, fib6_src),
allow_create, replace_required, extack);
if (IS_ERR(sn)) {
err = PTR_ERR(sn);
goto failure;
}
}
if (!rcu_access_pointer(fn->leaf)) {
if (fn->fn_flags & RTN_TL_ROOT) {
/* put back null_entry for root node */
rcu_assign_pointer(fn->leaf,
info->nl_net->ipv6.fib6_null_entry);
} else {
fib6_info_hold(rt);
rcu_assign_pointer(fn->leaf, rt);
}
}
fn = sn;
}
#endif
err = fib6_add_rt2node(fn, rt, info, extack);
if (!err) {
if (rt->nh)
list_add(&rt->nh_list, &rt->nh->f6i_list);
__fib6_update_sernum_upto_root(rt, fib6_new_sernum(info->nl_net));
if (fib6_has_expires(rt))
hlist_add_head(&rt->gc_link, &table->tb6_gc_hlist);
fib6_start_gc(info->nl_net, rt);
}
out:
if (err) {
#ifdef CONFIG_IPV6_SUBTREES
/*
* If fib6_add_1 has cleared the old leaf pointer in the
* super-tree leaf node we have to find a new one for it.
*/
if (pn != fn) {
struct fib6_info *pn_leaf =
rcu_dereference_protected(pn->leaf,
lockdep_is_held(&table->tb6_lock));
if (pn_leaf == rt) {
pn_leaf = NULL;
RCU_INIT_POINTER(pn->leaf, NULL);
fib6_info_release(rt);
}
if (!pn_leaf && !(pn->fn_flags & RTN_RTINFO)) {
pn_leaf = fib6_find_prefix(info->nl_net, table,
pn);
#if RT6_DEBUG >= 2
if (!pn_leaf) {
WARN_ON(!pn_leaf);
pn_leaf =
info->nl_net->ipv6.fib6_null_entry;
}
#endif
fib6_info_hold(pn_leaf);
rcu_assign_pointer(pn->leaf, pn_leaf);
}
}
#endif
goto failure;
} else if (fib6_requires_src(rt)) {
fib6_routes_require_src_inc(info->nl_net);
}
return err;
failure:
/* fn->leaf could be NULL and fib6_repair_tree() needs to be called if:
* 1. fn is an intermediate node and we failed to add the new
* route to it in both subtree creation failure and fib6_add_rt2node()
* failure case.
* 2. fn is the root node in the table and we fail to add the first
* default route to it.
*/
if (fn &&
(!(fn->fn_flags & (RTN_RTINFO|RTN_ROOT)) ||
(fn->fn_flags & RTN_TL_ROOT &&
!rcu_access_pointer(fn->leaf))))
fib6_repair_tree(info->nl_net, table, fn);
return err;
}
/*
* Routing tree lookup
*
*/
struct lookup_args {
int offset; /* key offset on fib6_info */
const struct in6_addr *addr; /* search key */
};
static struct fib6_node *fib6_node_lookup_1(struct fib6_node *root,
struct lookup_args *args)
{
struct fib6_node *fn;
__be32 dir;
if (unlikely(args->offset == 0))
return NULL;
/*
* Descend on a tree
*/
fn = root;
for (;;) {
struct fib6_node *next;
dir = addr_bit_set(args->addr, fn->fn_bit);
next = dir ? rcu_dereference(fn->right) :
rcu_dereference(fn->left);
if (next) {
fn = next;
continue;
}
break;
}
while (fn) {
struct fib6_node *subtree = FIB6_SUBTREE(fn);
if (subtree || fn->fn_flags & RTN_RTINFO) {
struct fib6_info *leaf = rcu_dereference(fn->leaf);
struct rt6key *key;
if (!leaf)
goto backtrack;
key = (struct rt6key *) ((u8 *)leaf + args->offset);
if (ipv6_prefix_equal(&key->addr, args->addr, key->plen)) {
#ifdef CONFIG_IPV6_SUBTREES
if (subtree) {
struct fib6_node *sfn;
sfn = fib6_node_lookup_1(subtree,
args + 1);
if (!sfn)
goto backtrack;
fn = sfn;
}
#endif
if (fn->fn_flags & RTN_RTINFO)
return fn;
}
}
backtrack:
if (fn->fn_flags & RTN_ROOT)
break;
fn = rcu_dereference(fn->parent);
}
return NULL;
}
/* called with rcu_read_lock() held
*/
struct fib6_node *fib6_node_lookup(struct fib6_node *root,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
struct fib6_node *fn;
struct lookup_args args[] = {
{
.offset = offsetof(struct fib6_info, fib6_dst),
.addr = daddr,
},
#ifdef CONFIG_IPV6_SUBTREES
{
.offset = offsetof(struct fib6_info, fib6_src),
.addr = saddr,
},
#endif
{
.offset = 0, /* sentinel */
}
};
fn = fib6_node_lookup_1(root, daddr ? args : args + 1);
if (!fn || fn->fn_flags & RTN_TL_ROOT)
fn = root;
return fn;
}
/*
* Get node with specified destination prefix (and source prefix,
* if subtrees are used)
* exact_match == true means we try to find fn with exact match of
* the passed in prefix addr
* exact_match == false means we try to find fn with longest prefix
* match of the passed in prefix addr. This is useful for finding fn
* for cached route as it will be stored in the exception table under
* the node with longest prefix length.
*/
static struct fib6_node *fib6_locate_1(struct fib6_node *root,
const struct in6_addr *addr,
int plen, int offset,
bool exact_match)
{
struct fib6_node *fn, *prev = NULL;
for (fn = root; fn ; ) {
struct fib6_info *leaf = rcu_dereference(fn->leaf);
struct rt6key *key;
/* This node is being deleted */
if (!leaf) {
if (plen <= fn->fn_bit)
goto out;
else
goto next;
}
key = (struct rt6key *)((u8 *)leaf + offset);
/*
* Prefix match
*/
if (plen < fn->fn_bit ||
!ipv6_prefix_equal(&key->addr, addr, fn->fn_bit))
goto out;
if (plen == fn->fn_bit)
return fn;
if (fn->fn_flags & RTN_RTINFO)
prev = fn;
next:
/*
* We have more bits to go
*/
if (addr_bit_set(addr, fn->fn_bit))
fn = rcu_dereference(fn->right);
else
fn = rcu_dereference(fn->left);
}
out:
if (exact_match)
return NULL;
else
return prev;
}
struct fib6_node *fib6_locate(struct fib6_node *root,
const struct in6_addr *daddr, int dst_len,
const struct in6_addr *saddr, int src_len,
bool exact_match)
{
struct fib6_node *fn;
fn = fib6_locate_1(root, daddr, dst_len,
offsetof(struct fib6_info, fib6_dst),
exact_match);
#ifdef CONFIG_IPV6_SUBTREES
if (src_len) {
WARN_ON(saddr == NULL);
if (fn) {
struct fib6_node *subtree = FIB6_SUBTREE(fn);
if (subtree) {
fn = fib6_locate_1(subtree, saddr, src_len,
offsetof(struct fib6_info, fib6_src),
exact_match);
}
}
}
#endif
if (fn && fn->fn_flags & RTN_RTINFO)
return fn;
return NULL;
}
/*
* Deletion
*
*/
static struct fib6_info *fib6_find_prefix(struct net *net,
struct fib6_table *table,
struct fib6_node *fn)
{
struct fib6_node *child_left, *child_right;
if (fn->fn_flags & RTN_ROOT)
return net->ipv6.fib6_null_entry;
while (fn) {
child_left = rcu_dereference_protected(fn->left,
lockdep_is_held(&table->tb6_lock));
child_right = rcu_dereference_protected(fn->right,
lockdep_is_held(&table->tb6_lock));
if (child_left)
return rcu_dereference_protected(child_left->leaf,
lockdep_is_held(&table->tb6_lock));
if (child_right)
return rcu_dereference_protected(child_right->leaf,
lockdep_is_held(&table->tb6_lock));
fn = FIB6_SUBTREE(fn);
}
return NULL;
}
/*
* Called to trim the tree of intermediate nodes when possible. "fn"
* is the node we want to try and remove.
* Need to own table->tb6_lock
*/
static struct fib6_node *fib6_repair_tree(struct net *net,
struct fib6_table *table,
struct fib6_node *fn)
{
int children;
int nstate;
struct fib6_node *child;
struct fib6_walker *w;
int iter = 0;
/* Set fn->leaf to null_entry for root node. */
if (fn->fn_flags & RTN_TL_ROOT) {
rcu_assign_pointer(fn->leaf, net->ipv6.fib6_null_entry);
return fn;
}
for (;;) {
struct fib6_node *fn_r = rcu_dereference_protected(fn->right,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *fn_l = rcu_dereference_protected(fn->left,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *pn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *pn_r = rcu_dereference_protected(pn->right,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *pn_l = rcu_dereference_protected(pn->left,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *fn_leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *pn_leaf = rcu_dereference_protected(pn->leaf,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *new_fn_leaf;
RT6_TRACE("fixing tree: plen=%d iter=%d\n", fn->fn_bit, iter);
iter++;
WARN_ON(fn->fn_flags & RTN_RTINFO);
WARN_ON(fn->fn_flags & RTN_TL_ROOT);
WARN_ON(fn_leaf);
children = 0;
child = NULL;
if (fn_r) {
child = fn_r;
children |= 1;
}
if (fn_l) {
child = fn_l;
children |= 2;
}
if (children == 3 || FIB6_SUBTREE(fn)
#ifdef CONFIG_IPV6_SUBTREES
/* Subtree root (i.e. fn) may have one child */
|| (children && fn->fn_flags & RTN_ROOT)
#endif
) {
new_fn_leaf = fib6_find_prefix(net, table, fn);
#if RT6_DEBUG >= 2
if (!new_fn_leaf) {
WARN_ON(!new_fn_leaf);
new_fn_leaf = net->ipv6.fib6_null_entry;
}
#endif
fib6_info_hold(new_fn_leaf);
rcu_assign_pointer(fn->leaf, new_fn_leaf);
return pn;
}
#ifdef CONFIG_IPV6_SUBTREES
if (FIB6_SUBTREE(pn) == fn) {
WARN_ON(!(fn->fn_flags & RTN_ROOT));
RCU_INIT_POINTER(pn->subtree, NULL);
nstate = FWS_L;
} else {
WARN_ON(fn->fn_flags & RTN_ROOT);
#endif
if (pn_r == fn)
rcu_assign_pointer(pn->right, child);
else if (pn_l == fn)
rcu_assign_pointer(pn->left, child);
#if RT6_DEBUG >= 2
else
WARN_ON(1);
#endif
if (child)
rcu_assign_pointer(child->parent, pn);
nstate = FWS_R;
#ifdef CONFIG_IPV6_SUBTREES
}
#endif
read_lock(&net->ipv6.fib6_walker_lock);
FOR_WALKERS(net, w) {
if (!child) {
if (w->node == fn) {
RT6_TRACE("W %p adjusted by delnode 1, s=%d/%d\n", w, w->state, nstate);
w->node = pn;
w->state = nstate;
}
} else {
if (w->node == fn) {
w->node = child;
if (children&2) {
RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
w->state = w->state >= FWS_R ? FWS_U : FWS_INIT;
} else {
RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
w->state = w->state >= FWS_C ? FWS_U : FWS_INIT;
}
}
}
}
read_unlock(&net->ipv6.fib6_walker_lock);
node_free(net, fn);
if (pn->fn_flags & RTN_RTINFO || FIB6_SUBTREE(pn))
return pn;
RCU_INIT_POINTER(pn->leaf, NULL);
fib6_info_release(pn_leaf);
fn = pn;
}
}
static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn,
struct fib6_info __rcu **rtp, struct nl_info *info)
{
struct fib6_info *leaf, *replace_rt = NULL;
struct fib6_walker *w;
struct fib6_info *rt = rcu_dereference_protected(*rtp,
lockdep_is_held(&table->tb6_lock));
struct net *net = info->nl_net;
bool notify_del = false;
RT6_TRACE("fib6_del_route\n");
/* If the deleted route is the first in the node and it is not part of
* a multipath route, then we need to replace it with the next route
* in the node, if exists.
*/
leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&table->tb6_lock));
if (leaf == rt && !rt->fib6_nsiblings) {
if (rcu_access_pointer(rt->fib6_next))
replace_rt = rcu_dereference_protected(rt->fib6_next,
lockdep_is_held(&table->tb6_lock));
else
notify_del = true;
}
/* Unlink it */
*rtp = rt->fib6_next;
rt->fib6_node = NULL;
net->ipv6.rt6_stats->fib_rt_entries--;
net->ipv6.rt6_stats->fib_discarded_routes++;
/* Reset round-robin state, if necessary */
if (rcu_access_pointer(fn->rr_ptr) == rt)
fn->rr_ptr = NULL;
/* Remove this entry from other siblings */
if (rt->fib6_nsiblings) {
struct fib6_info *sibling, *next_sibling;
/* The route is deleted from a multipath route. If this
* multipath route is the first route in the node, then we need
* to emit a delete notification. Otherwise, we need to skip
* the notification.
*/
if (rt->fib6_metric == leaf->fib6_metric &&
rt6_qualify_for_ecmp(leaf))
notify_del = true;
list_for_each_entry_safe(sibling, next_sibling,
&rt->fib6_siblings, fib6_siblings)
sibling->fib6_nsiblings--;
rt->fib6_nsiblings = 0;
list_del_init(&rt->fib6_siblings);
rt6_multipath_rebalance(next_sibling);
}
/* Adjust walkers */
read_lock(&net->ipv6.fib6_walker_lock);
FOR_WALKERS(net, w) {
if (w->state == FWS_C && w->leaf == rt) {
RT6_TRACE("walker %p adjusted by delroute\n", w);
w->leaf = rcu_dereference_protected(rt->fib6_next,
lockdep_is_held(&table->tb6_lock));
if (!w->leaf)
w->state = FWS_U;
}
}
read_unlock(&net->ipv6.fib6_walker_lock);
/* If it was last route, call fib6_repair_tree() to:
* 1. For root node, put back null_entry as how the table was created.
* 2. For other nodes, expunge its radix tree node.
*/
if (!rcu_access_pointer(fn->leaf)) {
if (!(fn->fn_flags & RTN_TL_ROOT)) {
fn->fn_flags &= ~RTN_RTINFO;
net->ipv6.rt6_stats->fib_route_nodes--;
}
fn = fib6_repair_tree(net, table, fn);
}
fib6_purge_rt(rt, fn, net);
if (!info->skip_notify_kernel) {
if (notify_del)
call_fib6_entry_notifiers(net, FIB_EVENT_ENTRY_DEL,
rt, NULL);
else if (replace_rt)
call_fib6_entry_notifiers_replace(net, replace_rt);
}
if (!info->skip_notify)
inet6_rt_notify(RTM_DELROUTE, rt, info, 0);
fib6_info_release(rt);
}
/* Need to own table->tb6_lock */
int fib6_del(struct fib6_info *rt, struct nl_info *info)
{
struct net *net = info->nl_net;
struct fib6_info __rcu **rtp;
struct fib6_info __rcu **rtp_next;
struct fib6_table *table;
struct fib6_node *fn;
if (rt == net->ipv6.fib6_null_entry)
return -ENOENT;
table = rt->fib6_table;
fn = rcu_dereference_protected(rt->fib6_node,
lockdep_is_held(&table->tb6_lock));
if (!fn)
return -ENOENT;
WARN_ON(!(fn->fn_flags & RTN_RTINFO));
/*
* Walk the leaf entries looking for ourself
*/
for (rtp = &fn->leaf; *rtp; rtp = rtp_next) {
struct fib6_info *cur = rcu_dereference_protected(*rtp,
lockdep_is_held(&table->tb6_lock));
if (rt == cur) {
if (fib6_requires_src(cur))
fib6_routes_require_src_dec(info->nl_net);
fib6_del_route(table, fn, rtp, info);
return 0;
}
rtp_next = &cur->fib6_next;
}
return -ENOENT;
}
/*
* Tree traversal function.
*
* Certainly, it is not interrupt safe.
* However, it is internally reenterable wrt itself and fib6_add/fib6_del.
* It means, that we can modify tree during walking
* and use this function for garbage collection, clone pruning,
* cleaning tree when a device goes down etc. etc.
*
* It guarantees that every node will be traversed,
* and that it will be traversed only once.
*
* Callback function w->func may return:
* 0 -> continue walking.
* positive value -> walking is suspended (used by tree dumps,
* and probably by gc, if it will be split to several slices)
* negative value -> terminate walking.
*
* The function itself returns:
* 0 -> walk is complete.
* >0 -> walk is incomplete (i.e. suspended)
* <0 -> walk is terminated by an error.
*
* This function is called with tb6_lock held.
*/
static int fib6_walk_continue(struct fib6_walker *w)
{
struct fib6_node *fn, *pn, *left, *right;
/* w->root should always be table->tb6_root */
WARN_ON_ONCE(!(w->root->fn_flags & RTN_TL_ROOT));
for (;;) {
fn = w->node;
if (!fn)
return 0;
switch (w->state) {
#ifdef CONFIG_IPV6_SUBTREES
case FWS_S:
if (FIB6_SUBTREE(fn)) {
w->node = FIB6_SUBTREE(fn);
continue;
}
w->state = FWS_L;
fallthrough;
#endif
case FWS_L:
left = rcu_dereference_protected(fn->left, 1);
if (left) {
w->node = left;
w->state = FWS_INIT;
continue;
}
w->state = FWS_R;
fallthrough;
case FWS_R:
right = rcu_dereference_protected(fn->right, 1);
if (right) {
w->node = right;
w->state = FWS_INIT;
continue;
}
w->state = FWS_C;
w->leaf = rcu_dereference_protected(fn->leaf, 1);
fallthrough;
case FWS_C:
if (w->leaf && fn->fn_flags & RTN_RTINFO) {
int err;
if (w->skip) {
w->skip--;
goto skip;
}
err = w->func(w);
if (err)
return err;
w->count++;
continue;
}
skip:
w->state = FWS_U;
fallthrough;
case FWS_U:
if (fn == w->root)
return 0;
pn = rcu_dereference_protected(fn->parent, 1);
left = rcu_dereference_protected(pn->left, 1);
right = rcu_dereference_protected(pn->right, 1);
w->node = pn;
#ifdef CONFIG_IPV6_SUBTREES
if (FIB6_SUBTREE(pn) == fn) {
WARN_ON(!(fn->fn_flags & RTN_ROOT));
w->state = FWS_L;
continue;
}
#endif
if (left == fn) {
w->state = FWS_R;
continue;
}
if (right == fn) {
w->state = FWS_C;
w->leaf = rcu_dereference_protected(w->node->leaf, 1);
continue;
}
#if RT6_DEBUG >= 2
WARN_ON(1);
#endif
}
}
}
static int fib6_walk(struct net *net, struct fib6_walker *w)
{
int res;
w->state = FWS_INIT;
w->node = w->root;
fib6_walker_link(net, w);
res = fib6_walk_continue(w);
if (res <= 0)
fib6_walker_unlink(net, w);
return res;
}
static int fib6_clean_node(struct fib6_walker *w)
{
int res;
struct fib6_info *rt;
struct fib6_cleaner *c = container_of(w, struct fib6_cleaner, w);
struct nl_info info = {
.nl_net = c->net,
.skip_notify = c->skip_notify,
};
if (c->sernum != FIB6_NO_SERNUM_CHANGE &&
READ_ONCE(w->node->fn_sernum) != c->sernum)
WRITE_ONCE(w->node->fn_sernum, c->sernum);
if (!c->func) {
WARN_ON_ONCE(c->sernum == FIB6_NO_SERNUM_CHANGE);
w->leaf = NULL;
return 0;
}
for_each_fib6_walker_rt(w) {
res = c->func(rt, c->arg);
if (res == -1) {
w->leaf = rt;
res = fib6_del(rt, &info);
if (res) {
#if RT6_DEBUG >= 2
pr_debug("%s: del failed: rt=%p@%p err=%d\n",
__func__, rt,
rcu_access_pointer(rt->fib6_node),
res);
#endif
continue;
}
return 0;
} else if (res == -2) {
if (WARN_ON(!rt->fib6_nsiblings))
continue;
rt = list_last_entry(&rt->fib6_siblings,
struct fib6_info, fib6_siblings);
continue;
}
WARN_ON(res != 0);
}
w->leaf = rt;
return 0;
}
/*
* Convenient frontend to tree walker.
*
* func is called on each route.
* It may return -2 -> skip multipath route.
* -1 -> delete this route.
* 0 -> continue walking
*/
static void fib6_clean_tree(struct net *net, struct fib6_node *root,
int (*func)(struct fib6_info *, void *arg),
int sernum, void *arg, bool skip_notify)
{
struct fib6_cleaner c;
c.w.root = root;
c.w.func = fib6_clean_node;
c.w.count = 0;
c.w.skip = 0;
c.w.skip_in_node = 0;
c.func = func;
c.sernum = sernum;
c.arg = arg;
c.net = net;
c.skip_notify = skip_notify;
fib6_walk(net, &c.w);
}
static void __fib6_clean_all(struct net *net,
int (*func)(struct fib6_info *, void *),
int sernum, void *arg, bool skip_notify)
{
struct fib6_table *table;
struct hlist_head *head;
unsigned int h;
rcu_read_lock();
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(table, head, tb6_hlist) {
spin_lock_bh(&table->tb6_lock);
fib6_clean_tree(net, &table->tb6_root,
func, sernum, arg, skip_notify);
spin_unlock_bh(&table->tb6_lock);
}
}
rcu_read_unlock();
}
void fib6_clean_all(struct net *net, int (*func)(struct fib6_info *, void *),
void *arg)
{
__fib6_clean_all(net, func, FIB6_NO_SERNUM_CHANGE, arg, false);
}
void fib6_clean_all_skip_notify(struct net *net,
int (*func)(struct fib6_info *, void *),
void *arg)
{
__fib6_clean_all(net, func, FIB6_NO_SERNUM_CHANGE, arg, true);
}
static void fib6_flush_trees(struct net *net)
{
int new_sernum = fib6_new_sernum(net);
__fib6_clean_all(net, NULL, new_sernum, NULL, false);
}
/*
* Garbage collection
*/
static int fib6_age(struct fib6_info *rt, struct fib6_gc_args *gc_args)
{
unsigned long now = jiffies;
/*
* check addrconf expiration here.
* Routes are expired even if they are in use.
*/
if (fib6_has_expires(rt) && rt->expires) {
if (time_after(now, rt->expires)) {
RT6_TRACE("expiring %p\n", rt);
return -1;
}
gc_args->more++;
}
/* Also age clones in the exception table.
* Note, that clones are aged out
* only if they are not in use now.
*/
rt6_age_exceptions(rt, gc_args, now);
return 0;
}
static void fib6_gc_table(struct net *net,
struct fib6_table *tb6,
struct fib6_gc_args *gc_args)
{
struct fib6_info *rt;
struct hlist_node *n;
struct nl_info info = {
.nl_net = net,
.skip_notify = false,
};
hlist_for_each_entry_safe(rt, n, &tb6->tb6_gc_hlist, gc_link)
if (fib6_age(rt, gc_args) == -1)
fib6_del(rt, &info);
}
static void fib6_gc_all(struct net *net, struct fib6_gc_args *gc_args)
{
struct fib6_table *table;
struct hlist_head *head;
unsigned int h;
rcu_read_lock();
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(table, head, tb6_hlist) {
spin_lock_bh(&table->tb6_lock);
fib6_gc_table(net, table, gc_args);
spin_unlock_bh(&table->tb6_lock);
}
}
rcu_read_unlock();
}
void fib6_run_gc(unsigned long expires, struct net *net, bool force)
{
struct fib6_gc_args gc_args;
unsigned long now;
if (force) {
spin_lock_bh(&net->ipv6.fib6_gc_lock);
} else if (!spin_trylock_bh(&net->ipv6.fib6_gc_lock)) {
mod_timer(&net->ipv6.ip6_fib_timer, jiffies + HZ);
return;
}
gc_args.timeout = expires ? (int)expires :
net->ipv6.sysctl.ip6_rt_gc_interval;
gc_args.more = 0;
fib6_gc_all(net, &gc_args);
now = jiffies;
net->ipv6.ip6_rt_last_gc = now;
if (gc_args.more)
mod_timer(&net->ipv6.ip6_fib_timer,
round_jiffies(now
+ net->ipv6.sysctl.ip6_rt_gc_interval));
else
del_timer(&net->ipv6.ip6_fib_timer);
spin_unlock_bh(&net->ipv6.fib6_gc_lock);
}
static void fib6_gc_timer_cb(struct timer_list *t)
{
struct net *arg = from_timer(arg, t, ipv6.ip6_fib_timer);
fib6_run_gc(0, arg, true);
}
static int __net_init fib6_net_init(struct net *net)
{
size_t size = sizeof(struct hlist_head) * FIB6_TABLE_HASHSZ;
int err;
err = fib6_notifier_init(net);
if (err)
return err;
/* Default to 3-tuple */
net->ipv6.sysctl.multipath_hash_fields =
FIB_MULTIPATH_HASH_FIELD_DEFAULT_MASK;
spin_lock_init(&net->ipv6.fib6_gc_lock);
rwlock_init(&net->ipv6.fib6_walker_lock);
INIT_LIST_HEAD(&net->ipv6.fib6_walkers);
timer_setup(&net->ipv6.ip6_fib_timer, fib6_gc_timer_cb, 0);
net->ipv6.rt6_stats = kzalloc(sizeof(*net->ipv6.rt6_stats), GFP_KERNEL);
if (!net->ipv6.rt6_stats)
goto out_notifier;
/* Avoid false sharing : Use at least a full cache line */
size = max_t(size_t, size, L1_CACHE_BYTES);
net->ipv6.fib_table_hash = kzalloc(size, GFP_KERNEL);
if (!net->ipv6.fib_table_hash)
goto out_rt6_stats;
net->ipv6.fib6_main_tbl = kzalloc(sizeof(*net->ipv6.fib6_main_tbl),
GFP_KERNEL);
if (!net->ipv6.fib6_main_tbl)
goto out_fib_table_hash;
net->ipv6.fib6_main_tbl->tb6_id = RT6_TABLE_MAIN;
rcu_assign_pointer(net->ipv6.fib6_main_tbl->tb6_root.leaf,
net->ipv6.fib6_null_entry);
net->ipv6.fib6_main_tbl->tb6_root.fn_flags =
RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
inet_peer_base_init(&net->ipv6.fib6_main_tbl->tb6_peers);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
net->ipv6.fib6_local_tbl = kzalloc(sizeof(*net->ipv6.fib6_local_tbl),
GFP_KERNEL);
if (!net->ipv6.fib6_local_tbl)
goto out_fib6_main_tbl;
net->ipv6.fib6_local_tbl->tb6_id = RT6_TABLE_LOCAL;
rcu_assign_pointer(net->ipv6.fib6_local_tbl->tb6_root.leaf,
net->ipv6.fib6_null_entry);
net->ipv6.fib6_local_tbl->tb6_root.fn_flags =
RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
inet_peer_base_init(&net->ipv6.fib6_local_tbl->tb6_peers);
#endif
fib6_tables_init(net);
return 0;
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
out_fib6_main_tbl:
kfree(net->ipv6.fib6_main_tbl);
#endif
out_fib_table_hash:
kfree(net->ipv6.fib_table_hash);
out_rt6_stats:
kfree(net->ipv6.rt6_stats);
out_notifier:
fib6_notifier_exit(net);
return -ENOMEM;
}
static void fib6_net_exit(struct net *net)
{
unsigned int i;
del_timer_sync(&net->ipv6.ip6_fib_timer);
for (i = 0; i < FIB6_TABLE_HASHSZ; i++) {
struct hlist_head *head = &net->ipv6.fib_table_hash[i];
struct hlist_node *tmp;
struct fib6_table *tb;
hlist_for_each_entry_safe(tb, tmp, head, tb6_hlist) {
hlist_del(&tb->tb6_hlist);
fib6_free_table(tb);
}
}
kfree(net->ipv6.fib_table_hash);
kfree(net->ipv6.rt6_stats);
fib6_notifier_exit(net);
}
static struct pernet_operations fib6_net_ops = {
.init = fib6_net_init,
.exit = fib6_net_exit,
};
int __init fib6_init(void)
{
int ret = -ENOMEM;
fib6_node_kmem = kmem_cache_create("fib6_nodes",
sizeof(struct fib6_node), 0,
SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT,
NULL);
if (!fib6_node_kmem)
goto out;
ret = register_pernet_subsys(&fib6_net_ops);
if (ret)
goto out_kmem_cache_create;
ret = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETROUTE, NULL,
inet6_dump_fib, 0);
if (ret)
goto out_unregister_subsys;
__fib6_flush_trees = fib6_flush_trees;
out:
return ret;
out_unregister_subsys:
unregister_pernet_subsys(&fib6_net_ops);
out_kmem_cache_create:
kmem_cache_destroy(fib6_node_kmem);
goto out;
}
void fib6_gc_cleanup(void)
{
unregister_pernet_subsys(&fib6_net_ops);
kmem_cache_destroy(fib6_node_kmem);
}
#ifdef CONFIG_PROC_FS
static int ipv6_route_native_seq_show(struct seq_file *seq, void *v)
{
struct fib6_info *rt = v;
struct ipv6_route_iter *iter = seq->private;
struct fib6_nh *fib6_nh = rt->fib6_nh;
unsigned int flags = rt->fib6_flags;
const struct net_device *dev;
if (rt->nh)
fib6_nh = nexthop_fib6_nh(rt->nh);
seq_printf(seq, "%pi6 %02x ", &rt->fib6_dst.addr, rt->fib6_dst.plen);
#ifdef CONFIG_IPV6_SUBTREES
seq_printf(seq, "%pi6 %02x ", &rt->fib6_src.addr, rt->fib6_src.plen);
#else
seq_puts(seq, "00000000000000000000000000000000 00 ");
#endif
if (fib6_nh->fib_nh_gw_family) {
flags |= RTF_GATEWAY;
seq_printf(seq, "%pi6", &fib6_nh->fib_nh_gw6);
} else {
seq_puts(seq, "00000000000000000000000000000000");
}
dev = fib6_nh->fib_nh_dev;
seq_printf(seq, " %08x %08x %08x %08x %8s\n",
rt->fib6_metric, refcount_read(&rt->fib6_ref), 0,
flags, dev ? dev->name : "");
iter->w.leaf = NULL;
return 0;
}
static int ipv6_route_yield(struct fib6_walker *w)
{
struct ipv6_route_iter *iter = w->args;
if (!iter->skip)
return 1;
do {
iter->w.leaf = rcu_dereference_protected(
iter->w.leaf->fib6_next,
lockdep_is_held(&iter->tbl->tb6_lock));
iter->skip--;
if (!iter->skip && iter->w.leaf)
return 1;
} while (iter->w.leaf);
return 0;
}
static void ipv6_route_seq_setup_walk(struct ipv6_route_iter *iter,
struct net *net)
{
memset(&iter->w, 0, sizeof(iter->w));
iter->w.func = ipv6_route_yield;
iter->w.root = &iter->tbl->tb6_root;
iter->w.state = FWS_INIT;
iter->w.node = iter->w.root;
iter->w.args = iter;
iter->sernum = READ_ONCE(iter->w.root->fn_sernum);
INIT_LIST_HEAD(&iter->w.lh);
fib6_walker_link(net, &iter->w);
}
static struct fib6_table *ipv6_route_seq_next_table(struct fib6_table *tbl,
struct net *net)
{
unsigned int h;
struct hlist_node *node;
if (tbl) {
h = (tbl->tb6_id & (FIB6_TABLE_HASHSZ - 1)) + 1;
node = rcu_dereference(hlist_next_rcu(&tbl->tb6_hlist));
} else {
h = 0;
node = NULL;
}
while (!node && h < FIB6_TABLE_HASHSZ) {
node = rcu_dereference(
hlist_first_rcu(&net->ipv6.fib_table_hash[h++]));
}
return hlist_entry_safe(node, struct fib6_table, tb6_hlist);
}
static void ipv6_route_check_sernum(struct ipv6_route_iter *iter)
{
int sernum = READ_ONCE(iter->w.root->fn_sernum);
if (iter->sernum != sernum) {
iter->sernum = sernum;
iter->w.state = FWS_INIT;
iter->w.node = iter->w.root;
WARN_ON(iter->w.skip);
iter->w.skip = iter->w.count;
}
}
static void *ipv6_route_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
int r;
struct fib6_info *n;
struct net *net = seq_file_net(seq);
struct ipv6_route_iter *iter = seq->private;
++(*pos);
if (!v)
goto iter_table;
n = rcu_dereference(((struct fib6_info *)v)->fib6_next);
if (n)
return n;
iter_table:
ipv6_route_check_sernum(iter);
spin_lock_bh(&iter->tbl->tb6_lock);
r = fib6_walk_continue(&iter->w);
spin_unlock_bh(&iter->tbl->tb6_lock);
if (r > 0) {
return iter->w.leaf;
} else if (r < 0) {
fib6_walker_unlink(net, &iter->w);
return NULL;
}
fib6_walker_unlink(net, &iter->w);
iter->tbl = ipv6_route_seq_next_table(iter->tbl, net);
if (!iter->tbl)
return NULL;
ipv6_route_seq_setup_walk(iter, net);
goto iter_table;
}
static void *ipv6_route_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
struct net *net = seq_file_net(seq);
struct ipv6_route_iter *iter = seq->private;
rcu_read_lock();
iter->tbl = ipv6_route_seq_next_table(NULL, net);
iter->skip = *pos;
if (iter->tbl) {
loff_t p = 0;
ipv6_route_seq_setup_walk(iter, net);
return ipv6_route_seq_next(seq, NULL, &p);
} else {
return NULL;
}
}
static bool ipv6_route_iter_active(struct ipv6_route_iter *iter)
{
struct fib6_walker *w = &iter->w;
return w->node && !(w->state == FWS_U && w->node == w->root);
}
static void ipv6_route_native_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
struct net *net = seq_file_net(seq);
struct ipv6_route_iter *iter = seq->private;
if (ipv6_route_iter_active(iter))
fib6_walker_unlink(net, &iter->w);
rcu_read_unlock();
}
#if IS_BUILTIN(CONFIG_IPV6) && defined(CONFIG_BPF_SYSCALL)
static int ipv6_route_prog_seq_show(struct bpf_prog *prog,
struct bpf_iter_meta *meta,
void *v)
{
struct bpf_iter__ipv6_route ctx;
ctx.meta = meta;
ctx.rt = v;
return bpf_iter_run_prog(prog, &ctx);
}
static int ipv6_route_seq_show(struct seq_file *seq, void *v)
{
struct ipv6_route_iter *iter = seq->private;
struct bpf_iter_meta meta;
struct bpf_prog *prog;
int ret;
meta.seq = seq;
prog = bpf_iter_get_info(&meta, false);
if (!prog)
return ipv6_route_native_seq_show(seq, v);
ret = ipv6_route_prog_seq_show(prog, &meta, v);
iter->w.leaf = NULL;
return ret;
}
static void ipv6_route_seq_stop(struct seq_file *seq, void *v)
{
struct bpf_iter_meta meta;
struct bpf_prog *prog;
if (!v) {
meta.seq = seq;
prog = bpf_iter_get_info(&meta, true);
if (prog)
(void)ipv6_route_prog_seq_show(prog, &meta, v);
}
ipv6_route_native_seq_stop(seq, v);
}
#else
static int ipv6_route_seq_show(struct seq_file *seq, void *v)
{
return ipv6_route_native_seq_show(seq, v);
}
static void ipv6_route_seq_stop(struct seq_file *seq, void *v)
{
ipv6_route_native_seq_stop(seq, v);
}
#endif
const struct seq_operations ipv6_route_seq_ops = {
.start = ipv6_route_seq_start,
.next = ipv6_route_seq_next,
.stop = ipv6_route_seq_stop,
.show = ipv6_route_seq_show
};
#endif /* CONFIG_PROC_FS */
| linux-master | net/ipv6/ip6_fib.c |
// SPDX-License-Identifier: GPL-2.0
/*
* xfrm6_input.c: based on net/ipv4/xfrm4_input.c
*
* Authors:
* Mitsuru KANDA @USAGI
* Kazunori MIYAZAWA @USAGI
* Kunihiro Ishiguro <[email protected]>
* YOSHIFUJI Hideaki @USAGI
* IPv6 support
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <net/ipv6.h>
#include <net/xfrm.h>
int xfrm6_rcv_spi(struct sk_buff *skb, int nexthdr, __be32 spi,
struct ip6_tnl *t)
{
XFRM_TUNNEL_SKB_CB(skb)->tunnel.ip6 = t;
XFRM_SPI_SKB_CB(skb)->family = AF_INET6;
XFRM_SPI_SKB_CB(skb)->daddroff = offsetof(struct ipv6hdr, daddr);
return xfrm_input(skb, nexthdr, spi, 0);
}
EXPORT_SYMBOL(xfrm6_rcv_spi);
static int xfrm6_transport_finish2(struct net *net, struct sock *sk,
struct sk_buff *skb)
{
if (xfrm_trans_queue(skb, ip6_rcv_finish)) {
kfree_skb(skb);
return NET_RX_DROP;
}
return 0;
}
int xfrm6_transport_finish(struct sk_buff *skb, int async)
{
struct xfrm_offload *xo = xfrm_offload(skb);
int nhlen = skb->data - skb_network_header(skb);
skb_network_header(skb)[IP6CB(skb)->nhoff] =
XFRM_MODE_SKB_CB(skb)->protocol;
#ifndef CONFIG_NETFILTER
if (!async)
return 1;
#endif
__skb_push(skb, nhlen);
ipv6_hdr(skb)->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
skb_postpush_rcsum(skb, skb_network_header(skb), nhlen);
if (xo && (xo->flags & XFRM_GRO)) {
skb_mac_header_rebuild(skb);
skb_reset_transport_header(skb);
return 0;
}
NF_HOOK(NFPROTO_IPV6, NF_INET_PRE_ROUTING,
dev_net(skb->dev), NULL, skb, skb->dev, NULL,
xfrm6_transport_finish2);
return 0;
}
/* If it's a keepalive packet, then just eat it.
* If it's an encapsulated packet, then pass it to the
* IPsec xfrm input.
* Returns 0 if skb passed to xfrm or was dropped.
* Returns >0 if skb should be passed to UDP.
* Returns <0 if skb should be resubmitted (-ret is protocol)
*/
int xfrm6_udp_encap_rcv(struct sock *sk, struct sk_buff *skb)
{
struct udp_sock *up = udp_sk(sk);
struct udphdr *uh;
struct ipv6hdr *ip6h;
int len;
int ip6hlen = sizeof(struct ipv6hdr);
__u8 *udpdata;
__be32 *udpdata32;
__u16 encap_type = up->encap_type;
if (skb->protocol == htons(ETH_P_IP))
return xfrm4_udp_encap_rcv(sk, skb);
/* if this is not encapsulated socket, then just return now */
if (!encap_type)
return 1;
/* If this is a paged skb, make sure we pull up
* whatever data we need to look at. */
len = skb->len - sizeof(struct udphdr);
if (!pskb_may_pull(skb, sizeof(struct udphdr) + min(len, 8)))
return 1;
/* Now we can get the pointers */
uh = udp_hdr(skb);
udpdata = (__u8 *)uh + sizeof(struct udphdr);
udpdata32 = (__be32 *)udpdata;
switch (encap_type) {
default:
case UDP_ENCAP_ESPINUDP:
/* Check if this is a keepalive packet. If so, eat it. */
if (len == 1 && udpdata[0] == 0xff) {
goto drop;
} else if (len > sizeof(struct ip_esp_hdr) && udpdata32[0] != 0) {
/* ESP Packet without Non-ESP header */
len = sizeof(struct udphdr);
} else
/* Must be an IKE packet.. pass it through */
return 1;
break;
case UDP_ENCAP_ESPINUDP_NON_IKE:
/* Check if this is a keepalive packet. If so, eat it. */
if (len == 1 && udpdata[0] == 0xff) {
goto drop;
} else if (len > 2 * sizeof(u32) + sizeof(struct ip_esp_hdr) &&
udpdata32[0] == 0 && udpdata32[1] == 0) {
/* ESP Packet with Non-IKE marker */
len = sizeof(struct udphdr) + 2 * sizeof(u32);
} else
/* Must be an IKE packet.. pass it through */
return 1;
break;
}
/* At this point we are sure that this is an ESPinUDP packet,
* so we need to remove 'len' bytes from the packet (the UDP
* header and optional ESP marker bytes) and then modify the
* protocol to ESP, and then call into the transform receiver.
*/
if (skb_unclone(skb, GFP_ATOMIC))
goto drop;
/* Now we can update and verify the packet length... */
ip6h = ipv6_hdr(skb);
ip6h->payload_len = htons(ntohs(ip6h->payload_len) - len);
if (skb->len < ip6hlen + len) {
/* packet is too small!?! */
goto drop;
}
/* pull the data buffer up to the ESP header and set the
* transport header to point to ESP. Keep UDP on the stack
* for later.
*/
__skb_pull(skb, len);
skb_reset_transport_header(skb);
/* process ESP */
return xfrm6_rcv_encap(skb, IPPROTO_ESP, 0, encap_type);
drop:
kfree_skb(skb);
return 0;
}
int xfrm6_rcv_tnl(struct sk_buff *skb, struct ip6_tnl *t)
{
return xfrm6_rcv_spi(skb, skb_network_header(skb)[IP6CB(skb)->nhoff],
0, t);
}
EXPORT_SYMBOL(xfrm6_rcv_tnl);
int xfrm6_rcv(struct sk_buff *skb)
{
return xfrm6_rcv_tnl(skb, NULL);
}
EXPORT_SYMBOL(xfrm6_rcv);
int xfrm6_input_addr(struct sk_buff *skb, xfrm_address_t *daddr,
xfrm_address_t *saddr, u8 proto)
{
struct net *net = dev_net(skb->dev);
struct xfrm_state *x = NULL;
struct sec_path *sp;
int i = 0;
sp = secpath_set(skb);
if (!sp) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINERROR);
goto drop;
}
if (1 + sp->len == XFRM_MAX_DEPTH) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
goto drop;
}
for (i = 0; i < 3; i++) {
xfrm_address_t *dst, *src;
switch (i) {
case 0:
dst = daddr;
src = saddr;
break;
case 1:
/* lookup state with wild-card source address */
dst = daddr;
src = (xfrm_address_t *)&in6addr_any;
break;
default:
/* lookup state with wild-card addresses */
dst = (xfrm_address_t *)&in6addr_any;
src = (xfrm_address_t *)&in6addr_any;
break;
}
x = xfrm_state_lookup_byaddr(net, skb->mark, dst, src, proto, AF_INET6);
if (!x)
continue;
spin_lock(&x->lock);
if ((!i || (x->props.flags & XFRM_STATE_WILDRECV)) &&
likely(x->km.state == XFRM_STATE_VALID) &&
!xfrm_state_check_expire(x)) {
spin_unlock(&x->lock);
if (x->type->input(x, skb) > 0) {
/* found a valid state */
break;
}
} else
spin_unlock(&x->lock);
xfrm_state_put(x);
x = NULL;
}
if (!x) {
XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOSTATES);
xfrm_audit_state_notfound_simple(skb, AF_INET6);
goto drop;
}
sp->xvec[sp->len++] = x;
spin_lock(&x->lock);
x->curlft.bytes += skb->len;
x->curlft.packets++;
spin_unlock(&x->lock);
return 1;
drop:
return -1;
}
EXPORT_SYMBOL(xfrm6_input_addr);
| linux-master | net/ipv6/xfrm6_input.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* IPv6 Syncookies implementation for the Linux kernel
*
* Authors:
* Glenn Griffin <[email protected]>
*
* Based on IPv4 implementation by Andi Kleen
* linux/net/ipv4/syncookies.c
*/
#include <linux/tcp.h>
#include <linux/random.h>
#include <linux/siphash.h>
#include <linux/kernel.h>
#include <net/secure_seq.h>
#include <net/ipv6.h>
#include <net/tcp.h>
#define COOKIEBITS 24 /* Upper bits store count */
#define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
static siphash_aligned_key_t syncookie6_secret[2];
/* RFC 2460, Section 8.3:
* [ipv6 tcp] MSS must be computed as the maximum packet size minus 60 [..]
*
* Due to IPV6_MIN_MTU=1280 the lowest possible MSS is 1220, which allows
* using higher values than ipv4 tcp syncookies.
* The other values are chosen based on ethernet (1500 and 9k MTU), plus
* one that accounts for common encap (PPPoe) overhead. Table must be sorted.
*/
static __u16 const msstab[] = {
1280 - 60, /* IPV6_MIN_MTU - 60 */
1480 - 60,
1500 - 60,
9000 - 60,
};
static u32 cookie_hash(const struct in6_addr *saddr,
const struct in6_addr *daddr,
__be16 sport, __be16 dport, u32 count, int c)
{
const struct {
struct in6_addr saddr;
struct in6_addr daddr;
u32 count;
__be16 sport;
__be16 dport;
} __aligned(SIPHASH_ALIGNMENT) combined = {
.saddr = *saddr,
.daddr = *daddr,
.count = count,
.sport = sport,
.dport = dport
};
net_get_random_once(syncookie6_secret, sizeof(syncookie6_secret));
return siphash(&combined, offsetofend(typeof(combined), dport),
&syncookie6_secret[c]);
}
static __u32 secure_tcp_syn_cookie(const struct in6_addr *saddr,
const struct in6_addr *daddr,
__be16 sport, __be16 dport, __u32 sseq,
__u32 data)
{
u32 count = tcp_cookie_time();
return (cookie_hash(saddr, daddr, sport, dport, 0, 0) +
sseq + (count << COOKIEBITS) +
((cookie_hash(saddr, daddr, sport, dport, count, 1) + data)
& COOKIEMASK));
}
static __u32 check_tcp_syn_cookie(__u32 cookie, const struct in6_addr *saddr,
const struct in6_addr *daddr, __be16 sport,
__be16 dport, __u32 sseq)
{
__u32 diff, count = tcp_cookie_time();
cookie -= cookie_hash(saddr, daddr, sport, dport, 0, 0) + sseq;
diff = (count - (cookie >> COOKIEBITS)) & ((__u32) -1 >> COOKIEBITS);
if (diff >= MAX_SYNCOOKIE_AGE)
return (__u32)-1;
return (cookie -
cookie_hash(saddr, daddr, sport, dport, count - diff, 1))
& COOKIEMASK;
}
u32 __cookie_v6_init_sequence(const struct ipv6hdr *iph,
const struct tcphdr *th, __u16 *mssp)
{
int mssind;
const __u16 mss = *mssp;
for (mssind = ARRAY_SIZE(msstab) - 1; mssind ; mssind--)
if (mss >= msstab[mssind])
break;
*mssp = msstab[mssind];
return secure_tcp_syn_cookie(&iph->saddr, &iph->daddr, th->source,
th->dest, ntohl(th->seq), mssind);
}
EXPORT_SYMBOL_GPL(__cookie_v6_init_sequence);
__u32 cookie_v6_init_sequence(const struct sk_buff *skb, __u16 *mssp)
{
const struct ipv6hdr *iph = ipv6_hdr(skb);
const struct tcphdr *th = tcp_hdr(skb);
return __cookie_v6_init_sequence(iph, th, mssp);
}
int __cookie_v6_check(const struct ipv6hdr *iph, const struct tcphdr *th,
__u32 cookie)
{
__u32 seq = ntohl(th->seq) - 1;
__u32 mssind = check_tcp_syn_cookie(cookie, &iph->saddr, &iph->daddr,
th->source, th->dest, seq);
return mssind < ARRAY_SIZE(msstab) ? msstab[mssind] : 0;
}
EXPORT_SYMBOL_GPL(__cookie_v6_check);
struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb)
{
struct tcp_options_received tcp_opt;
struct inet_request_sock *ireq;
struct tcp_request_sock *treq;
struct ipv6_pinfo *np = inet6_sk(sk);
struct tcp_sock *tp = tcp_sk(sk);
const struct tcphdr *th = tcp_hdr(skb);
__u32 cookie = ntohl(th->ack_seq) - 1;
struct sock *ret = sk;
struct request_sock *req;
int full_space, mss;
struct dst_entry *dst;
__u8 rcv_wscale;
u32 tsoff = 0;
if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies) ||
!th->ack || th->rst)
goto out;
if (tcp_synq_no_recent_overflow(sk))
goto out;
mss = __cookie_v6_check(ipv6_hdr(skb), th, cookie);
if (mss == 0) {
__NET_INC_STATS(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED);
goto out;
}
__NET_INC_STATS(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV);
/* check for timestamp cookie support */
memset(&tcp_opt, 0, sizeof(tcp_opt));
tcp_parse_options(sock_net(sk), skb, &tcp_opt, 0, NULL);
if (tcp_opt.saw_tstamp && tcp_opt.rcv_tsecr) {
tsoff = secure_tcpv6_ts_off(sock_net(sk),
ipv6_hdr(skb)->daddr.s6_addr32,
ipv6_hdr(skb)->saddr.s6_addr32);
tcp_opt.rcv_tsecr -= tsoff;
}
if (!cookie_timestamp_decode(sock_net(sk), &tcp_opt))
goto out;
ret = NULL;
req = cookie_tcp_reqsk_alloc(&tcp6_request_sock_ops,
&tcp_request_sock_ipv6_ops, sk, skb);
if (!req)
goto out;
ireq = inet_rsk(req);
treq = tcp_rsk(req);
treq->tfo_listener = false;
if (security_inet_conn_request(sk, skb, req))
goto out_free;
req->mss = mss;
ireq->ir_rmt_port = th->source;
ireq->ir_num = ntohs(th->dest);
ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr;
ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr;
if (ipv6_opt_accepted(sk, skb, &TCP_SKB_CB(skb)->header.h6) ||
np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo ||
np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) {
refcount_inc(&skb->users);
ireq->pktopts = skb;
}
ireq->ir_iif = inet_request_bound_dev_if(sk, skb);
/* So that link locals have meaning */
if (!sk->sk_bound_dev_if &&
ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL)
ireq->ir_iif = tcp_v6_iif(skb);
ireq->ir_mark = inet_request_mark(sk, skb);
req->num_retrans = 0;
ireq->snd_wscale = tcp_opt.snd_wscale;
ireq->sack_ok = tcp_opt.sack_ok;
ireq->wscale_ok = tcp_opt.wscale_ok;
ireq->tstamp_ok = tcp_opt.saw_tstamp;
req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0;
treq->snt_synack = 0;
treq->rcv_isn = ntohl(th->seq) - 1;
treq->snt_isn = cookie;
treq->ts_off = 0;
treq->txhash = net_tx_rndhash();
if (IS_ENABLED(CONFIG_SMC))
ireq->smc_ok = 0;
/*
* We need to lookup the dst_entry to get the correct window size.
* This is taken from tcp_v6_syn_recv_sock. Somebody please enlighten
* me if there is a preferred way.
*/
{
struct in6_addr *final_p, final;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_TCP;
fl6.daddr = ireq->ir_v6_rmt_addr;
final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt), &final);
fl6.saddr = ireq->ir_v6_loc_addr;
fl6.flowi6_oif = ireq->ir_iif;
fl6.flowi6_mark = ireq->ir_mark;
fl6.fl6_dport = ireq->ir_rmt_port;
fl6.fl6_sport = inet_sk(sk)->inet_sport;
fl6.flowi6_uid = sk->sk_uid;
security_req_classify_flow(req, flowi6_to_flowi_common(&fl6));
dst = ip6_dst_lookup_flow(sock_net(sk), sk, &fl6, final_p);
if (IS_ERR(dst))
goto out_free;
}
req->rsk_window_clamp = tp->window_clamp ? :dst_metric(dst, RTAX_WINDOW);
/* limit the window selection if the user enforce a smaller rx buffer */
full_space = tcp_full_space(sk);
if (sk->sk_userlocks & SOCK_RCVBUF_LOCK &&
(req->rsk_window_clamp > full_space || req->rsk_window_clamp == 0))
req->rsk_window_clamp = full_space;
tcp_select_initial_window(sk, full_space, req->mss,
&req->rsk_rcv_wnd, &req->rsk_window_clamp,
ireq->wscale_ok, &rcv_wscale,
dst_metric(dst, RTAX_INITRWND));
ireq->rcv_wscale = rcv_wscale;
ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), dst);
ret = tcp_get_cookie_sock(sk, skb, req, dst, tsoff);
out:
return ret;
out_free:
reqsk_free(req);
return NULL;
}
| linux-master | net/ipv6/syncookies.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* SR-IPv6 implementation
*
* Author:
* David Lebrun <[email protected]>
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/net.h>
#include <linux/in6.h>
#include <linux/slab.h>
#include <linux/rhashtable.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <net/seg6.h>
#include <net/genetlink.h>
#include <linux/seg6.h>
#include <linux/seg6_genl.h>
#ifdef CONFIG_IPV6_SEG6_HMAC
#include <net/seg6_hmac.h>
#endif
bool seg6_validate_srh(struct ipv6_sr_hdr *srh, int len, bool reduced)
{
unsigned int tlv_offset;
int max_last_entry;
int trailing;
if (srh->type != IPV6_SRCRT_TYPE_4)
return false;
if (((srh->hdrlen + 1) << 3) != len)
return false;
if (!reduced && srh->segments_left > srh->first_segment) {
return false;
} else {
max_last_entry = (srh->hdrlen / 2) - 1;
if (srh->first_segment > max_last_entry)
return false;
if (srh->segments_left > srh->first_segment + 1)
return false;
}
tlv_offset = sizeof(*srh) + ((srh->first_segment + 1) << 4);
trailing = len - tlv_offset;
if (trailing < 0)
return false;
while (trailing) {
struct sr6_tlv *tlv;
unsigned int tlv_len;
if (trailing < sizeof(*tlv))
return false;
tlv = (struct sr6_tlv *)((unsigned char *)srh + tlv_offset);
tlv_len = sizeof(*tlv) + tlv->len;
trailing -= tlv_len;
if (trailing < 0)
return false;
tlv_offset += tlv_len;
}
return true;
}
struct ipv6_sr_hdr *seg6_get_srh(struct sk_buff *skb, int flags)
{
struct ipv6_sr_hdr *srh;
int len, srhoff = 0;
if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, &flags) < 0)
return NULL;
if (!pskb_may_pull(skb, srhoff + sizeof(*srh)))
return NULL;
srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
len = (srh->hdrlen + 1) << 3;
if (!pskb_may_pull(skb, srhoff + len))
return NULL;
/* note that pskb_may_pull may change pointers in header;
* for this reason it is necessary to reload them when needed.
*/
srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
if (!seg6_validate_srh(srh, len, true))
return NULL;
return srh;
}
/* Determine if an ICMP invoking packet contains a segment routing
* header. If it does, extract the offset to the true destination
* address, which is in the first segment address.
*/
void seg6_icmp_srh(struct sk_buff *skb, struct inet6_skb_parm *opt)
{
__u16 network_header = skb->network_header;
struct ipv6_sr_hdr *srh;
/* Update network header to point to the invoking packet
* inside the ICMP packet, so we can use the seg6_get_srh()
* helper.
*/
skb_reset_network_header(skb);
srh = seg6_get_srh(skb, 0);
if (!srh)
goto out;
if (srh->type != IPV6_SRCRT_TYPE_4)
goto out;
opt->flags |= IP6SKB_SEG6;
opt->srhoff = (unsigned char *)srh - skb->data;
out:
/* Restore the network header back to the ICMP packet */
skb->network_header = network_header;
}
static struct genl_family seg6_genl_family;
static const struct nla_policy seg6_genl_policy[SEG6_ATTR_MAX + 1] = {
[SEG6_ATTR_DST] = { .type = NLA_BINARY,
.len = sizeof(struct in6_addr) },
[SEG6_ATTR_DSTLEN] = { .type = NLA_S32, },
[SEG6_ATTR_HMACKEYID] = { .type = NLA_U32, },
[SEG6_ATTR_SECRET] = { .type = NLA_BINARY, },
[SEG6_ATTR_SECRETLEN] = { .type = NLA_U8, },
[SEG6_ATTR_ALGID] = { .type = NLA_U8, },
[SEG6_ATTR_HMACINFO] = { .type = NLA_NESTED, },
};
#ifdef CONFIG_IPV6_SEG6_HMAC
static int seg6_genl_sethmac(struct sk_buff *skb, struct genl_info *info)
{
struct net *net = genl_info_net(info);
struct seg6_pernet_data *sdata;
struct seg6_hmac_info *hinfo;
u32 hmackeyid;
char *secret;
int err = 0;
u8 algid;
u8 slen;
sdata = seg6_pernet(net);
if (!info->attrs[SEG6_ATTR_HMACKEYID] ||
!info->attrs[SEG6_ATTR_SECRETLEN] ||
!info->attrs[SEG6_ATTR_ALGID])
return -EINVAL;
hmackeyid = nla_get_u32(info->attrs[SEG6_ATTR_HMACKEYID]);
slen = nla_get_u8(info->attrs[SEG6_ATTR_SECRETLEN]);
algid = nla_get_u8(info->attrs[SEG6_ATTR_ALGID]);
if (hmackeyid == 0)
return -EINVAL;
if (slen > SEG6_HMAC_SECRET_LEN)
return -EINVAL;
mutex_lock(&sdata->lock);
hinfo = seg6_hmac_info_lookup(net, hmackeyid);
if (!slen) {
err = seg6_hmac_info_del(net, hmackeyid);
goto out_unlock;
}
if (!info->attrs[SEG6_ATTR_SECRET]) {
err = -EINVAL;
goto out_unlock;
}
if (slen > nla_len(info->attrs[SEG6_ATTR_SECRET])) {
err = -EINVAL;
goto out_unlock;
}
if (hinfo) {
err = seg6_hmac_info_del(net, hmackeyid);
if (err)
goto out_unlock;
}
secret = (char *)nla_data(info->attrs[SEG6_ATTR_SECRET]);
hinfo = kzalloc(sizeof(*hinfo), GFP_KERNEL);
if (!hinfo) {
err = -ENOMEM;
goto out_unlock;
}
memcpy(hinfo->secret, secret, slen);
hinfo->slen = slen;
hinfo->alg_id = algid;
hinfo->hmackeyid = hmackeyid;
err = seg6_hmac_info_add(net, hmackeyid, hinfo);
if (err)
kfree(hinfo);
out_unlock:
mutex_unlock(&sdata->lock);
return err;
}
#else
static int seg6_genl_sethmac(struct sk_buff *skb, struct genl_info *info)
{
return -ENOTSUPP;
}
#endif
static int seg6_genl_set_tunsrc(struct sk_buff *skb, struct genl_info *info)
{
struct net *net = genl_info_net(info);
struct in6_addr *val, *t_old, *t_new;
struct seg6_pernet_data *sdata;
sdata = seg6_pernet(net);
if (!info->attrs[SEG6_ATTR_DST])
return -EINVAL;
val = nla_data(info->attrs[SEG6_ATTR_DST]);
t_new = kmemdup(val, sizeof(*val), GFP_KERNEL);
if (!t_new)
return -ENOMEM;
mutex_lock(&sdata->lock);
t_old = sdata->tun_src;
rcu_assign_pointer(sdata->tun_src, t_new);
mutex_unlock(&sdata->lock);
synchronize_net();
kfree(t_old);
return 0;
}
static int seg6_genl_get_tunsrc(struct sk_buff *skb, struct genl_info *info)
{
struct net *net = genl_info_net(info);
struct in6_addr *tun_src;
struct sk_buff *msg;
void *hdr;
msg = genlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = genlmsg_put(msg, info->snd_portid, info->snd_seq,
&seg6_genl_family, 0, SEG6_CMD_GET_TUNSRC);
if (!hdr)
goto free_msg;
rcu_read_lock();
tun_src = rcu_dereference(seg6_pernet(net)->tun_src);
if (nla_put(msg, SEG6_ATTR_DST, sizeof(struct in6_addr), tun_src))
goto nla_put_failure;
rcu_read_unlock();
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
rcu_read_unlock();
free_msg:
nlmsg_free(msg);
return -ENOMEM;
}
#ifdef CONFIG_IPV6_SEG6_HMAC
static int __seg6_hmac_fill_info(struct seg6_hmac_info *hinfo,
struct sk_buff *msg)
{
if (nla_put_u32(msg, SEG6_ATTR_HMACKEYID, hinfo->hmackeyid) ||
nla_put_u8(msg, SEG6_ATTR_SECRETLEN, hinfo->slen) ||
nla_put(msg, SEG6_ATTR_SECRET, hinfo->slen, hinfo->secret) ||
nla_put_u8(msg, SEG6_ATTR_ALGID, hinfo->alg_id))
return -1;
return 0;
}
static int __seg6_genl_dumphmac_element(struct seg6_hmac_info *hinfo,
u32 portid, u32 seq, u32 flags,
struct sk_buff *skb, u8 cmd)
{
void *hdr;
hdr = genlmsg_put(skb, portid, seq, &seg6_genl_family, flags, cmd);
if (!hdr)
return -ENOMEM;
if (__seg6_hmac_fill_info(hinfo, skb) < 0)
goto nla_put_failure;
genlmsg_end(skb, hdr);
return 0;
nla_put_failure:
genlmsg_cancel(skb, hdr);
return -EMSGSIZE;
}
static int seg6_genl_dumphmac_start(struct netlink_callback *cb)
{
struct net *net = sock_net(cb->skb->sk);
struct seg6_pernet_data *sdata;
struct rhashtable_iter *iter;
sdata = seg6_pernet(net);
iter = (struct rhashtable_iter *)cb->args[0];
if (!iter) {
iter = kmalloc(sizeof(*iter), GFP_KERNEL);
if (!iter)
return -ENOMEM;
cb->args[0] = (long)iter;
}
rhashtable_walk_enter(&sdata->hmac_infos, iter);
return 0;
}
static int seg6_genl_dumphmac_done(struct netlink_callback *cb)
{
struct rhashtable_iter *iter = (struct rhashtable_iter *)cb->args[0];
rhashtable_walk_exit(iter);
kfree(iter);
return 0;
}
static int seg6_genl_dumphmac(struct sk_buff *skb, struct netlink_callback *cb)
{
struct rhashtable_iter *iter = (struct rhashtable_iter *)cb->args[0];
struct seg6_hmac_info *hinfo;
int ret;
rhashtable_walk_start(iter);
for (;;) {
hinfo = rhashtable_walk_next(iter);
if (IS_ERR(hinfo)) {
if (PTR_ERR(hinfo) == -EAGAIN)
continue;
ret = PTR_ERR(hinfo);
goto done;
} else if (!hinfo) {
break;
}
ret = __seg6_genl_dumphmac_element(hinfo,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
NLM_F_MULTI,
skb, SEG6_CMD_DUMPHMAC);
if (ret)
goto done;
}
ret = skb->len;
done:
rhashtable_walk_stop(iter);
return ret;
}
#else
static int seg6_genl_dumphmac_start(struct netlink_callback *cb)
{
return 0;
}
static int seg6_genl_dumphmac_done(struct netlink_callback *cb)
{
return 0;
}
static int seg6_genl_dumphmac(struct sk_buff *skb, struct netlink_callback *cb)
{
return -ENOTSUPP;
}
#endif
static int __net_init seg6_net_init(struct net *net)
{
struct seg6_pernet_data *sdata;
sdata = kzalloc(sizeof(*sdata), GFP_KERNEL);
if (!sdata)
return -ENOMEM;
mutex_init(&sdata->lock);
sdata->tun_src = kzalloc(sizeof(*sdata->tun_src), GFP_KERNEL);
if (!sdata->tun_src) {
kfree(sdata);
return -ENOMEM;
}
net->ipv6.seg6_data = sdata;
#ifdef CONFIG_IPV6_SEG6_HMAC
if (seg6_hmac_net_init(net)) {
kfree(rcu_dereference_raw(sdata->tun_src));
kfree(sdata);
return -ENOMEM;
}
#endif
return 0;
}
static void __net_exit seg6_net_exit(struct net *net)
{
struct seg6_pernet_data *sdata = seg6_pernet(net);
#ifdef CONFIG_IPV6_SEG6_HMAC
seg6_hmac_net_exit(net);
#endif
kfree(rcu_dereference_raw(sdata->tun_src));
kfree(sdata);
}
static struct pernet_operations ip6_segments_ops = {
.init = seg6_net_init,
.exit = seg6_net_exit,
};
static const struct genl_ops seg6_genl_ops[] = {
{
.cmd = SEG6_CMD_SETHMAC,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = seg6_genl_sethmac,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = SEG6_CMD_DUMPHMAC,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.start = seg6_genl_dumphmac_start,
.dumpit = seg6_genl_dumphmac,
.done = seg6_genl_dumphmac_done,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = SEG6_CMD_SET_TUNSRC,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = seg6_genl_set_tunsrc,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = SEG6_CMD_GET_TUNSRC,
.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
.doit = seg6_genl_get_tunsrc,
.flags = GENL_ADMIN_PERM,
},
};
static struct genl_family seg6_genl_family __ro_after_init = {
.hdrsize = 0,
.name = SEG6_GENL_NAME,
.version = SEG6_GENL_VERSION,
.maxattr = SEG6_ATTR_MAX,
.policy = seg6_genl_policy,
.netnsok = true,
.parallel_ops = true,
.ops = seg6_genl_ops,
.n_ops = ARRAY_SIZE(seg6_genl_ops),
.resv_start_op = SEG6_CMD_GET_TUNSRC + 1,
.module = THIS_MODULE,
};
int __init seg6_init(void)
{
int err;
err = genl_register_family(&seg6_genl_family);
if (err)
goto out;
err = register_pernet_subsys(&ip6_segments_ops);
if (err)
goto out_unregister_genl;
#ifdef CONFIG_IPV6_SEG6_LWTUNNEL
err = seg6_iptunnel_init();
if (err)
goto out_unregister_pernet;
err = seg6_local_init();
if (err)
goto out_unregister_pernet;
#endif
#ifdef CONFIG_IPV6_SEG6_HMAC
err = seg6_hmac_init();
if (err)
goto out_unregister_iptun;
#endif
pr_info("Segment Routing with IPv6\n");
out:
return err;
#ifdef CONFIG_IPV6_SEG6_HMAC
out_unregister_iptun:
#ifdef CONFIG_IPV6_SEG6_LWTUNNEL
seg6_local_exit();
seg6_iptunnel_exit();
#endif
#endif
#ifdef CONFIG_IPV6_SEG6_LWTUNNEL
out_unregister_pernet:
unregister_pernet_subsys(&ip6_segments_ops);
#endif
out_unregister_genl:
genl_unregister_family(&seg6_genl_family);
goto out;
}
void seg6_exit(void)
{
#ifdef CONFIG_IPV6_SEG6_HMAC
seg6_hmac_exit();
#endif
#ifdef CONFIG_IPV6_SEG6_LWTUNNEL
seg6_iptunnel_exit();
#endif
unregister_pernet_subsys(&ip6_segments_ops);
genl_unregister_family(&seg6_genl_family);
}
| linux-master | net/ipv6/seg6.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* RAW sockets for IPv6
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <[email protected]>
*
* Adapted from linux/net/ipv4/raw.c
*
* Fixes:
* Hideaki YOSHIFUJI : sin6_scope_id support
* YOSHIFUJI,H.@USAGI : raw checksum (RFC2292(bis) compliance)
* Kazunori MIYAZAWA @USAGI: change process style to use ip6_append_data
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/slab.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/in6.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/icmpv6.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <linux/skbuff.h>
#include <linux/compat.h>
#include <linux/uaccess.h>
#include <asm/ioctls.h>
#include <net/net_namespace.h>
#include <net/ip.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/protocol.h>
#include <net/ip6_route.h>
#include <net/ip6_checksum.h>
#include <net/addrconf.h>
#include <net/transp_v6.h>
#include <net/udp.h>
#include <net/inet_common.h>
#include <net/tcp_states.h>
#if IS_ENABLED(CONFIG_IPV6_MIP6)
#include <net/mip6.h>
#endif
#include <linux/mroute6.h>
#include <net/raw.h>
#include <net/rawv6.h>
#include <net/xfrm.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/export.h>
#define ICMPV6_HDRLEN 4 /* ICMPv6 header, RFC 4443 Section 2.1 */
struct raw_hashinfo raw_v6_hashinfo;
EXPORT_SYMBOL_GPL(raw_v6_hashinfo);
bool raw_v6_match(struct net *net, const struct sock *sk, unsigned short num,
const struct in6_addr *loc_addr,
const struct in6_addr *rmt_addr, int dif, int sdif)
{
if (inet_sk(sk)->inet_num != num ||
!net_eq(sock_net(sk), net) ||
(!ipv6_addr_any(&sk->sk_v6_daddr) &&
!ipv6_addr_equal(&sk->sk_v6_daddr, rmt_addr)) ||
!raw_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
dif, sdif))
return false;
if (ipv6_addr_any(&sk->sk_v6_rcv_saddr) ||
ipv6_addr_equal(&sk->sk_v6_rcv_saddr, loc_addr) ||
(ipv6_addr_is_multicast(loc_addr) &&
inet6_mc_check(sk, loc_addr, rmt_addr)))
return true;
return false;
}
EXPORT_SYMBOL_GPL(raw_v6_match);
/*
* 0 - deliver
* 1 - block
*/
static int icmpv6_filter(const struct sock *sk, const struct sk_buff *skb)
{
struct icmp6hdr _hdr;
const struct icmp6hdr *hdr;
/* We require only the four bytes of the ICMPv6 header, not any
* additional bytes of message body in "struct icmp6hdr".
*/
hdr = skb_header_pointer(skb, skb_transport_offset(skb),
ICMPV6_HDRLEN, &_hdr);
if (hdr) {
const __u32 *data = &raw6_sk(sk)->filter.data[0];
unsigned int type = hdr->icmp6_type;
return (data[type >> 5] & (1U << (type & 31))) != 0;
}
return 1;
}
#if IS_ENABLED(CONFIG_IPV6_MIP6)
typedef int mh_filter_t(struct sock *sock, struct sk_buff *skb);
static mh_filter_t __rcu *mh_filter __read_mostly;
int rawv6_mh_filter_register(mh_filter_t filter)
{
rcu_assign_pointer(mh_filter, filter);
return 0;
}
EXPORT_SYMBOL(rawv6_mh_filter_register);
int rawv6_mh_filter_unregister(mh_filter_t filter)
{
RCU_INIT_POINTER(mh_filter, NULL);
synchronize_rcu();
return 0;
}
EXPORT_SYMBOL(rawv6_mh_filter_unregister);
#endif
/*
* demultiplex raw sockets.
* (should consider queueing the skb in the sock receive_queue
* without calling rawv6.c)
*
* Caller owns SKB so we must make clones.
*/
static bool ipv6_raw_deliver(struct sk_buff *skb, int nexthdr)
{
struct net *net = dev_net(skb->dev);
const struct in6_addr *saddr;
const struct in6_addr *daddr;
struct hlist_head *hlist;
struct sock *sk;
bool delivered = false;
__u8 hash;
saddr = &ipv6_hdr(skb)->saddr;
daddr = saddr + 1;
hash = raw_hashfunc(net, nexthdr);
hlist = &raw_v6_hashinfo.ht[hash];
rcu_read_lock();
sk_for_each_rcu(sk, hlist) {
int filtered;
if (!raw_v6_match(net, sk, nexthdr, daddr, saddr,
inet6_iif(skb), inet6_sdif(skb)))
continue;
delivered = true;
switch (nexthdr) {
case IPPROTO_ICMPV6:
filtered = icmpv6_filter(sk, skb);
break;
#if IS_ENABLED(CONFIG_IPV6_MIP6)
case IPPROTO_MH:
{
/* XXX: To validate MH only once for each packet,
* this is placed here. It should be after checking
* xfrm policy, however it doesn't. The checking xfrm
* policy is placed in rawv6_rcv() because it is
* required for each socket.
*/
mh_filter_t *filter;
filter = rcu_dereference(mh_filter);
filtered = filter ? (*filter)(sk, skb) : 0;
break;
}
#endif
default:
filtered = 0;
break;
}
if (filtered < 0)
break;
if (filtered == 0) {
struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
/* Not releasing hash table! */
if (clone)
rawv6_rcv(sk, clone);
}
}
rcu_read_unlock();
return delivered;
}
bool raw6_local_deliver(struct sk_buff *skb, int nexthdr)
{
return ipv6_raw_deliver(skb, nexthdr);
}
/* This cleans up af_inet6 a bit. -DaveM */
static int rawv6_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) uaddr;
__be32 v4addr = 0;
int addr_type;
int err;
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (addr->sin6_family != AF_INET6)
return -EINVAL;
addr_type = ipv6_addr_type(&addr->sin6_addr);
/* Raw sockets are IPv6 only */
if (addr_type == IPV6_ADDR_MAPPED)
return -EADDRNOTAVAIL;
lock_sock(sk);
err = -EINVAL;
if (sk->sk_state != TCP_CLOSE)
goto out;
rcu_read_lock();
/* Check if the address belongs to the host. */
if (addr_type != IPV6_ADDR_ANY) {
struct net_device *dev = NULL;
if (__ipv6_addr_needs_scope_id(addr_type)) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
addr->sin6_scope_id) {
/* Override any existing binding, if another
* one is supplied by user.
*/
sk->sk_bound_dev_if = addr->sin6_scope_id;
}
/* Binding to link-local address requires an interface */
if (!sk->sk_bound_dev_if)
goto out_unlock;
}
if (sk->sk_bound_dev_if) {
err = -ENODEV;
dev = dev_get_by_index_rcu(sock_net(sk),
sk->sk_bound_dev_if);
if (!dev)
goto out_unlock;
}
/* ipv4 addr of the socket is invalid. Only the
* unspecified and mapped address have a v4 equivalent.
*/
v4addr = LOOPBACK4_IPV6;
if (!(addr_type & IPV6_ADDR_MULTICAST) &&
!ipv6_can_nonlocal_bind(sock_net(sk), inet)) {
err = -EADDRNOTAVAIL;
if (!ipv6_chk_addr(sock_net(sk), &addr->sin6_addr,
dev, 0)) {
goto out_unlock;
}
}
}
inet->inet_rcv_saddr = inet->inet_saddr = v4addr;
sk->sk_v6_rcv_saddr = addr->sin6_addr;
if (!(addr_type & IPV6_ADDR_MULTICAST))
np->saddr = addr->sin6_addr;
err = 0;
out_unlock:
rcu_read_unlock();
out:
release_sock(sk);
return err;
}
static void rawv6_err(struct sock *sk, struct sk_buff *skb,
struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
struct ipv6_pinfo *np = inet6_sk(sk);
int err;
int harderr;
/* Report error on raw socket, if:
1. User requested recverr.
2. Socket is connected (otherwise the error indication
is useless without recverr and error is hard.
*/
if (!np->recverr && sk->sk_state != TCP_ESTABLISHED)
return;
harderr = icmpv6_err_convert(type, code, &err);
if (type == ICMPV6_PKT_TOOBIG) {
ip6_sk_update_pmtu(skb, sk, info);
harderr = (np->pmtudisc == IPV6_PMTUDISC_DO);
}
if (type == NDISC_REDIRECT) {
ip6_sk_redirect(skb, sk);
return;
}
if (np->recverr) {
u8 *payload = skb->data;
if (!inet_test_bit(HDRINCL, sk))
payload += offset;
ipv6_icmp_error(sk, skb, err, 0, ntohl(info), payload);
}
if (np->recverr || harderr) {
sk->sk_err = err;
sk_error_report(sk);
}
}
void raw6_icmp_error(struct sk_buff *skb, int nexthdr,
u8 type, u8 code, int inner_offset, __be32 info)
{
struct net *net = dev_net(skb->dev);
struct hlist_head *hlist;
struct sock *sk;
int hash;
hash = raw_hashfunc(net, nexthdr);
hlist = &raw_v6_hashinfo.ht[hash];
rcu_read_lock();
sk_for_each_rcu(sk, hlist) {
/* Note: ipv6_hdr(skb) != skb->data */
const struct ipv6hdr *ip6h = (const struct ipv6hdr *)skb->data;
if (!raw_v6_match(net, sk, nexthdr, &ip6h->saddr, &ip6h->daddr,
inet6_iif(skb), inet6_iif(skb)))
continue;
rawv6_err(sk, skb, NULL, type, code, inner_offset, info);
}
rcu_read_unlock();
}
static inline int rawv6_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
enum skb_drop_reason reason;
if ((raw6_sk(sk)->checksum || rcu_access_pointer(sk->sk_filter)) &&
skb_checksum_complete(skb)) {
atomic_inc(&sk->sk_drops);
kfree_skb_reason(skb, SKB_DROP_REASON_SKB_CSUM);
return NET_RX_DROP;
}
/* Charge it to the socket. */
skb_dst_drop(skb);
if (sock_queue_rcv_skb_reason(sk, skb, &reason) < 0) {
kfree_skb_reason(skb, reason);
return NET_RX_DROP;
}
return 0;
}
/*
* This is next to useless...
* if we demultiplex in network layer we don't need the extra call
* just to queue the skb...
* maybe we could have the network decide upon a hint if it
* should call raw_rcv for demultiplexing
*/
int rawv6_rcv(struct sock *sk, struct sk_buff *skb)
{
struct inet_sock *inet = inet_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb)) {
atomic_inc(&sk->sk_drops);
kfree_skb_reason(skb, SKB_DROP_REASON_XFRM_POLICY);
return NET_RX_DROP;
}
nf_reset_ct(skb);
if (!rp->checksum)
skb->ip_summed = CHECKSUM_UNNECESSARY;
if (skb->ip_summed == CHECKSUM_COMPLETE) {
skb_postpull_rcsum(skb, skb_network_header(skb),
skb_network_header_len(skb));
if (!csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
skb->len, inet->inet_num, skb->csum))
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
if (!skb_csum_unnecessary(skb))
skb->csum = ~csum_unfold(csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
skb->len,
inet->inet_num, 0));
if (inet_test_bit(HDRINCL, sk)) {
if (skb_checksum_complete(skb)) {
atomic_inc(&sk->sk_drops);
kfree_skb_reason(skb, SKB_DROP_REASON_SKB_CSUM);
return NET_RX_DROP;
}
}
rawv6_rcv_skb(sk, skb);
return 0;
}
/*
* This should be easy, if there is something there
* we return it, otherwise we block.
*/
static int rawv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
struct sk_buff *skb;
size_t copied;
int err;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len, addr_len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len, addr_len);
skb = skb_recv_datagram(sk, flags, &err);
if (!skb)
goto out;
copied = skb->len;
if (copied > len) {
copied = len;
msg->msg_flags |= MSG_TRUNC;
}
if (skb_csum_unnecessary(skb)) {
err = skb_copy_datagram_msg(skb, 0, msg, copied);
} else if (msg->msg_flags&MSG_TRUNC) {
if (__skb_checksum_complete(skb))
goto csum_copy_err;
err = skb_copy_datagram_msg(skb, 0, msg, copied);
} else {
err = skb_copy_and_csum_datagram_msg(skb, 0, msg);
if (err == -EINVAL)
goto csum_copy_err;
}
if (err)
goto out_free;
/* Copy the address. */
if (sin6) {
sin6->sin6_family = AF_INET6;
sin6->sin6_port = 0;
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_flowinfo = 0;
sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr,
inet6_iif(skb));
*addr_len = sizeof(*sin6);
}
sock_recv_cmsgs(msg, sk, skb);
if (np->rxopt.all)
ip6_datagram_recv_ctl(sk, msg, skb);
err = copied;
if (flags & MSG_TRUNC)
err = skb->len;
out_free:
skb_free_datagram(sk, skb);
out:
return err;
csum_copy_err:
skb_kill_datagram(sk, skb, flags);
/* Error for blocking case is chosen to masquerade
as some normal condition.
*/
err = (flags&MSG_DONTWAIT) ? -EAGAIN : -EHOSTUNREACH;
goto out;
}
static int rawv6_push_pending_frames(struct sock *sk, struct flowi6 *fl6,
struct raw6_sock *rp)
{
struct ipv6_txoptions *opt;
struct sk_buff *skb;
int err = 0;
int offset;
int len;
int total_len;
__wsum tmp_csum;
__sum16 csum;
if (!rp->checksum)
goto send;
skb = skb_peek(&sk->sk_write_queue);
if (!skb)
goto out;
offset = rp->offset;
total_len = inet_sk(sk)->cork.base.length;
opt = inet6_sk(sk)->cork.opt;
total_len -= opt ? opt->opt_flen : 0;
if (offset >= total_len - 1) {
err = -EINVAL;
ip6_flush_pending_frames(sk);
goto out;
}
/* should be check HW csum miyazawa */
if (skb_queue_len(&sk->sk_write_queue) == 1) {
/*
* Only one fragment on the socket.
*/
tmp_csum = skb->csum;
} else {
struct sk_buff *csum_skb = NULL;
tmp_csum = 0;
skb_queue_walk(&sk->sk_write_queue, skb) {
tmp_csum = csum_add(tmp_csum, skb->csum);
if (csum_skb)
continue;
len = skb->len - skb_transport_offset(skb);
if (offset >= len) {
offset -= len;
continue;
}
csum_skb = skb;
}
skb = csum_skb;
}
offset += skb_transport_offset(skb);
err = skb_copy_bits(skb, offset, &csum, 2);
if (err < 0) {
ip6_flush_pending_frames(sk);
goto out;
}
/* in case cksum was not initialized */
if (unlikely(csum))
tmp_csum = csum_sub(tmp_csum, csum_unfold(csum));
csum = csum_ipv6_magic(&fl6->saddr, &fl6->daddr,
total_len, fl6->flowi6_proto, tmp_csum);
if (csum == 0 && fl6->flowi6_proto == IPPROTO_UDP)
csum = CSUM_MANGLED_0;
BUG_ON(skb_store_bits(skb, offset, &csum, 2));
send:
err = ip6_push_pending_frames(sk);
out:
return err;
}
static int rawv6_send_hdrinc(struct sock *sk, struct msghdr *msg, int length,
struct flowi6 *fl6, struct dst_entry **dstp,
unsigned int flags, const struct sockcm_cookie *sockc)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct net *net = sock_net(sk);
struct ipv6hdr *iph;
struct sk_buff *skb;
int err;
struct rt6_info *rt = (struct rt6_info *)*dstp;
int hlen = LL_RESERVED_SPACE(rt->dst.dev);
int tlen = rt->dst.dev->needed_tailroom;
if (length > rt->dst.dev->mtu) {
ipv6_local_error(sk, EMSGSIZE, fl6, rt->dst.dev->mtu);
return -EMSGSIZE;
}
if (length < sizeof(struct ipv6hdr))
return -EINVAL;
if (flags&MSG_PROBE)
goto out;
skb = sock_alloc_send_skb(sk,
length + hlen + tlen + 15,
flags & MSG_DONTWAIT, &err);
if (!skb)
goto error;
skb_reserve(skb, hlen);
skb->protocol = htons(ETH_P_IPV6);
skb->priority = READ_ONCE(sk->sk_priority);
skb->mark = sockc->mark;
skb->tstamp = sockc->transmit_time;
skb_put(skb, length);
skb_reset_network_header(skb);
iph = ipv6_hdr(skb);
skb->ip_summed = CHECKSUM_NONE;
skb_setup_tx_timestamp(skb, sockc->tsflags);
if (flags & MSG_CONFIRM)
skb_set_dst_pending_confirm(skb, 1);
skb->transport_header = skb->network_header;
err = memcpy_from_msg(iph, msg, length);
if (err) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
skb_dst_set(skb, &rt->dst);
*dstp = NULL;
/* if egress device is enslaved to an L3 master device pass the
* skb to its handler for processing
*/
skb = l3mdev_ip6_out(sk, skb);
if (unlikely(!skb))
return 0;
/* Acquire rcu_read_lock() in case we need to use rt->rt6i_idev
* in the error path. Since skb has been freed, the dst could
* have been queued for deletion.
*/
rcu_read_lock();
IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len);
err = NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, net, sk, skb,
NULL, rt->dst.dev, dst_output);
if (err > 0)
err = net_xmit_errno(err);
if (err) {
IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
rcu_read_unlock();
goto error_check;
}
rcu_read_unlock();
out:
return 0;
error:
IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
error_check:
if (err == -ENOBUFS && !np->recverr)
err = 0;
return err;
}
struct raw6_frag_vec {
struct msghdr *msg;
int hlen;
char c[4];
};
static int rawv6_probe_proto_opt(struct raw6_frag_vec *rfv, struct flowi6 *fl6)
{
int err = 0;
switch (fl6->flowi6_proto) {
case IPPROTO_ICMPV6:
rfv->hlen = 2;
err = memcpy_from_msg(rfv->c, rfv->msg, rfv->hlen);
if (!err) {
fl6->fl6_icmp_type = rfv->c[0];
fl6->fl6_icmp_code = rfv->c[1];
}
break;
case IPPROTO_MH:
rfv->hlen = 4;
err = memcpy_from_msg(rfv->c, rfv->msg, rfv->hlen);
if (!err)
fl6->fl6_mh_type = rfv->c[2];
}
return err;
}
static int raw6_getfrag(void *from, char *to, int offset, int len, int odd,
struct sk_buff *skb)
{
struct raw6_frag_vec *rfv = from;
if (offset < rfv->hlen) {
int copy = min(rfv->hlen - offset, len);
if (skb->ip_summed == CHECKSUM_PARTIAL)
memcpy(to, rfv->c + offset, copy);
else
skb->csum = csum_block_add(
skb->csum,
csum_partial_copy_nocheck(rfv->c + offset,
to, copy),
odd);
odd = 0;
offset += copy;
to += copy;
len -= copy;
if (!len)
return 0;
}
offset -= rfv->hlen;
return ip_generic_getfrag(rfv->msg, to, offset, len, odd, skb);
}
static int rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions *opt_to_free = NULL;
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct raw6_frag_vec rfv;
struct flowi6 fl6;
struct ipcm6_cookie ipc6;
int addr_len = msg->msg_namelen;
int hdrincl;
u16 proto;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
hdrincl = inet_test_bit(HDRINCL, sk);
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = READ_ONCE(sk->sk_mark);
fl6.flowi6_uid = sk->sk_uid;
ipcm6_init(&ipc6);
ipc6.sockc.tsflags = READ_ONCE(sk->sk_tsflags);
ipc6.sockc.mark = fl6.flowi6_mark;
if (sin6) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (sin6->sin6_family && sin6->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
/* port is the proto value [0..255] carried in nexthdr */
proto = ntohs(sin6->sin6_port);
if (!proto)
proto = inet->inet_num;
else if (proto != inet->inet_num &&
inet->inet_num != IPPROTO_RAW)
return -EINVAL;
if (proto > 255)
return -EINVAL;
daddr = &sin6->sin6_addr;
if (np->sndflow) {
fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (IS_ERR(flowlabel))
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
sin6->sin6_scope_id &&
__ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
fl6.flowi6_oif = sin6->sin6_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
proto = inet->inet_num;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
ipc6.opt = opt;
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, &ipc6);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (IS_ERR(flowlabel))
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (!opt) {
opt = txopt_get(np);
opt_to_free = opt;
}
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = proto;
fl6.flowi6_mark = ipc6.sockc.mark;
if (!hdrincl) {
rfv.msg = msg;
rfv.hlen = 0;
err = rawv6_probe_proto_opt(&rfv, &fl6);
if (err)
goto out;
}
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi_common(&fl6));
if (hdrincl)
fl6.flowi6_flags |= FLOWI_FLAG_KNOWN_NH;
if (ipc6.tclass < 0)
ipc6.tclass = np->tclass;
fl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel);
dst = ip6_dst_lookup_flow(sock_net(sk), sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (ipc6.hlimit < 0)
ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (ipc6.dontfrag < 0)
ipc6.dontfrag = np->dontfrag;
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (hdrincl)
err = rawv6_send_hdrinc(sk, msg, len, &fl6, &dst,
msg->msg_flags, &ipc6.sockc);
else {
ipc6.opt = opt;
lock_sock(sk);
err = ip6_append_data(sk, raw6_getfrag, &rfv,
len, 0, &ipc6, &fl6, (struct rt6_info *)dst,
msg->msg_flags);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = rawv6_push_pending_frames(sk, &fl6, rp);
release_sock(sk);
}
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
txopt_put(opt_to_free);
return err < 0 ? err : len;
do_confirm:
if (msg->msg_flags & MSG_PROBE)
dst_confirm_neigh(dst, &fl6.daddr);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
static int rawv6_seticmpfilter(struct sock *sk, int level, int optname,
sockptr_t optval, int optlen)
{
switch (optname) {
case ICMPV6_FILTER:
if (optlen > sizeof(struct icmp6_filter))
optlen = sizeof(struct icmp6_filter);
if (copy_from_sockptr(&raw6_sk(sk)->filter, optval, optlen))
return -EFAULT;
return 0;
default:
return -ENOPROTOOPT;
}
return 0;
}
static int rawv6_geticmpfilter(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
int len;
switch (optname) {
case ICMPV6_FILTER:
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
if (len > sizeof(struct icmp6_filter))
len = sizeof(struct icmp6_filter);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &raw6_sk(sk)->filter, len))
return -EFAULT;
return 0;
default:
return -ENOPROTOOPT;
}
return 0;
}
static int do_rawv6_setsockopt(struct sock *sk, int level, int optname,
sockptr_t optval, unsigned int optlen)
{
struct raw6_sock *rp = raw6_sk(sk);
int val;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_sockptr(&val, optval, sizeof(val)))
return -EFAULT;
switch (optname) {
case IPV6_HDRINCL:
if (sk->sk_type != SOCK_RAW)
return -EINVAL;
inet_assign_bit(HDRINCL, sk, val);
return 0;
case IPV6_CHECKSUM:
if (inet_sk(sk)->inet_num == IPPROTO_ICMPV6 &&
level == IPPROTO_IPV6) {
/*
* RFC3542 tells that IPV6_CHECKSUM socket
* option in the IPPROTO_IPV6 level is not
* allowed on ICMPv6 sockets.
* If you want to set it, use IPPROTO_RAW
* level IPV6_CHECKSUM socket option
* (Linux extension).
*/
return -EINVAL;
}
/* You may get strange result with a positive odd offset;
RFC2292bis agrees with me. */
if (val > 0 && (val&1))
return -EINVAL;
if (val < 0) {
rp->checksum = 0;
} else {
rp->checksum = 1;
rp->offset = val;
}
return 0;
default:
return -ENOPROTOOPT;
}
}
static int rawv6_setsockopt(struct sock *sk, int level, int optname,
sockptr_t optval, unsigned int optlen)
{
switch (level) {
case SOL_RAW:
break;
case SOL_ICMPV6:
if (inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
return rawv6_seticmpfilter(sk, level, optname, optval, optlen);
case SOL_IPV6:
if (optname == IPV6_CHECKSUM ||
optname == IPV6_HDRINCL)
break;
fallthrough;
default:
return ipv6_setsockopt(sk, level, optname, optval, optlen);
}
return do_rawv6_setsockopt(sk, level, optname, optval, optlen);
}
static int do_rawv6_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
struct raw6_sock *rp = raw6_sk(sk);
int val, len;
if (get_user(len, optlen))
return -EFAULT;
switch (optname) {
case IPV6_HDRINCL:
val = inet_test_bit(HDRINCL, sk);
break;
case IPV6_CHECKSUM:
/*
* We allow getsockopt() for IPPROTO_IPV6-level
* IPV6_CHECKSUM socket option on ICMPv6 sockets
* since RFC3542 is silent about it.
*/
if (rp->checksum == 0)
val = -1;
else
val = rp->offset;
break;
default:
return -ENOPROTOOPT;
}
len = min_t(unsigned int, sizeof(int), len);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
static int rawv6_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
switch (level) {
case SOL_RAW:
break;
case SOL_ICMPV6:
if (inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
return rawv6_geticmpfilter(sk, level, optname, optval, optlen);
case SOL_IPV6:
if (optname == IPV6_CHECKSUM ||
optname == IPV6_HDRINCL)
break;
fallthrough;
default:
return ipv6_getsockopt(sk, level, optname, optval, optlen);
}
return do_rawv6_getsockopt(sk, level, optname, optval, optlen);
}
static int rawv6_ioctl(struct sock *sk, int cmd, int *karg)
{
switch (cmd) {
case SIOCOUTQ: {
*karg = sk_wmem_alloc_get(sk);
return 0;
}
case SIOCINQ: {
struct sk_buff *skb;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
*karg = skb->len;
else
*karg = 0;
spin_unlock_bh(&sk->sk_receive_queue.lock);
return 0;
}
default:
#ifdef CONFIG_IPV6_MROUTE
return ip6mr_ioctl(sk, cmd, karg);
#else
return -ENOIOCTLCMD;
#endif
}
}
#ifdef CONFIG_COMPAT
static int compat_rawv6_ioctl(struct sock *sk, unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ:
case SIOCINQ:
return -ENOIOCTLCMD;
default:
#ifdef CONFIG_IPV6_MROUTE
return ip6mr_compat_ioctl(sk, cmd, compat_ptr(arg));
#else
return -ENOIOCTLCMD;
#endif
}
}
#endif
static void rawv6_close(struct sock *sk, long timeout)
{
if (inet_sk(sk)->inet_num == IPPROTO_RAW)
ip6_ra_control(sk, -1);
ip6mr_sk_done(sk);
sk_common_release(sk);
}
static void raw6_destroy(struct sock *sk)
{
lock_sock(sk);
ip6_flush_pending_frames(sk);
release_sock(sk);
}
static int rawv6_init_sk(struct sock *sk)
{
struct raw6_sock *rp = raw6_sk(sk);
switch (inet_sk(sk)->inet_num) {
case IPPROTO_ICMPV6:
rp->checksum = 1;
rp->offset = 2;
break;
case IPPROTO_MH:
rp->checksum = 1;
rp->offset = 4;
break;
default:
break;
}
return 0;
}
struct proto rawv6_prot = {
.name = "RAWv6",
.owner = THIS_MODULE,
.close = rawv6_close,
.destroy = raw6_destroy,
.connect = ip6_datagram_connect_v6_only,
.disconnect = __udp_disconnect,
.ioctl = rawv6_ioctl,
.init = rawv6_init_sk,
.setsockopt = rawv6_setsockopt,
.getsockopt = rawv6_getsockopt,
.sendmsg = rawv6_sendmsg,
.recvmsg = rawv6_recvmsg,
.bind = rawv6_bind,
.backlog_rcv = rawv6_rcv_skb,
.hash = raw_hash_sk,
.unhash = raw_unhash_sk,
.obj_size = sizeof(struct raw6_sock),
.ipv6_pinfo_offset = offsetof(struct raw6_sock, inet6),
.useroffset = offsetof(struct raw6_sock, filter),
.usersize = sizeof_field(struct raw6_sock, filter),
.h.raw_hash = &raw_v6_hashinfo,
#ifdef CONFIG_COMPAT
.compat_ioctl = compat_rawv6_ioctl,
#endif
.diag_destroy = raw_abort,
};
#ifdef CONFIG_PROC_FS
static int raw6_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN) {
seq_puts(seq, IPV6_SEQ_DGRAM_HEADER);
} else {
struct sock *sp = v;
__u16 srcp = inet_sk(sp)->inet_num;
ip6_dgram_sock_seq_show(seq, v, srcp, 0,
raw_seq_private(seq)->bucket);
}
return 0;
}
static const struct seq_operations raw6_seq_ops = {
.start = raw_seq_start,
.next = raw_seq_next,
.stop = raw_seq_stop,
.show = raw6_seq_show,
};
static int __net_init raw6_init_net(struct net *net)
{
if (!proc_create_net_data("raw6", 0444, net->proc_net, &raw6_seq_ops,
sizeof(struct raw_iter_state), &raw_v6_hashinfo))
return -ENOMEM;
return 0;
}
static void __net_exit raw6_exit_net(struct net *net)
{
remove_proc_entry("raw6", net->proc_net);
}
static struct pernet_operations raw6_net_ops = {
.init = raw6_init_net,
.exit = raw6_exit_net,
};
int __init raw6_proc_init(void)
{
return register_pernet_subsys(&raw6_net_ops);
}
void raw6_proc_exit(void)
{
unregister_pernet_subsys(&raw6_net_ops);
}
#endif /* CONFIG_PROC_FS */
/* Same as inet6_dgram_ops, sans udp_poll. */
const struct proto_ops inet6_sockraw_ops = {
.family = PF_INET6,
.owner = THIS_MODULE,
.release = inet6_release,
.bind = inet6_bind,
.connect = inet_dgram_connect, /* ok */
.socketpair = sock_no_socketpair, /* a do nothing */
.accept = sock_no_accept, /* a do nothing */
.getname = inet6_getname,
.poll = datagram_poll, /* ok */
.ioctl = inet6_ioctl, /* must change */
.gettstamp = sock_gettstamp,
.listen = sock_no_listen, /* ok */
.shutdown = inet_shutdown, /* ok */
.setsockopt = sock_common_setsockopt, /* ok */
.getsockopt = sock_common_getsockopt, /* ok */
.sendmsg = inet_sendmsg, /* ok */
.recvmsg = sock_common_recvmsg, /* ok */
.mmap = sock_no_mmap,
#ifdef CONFIG_COMPAT
.compat_ioctl = inet6_compat_ioctl,
#endif
};
static struct inet_protosw rawv6_protosw = {
.type = SOCK_RAW,
.protocol = IPPROTO_IP, /* wild card */
.prot = &rawv6_prot,
.ops = &inet6_sockraw_ops,
.flags = INET_PROTOSW_REUSE,
};
int __init rawv6_init(void)
{
return inet6_register_protosw(&rawv6_protosw);
}
void rawv6_exit(void)
{
inet6_unregister_protosw(&rawv6_protosw);
}
| linux-master | net/ipv6/raw.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Extension Header handling for IPv6
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <[email protected]>
* Andi Kleen <[email protected]>
* Alexey Kuznetsov <[email protected]>
*/
/* Changes:
* yoshfuji : ensure not to overrun while parsing
* tlv options.
* Mitsuru KANDA @USAGI and: Remove ipv6_parse_exthdrs().
* YOSHIFUJI Hideaki @USAGI Register inbound extension header
* handlers as inet6_protocol{}.
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/icmpv6.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <net/dst.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/protocol.h>
#include <net/transp_v6.h>
#include <net/rawv6.h>
#include <net/ndisc.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/calipso.h>
#if IS_ENABLED(CONFIG_IPV6_MIP6)
#include <net/xfrm.h>
#endif
#include <linux/seg6.h>
#include <net/seg6.h>
#ifdef CONFIG_IPV6_SEG6_HMAC
#include <net/seg6_hmac.h>
#endif
#include <net/rpl.h>
#include <linux/ioam6.h>
#include <net/ioam6.h>
#include <net/dst_metadata.h>
#include <linux/uaccess.h>
/*********************
Generic functions
*********************/
/* An unknown option is detected, decide what to do */
static bool ip6_tlvopt_unknown(struct sk_buff *skb, int optoff,
bool disallow_unknowns)
{
if (disallow_unknowns) {
/* If unknown TLVs are disallowed by configuration
* then always silently drop packet. Note this also
* means no ICMP parameter problem is sent which
* could be a good property to mitigate a reflection DOS
* attack.
*/
goto drop;
}
switch ((skb_network_header(skb)[optoff] & 0xC0) >> 6) {
case 0: /* ignore */
return true;
case 1: /* drop packet */
break;
case 3: /* Send ICMP if not a multicast address and drop packet */
/* Actually, it is redundant check. icmp_send
will recheck in any case.
*/
if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr))
break;
fallthrough;
case 2: /* send ICMP PARM PROB regardless and drop packet */
icmpv6_param_prob_reason(skb, ICMPV6_UNK_OPTION, optoff,
SKB_DROP_REASON_UNHANDLED_PROTO);
return false;
}
drop:
kfree_skb_reason(skb, SKB_DROP_REASON_UNHANDLED_PROTO);
return false;
}
static bool ipv6_hop_ra(struct sk_buff *skb, int optoff);
static bool ipv6_hop_ioam(struct sk_buff *skb, int optoff);
static bool ipv6_hop_jumbo(struct sk_buff *skb, int optoff);
static bool ipv6_hop_calipso(struct sk_buff *skb, int optoff);
#if IS_ENABLED(CONFIG_IPV6_MIP6)
static bool ipv6_dest_hao(struct sk_buff *skb, int optoff);
#endif
/* Parse tlv encoded option header (hop-by-hop or destination) */
static bool ip6_parse_tlv(bool hopbyhop,
struct sk_buff *skb,
int max_count)
{
int len = (skb_transport_header(skb)[1] + 1) << 3;
const unsigned char *nh = skb_network_header(skb);
int off = skb_network_header_len(skb);
bool disallow_unknowns = false;
int tlv_count = 0;
int padlen = 0;
if (unlikely(max_count < 0)) {
disallow_unknowns = true;
max_count = -max_count;
}
off += 2;
len -= 2;
while (len > 0) {
int optlen, i;
if (nh[off] == IPV6_TLV_PAD1) {
padlen++;
if (padlen > 7)
goto bad;
off++;
len--;
continue;
}
if (len < 2)
goto bad;
optlen = nh[off + 1] + 2;
if (optlen > len)
goto bad;
if (nh[off] == IPV6_TLV_PADN) {
/* RFC 2460 states that the purpose of PadN is
* to align the containing header to multiples
* of 8. 7 is therefore the highest valid value.
* See also RFC 4942, Section 2.1.9.5.
*/
padlen += optlen;
if (padlen > 7)
goto bad;
/* RFC 4942 recommends receiving hosts to
* actively check PadN payload to contain
* only zeroes.
*/
for (i = 2; i < optlen; i++) {
if (nh[off + i] != 0)
goto bad;
}
} else {
tlv_count++;
if (tlv_count > max_count)
goto bad;
if (hopbyhop) {
switch (nh[off]) {
case IPV6_TLV_ROUTERALERT:
if (!ipv6_hop_ra(skb, off))
return false;
break;
case IPV6_TLV_IOAM:
if (!ipv6_hop_ioam(skb, off))
return false;
break;
case IPV6_TLV_JUMBO:
if (!ipv6_hop_jumbo(skb, off))
return false;
break;
case IPV6_TLV_CALIPSO:
if (!ipv6_hop_calipso(skb, off))
return false;
break;
default:
if (!ip6_tlvopt_unknown(skb, off,
disallow_unknowns))
return false;
break;
}
} else {
switch (nh[off]) {
#if IS_ENABLED(CONFIG_IPV6_MIP6)
case IPV6_TLV_HAO:
if (!ipv6_dest_hao(skb, off))
return false;
break;
#endif
default:
if (!ip6_tlvopt_unknown(skb, off,
disallow_unknowns))
return false;
break;
}
}
padlen = 0;
}
off += optlen;
len -= optlen;
}
if (len == 0)
return true;
bad:
kfree_skb_reason(skb, SKB_DROP_REASON_IP_INHDR);
return false;
}
/*****************************
Destination options header.
*****************************/
#if IS_ENABLED(CONFIG_IPV6_MIP6)
static bool ipv6_dest_hao(struct sk_buff *skb, int optoff)
{
struct ipv6_destopt_hao *hao;
struct inet6_skb_parm *opt = IP6CB(skb);
struct ipv6hdr *ipv6h = ipv6_hdr(skb);
SKB_DR(reason);
int ret;
if (opt->dsthao) {
net_dbg_ratelimited("hao duplicated\n");
goto discard;
}
opt->dsthao = opt->dst1;
opt->dst1 = 0;
hao = (struct ipv6_destopt_hao *)(skb_network_header(skb) + optoff);
if (hao->length != 16) {
net_dbg_ratelimited("hao invalid option length = %d\n",
hao->length);
SKB_DR_SET(reason, IP_INHDR);
goto discard;
}
if (!(ipv6_addr_type(&hao->addr) & IPV6_ADDR_UNICAST)) {
net_dbg_ratelimited("hao is not an unicast addr: %pI6\n",
&hao->addr);
SKB_DR_SET(reason, INVALID_PROTO);
goto discard;
}
ret = xfrm6_input_addr(skb, (xfrm_address_t *)&ipv6h->daddr,
(xfrm_address_t *)&hao->addr, IPPROTO_DSTOPTS);
if (unlikely(ret < 0)) {
SKB_DR_SET(reason, XFRM_POLICY);
goto discard;
}
if (skb_cloned(skb)) {
if (pskb_expand_head(skb, 0, 0, GFP_ATOMIC))
goto discard;
/* update all variable using below by copied skbuff */
hao = (struct ipv6_destopt_hao *)(skb_network_header(skb) +
optoff);
ipv6h = ipv6_hdr(skb);
}
if (skb->ip_summed == CHECKSUM_COMPLETE)
skb->ip_summed = CHECKSUM_NONE;
swap(ipv6h->saddr, hao->addr);
if (skb->tstamp == 0)
__net_timestamp(skb);
return true;
discard:
kfree_skb_reason(skb, reason);
return false;
}
#endif
static int ipv6_destopt_rcv(struct sk_buff *skb)
{
struct inet6_dev *idev = __in6_dev_get(skb->dev);
struct inet6_skb_parm *opt = IP6CB(skb);
#if IS_ENABLED(CONFIG_IPV6_MIP6)
__u16 dstbuf;
#endif
struct dst_entry *dst = skb_dst(skb);
struct net *net = dev_net(skb->dev);
int extlen;
if (!pskb_may_pull(skb, skb_transport_offset(skb) + 8) ||
!pskb_may_pull(skb, (skb_transport_offset(skb) +
((skb_transport_header(skb)[1] + 1) << 3)))) {
__IP6_INC_STATS(dev_net(dst->dev), idev,
IPSTATS_MIB_INHDRERRORS);
fail_and_free:
kfree_skb(skb);
return -1;
}
extlen = (skb_transport_header(skb)[1] + 1) << 3;
if (extlen > net->ipv6.sysctl.max_dst_opts_len)
goto fail_and_free;
opt->lastopt = opt->dst1 = skb_network_header_len(skb);
#if IS_ENABLED(CONFIG_IPV6_MIP6)
dstbuf = opt->dst1;
#endif
if (ip6_parse_tlv(false, skb, net->ipv6.sysctl.max_dst_opts_cnt)) {
skb->transport_header += extlen;
opt = IP6CB(skb);
#if IS_ENABLED(CONFIG_IPV6_MIP6)
opt->nhoff = dstbuf;
#else
opt->nhoff = opt->dst1;
#endif
return 1;
}
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
return -1;
}
static void seg6_update_csum(struct sk_buff *skb)
{
struct ipv6_sr_hdr *hdr;
struct in6_addr *addr;
__be32 from, to;
/* srh is at transport offset and seg_left is already decremented
* but daddr is not yet updated with next segment
*/
hdr = (struct ipv6_sr_hdr *)skb_transport_header(skb);
addr = hdr->segments + hdr->segments_left;
hdr->segments_left++;
from = *(__be32 *)hdr;
hdr->segments_left--;
to = *(__be32 *)hdr;
/* update skb csum with diff resulting from seg_left decrement */
update_csum_diff4(skb, from, to);
/* compute csum diff between current and next segment and update */
update_csum_diff16(skb, (__be32 *)(&ipv6_hdr(skb)->daddr),
(__be32 *)addr);
}
static int ipv6_srh_rcv(struct sk_buff *skb)
{
struct inet6_skb_parm *opt = IP6CB(skb);
struct net *net = dev_net(skb->dev);
struct ipv6_sr_hdr *hdr;
struct inet6_dev *idev;
struct in6_addr *addr;
int accept_seg6;
hdr = (struct ipv6_sr_hdr *)skb_transport_header(skb);
idev = __in6_dev_get(skb->dev);
accept_seg6 = net->ipv6.devconf_all->seg6_enabled;
if (accept_seg6 > idev->cnf.seg6_enabled)
accept_seg6 = idev->cnf.seg6_enabled;
if (!accept_seg6) {
kfree_skb(skb);
return -1;
}
#ifdef CONFIG_IPV6_SEG6_HMAC
if (!seg6_hmac_validate_skb(skb)) {
kfree_skb(skb);
return -1;
}
#endif
looped_back:
if (hdr->segments_left == 0) {
if (hdr->nexthdr == NEXTHDR_IPV6 || hdr->nexthdr == NEXTHDR_IPV4) {
int offset = (hdr->hdrlen + 1) << 3;
skb_postpull_rcsum(skb, skb_network_header(skb),
skb_network_header_len(skb));
skb_pull(skb, offset);
skb_postpull_rcsum(skb, skb_transport_header(skb),
offset);
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb->encapsulation = 0;
if (hdr->nexthdr == NEXTHDR_IPV4)
skb->protocol = htons(ETH_P_IP);
__skb_tunnel_rx(skb, skb->dev, net);
netif_rx(skb);
return -1;
}
opt->srcrt = skb_network_header_len(skb);
opt->lastopt = opt->srcrt;
skb->transport_header += (hdr->hdrlen + 1) << 3;
opt->nhoff = (&hdr->nexthdr) - skb_network_header(skb);
return 1;
}
if (hdr->segments_left >= (hdr->hdrlen >> 1)) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
((&hdr->segments_left) -
skb_network_header(skb)));
return -1;
}
if (skb_cloned(skb)) {
if (pskb_expand_head(skb, 0, 0, GFP_ATOMIC)) {
__IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return -1;
}
hdr = (struct ipv6_sr_hdr *)skb_transport_header(skb);
}
hdr->segments_left--;
addr = hdr->segments + hdr->segments_left;
skb_push(skb, sizeof(struct ipv6hdr));
if (skb->ip_summed == CHECKSUM_COMPLETE)
seg6_update_csum(skb);
ipv6_hdr(skb)->daddr = *addr;
ip6_route_input(skb);
if (skb_dst(skb)->error) {
dst_input(skb);
return -1;
}
if (skb_dst(skb)->dev->flags & IFF_LOOPBACK) {
if (ipv6_hdr(skb)->hop_limit <= 1) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
icmpv6_send(skb, ICMPV6_TIME_EXCEED,
ICMPV6_EXC_HOPLIMIT, 0);
kfree_skb(skb);
return -1;
}
ipv6_hdr(skb)->hop_limit--;
skb_pull(skb, sizeof(struct ipv6hdr));
goto looped_back;
}
dst_input(skb);
return -1;
}
static int ipv6_rpl_srh_rcv(struct sk_buff *skb)
{
struct ipv6_rpl_sr_hdr *hdr, *ohdr, *chdr;
struct inet6_skb_parm *opt = IP6CB(skb);
struct net *net = dev_net(skb->dev);
struct inet6_dev *idev;
struct ipv6hdr *oldhdr;
unsigned char *buf;
int accept_rpl_seg;
int i, err;
u64 n = 0;
u32 r;
idev = __in6_dev_get(skb->dev);
accept_rpl_seg = net->ipv6.devconf_all->rpl_seg_enabled;
if (accept_rpl_seg > idev->cnf.rpl_seg_enabled)
accept_rpl_seg = idev->cnf.rpl_seg_enabled;
if (!accept_rpl_seg) {
kfree_skb(skb);
return -1;
}
looped_back:
hdr = (struct ipv6_rpl_sr_hdr *)skb_transport_header(skb);
if (hdr->segments_left == 0) {
if (hdr->nexthdr == NEXTHDR_IPV6) {
int offset = (hdr->hdrlen + 1) << 3;
skb_postpull_rcsum(skb, skb_network_header(skb),
skb_network_header_len(skb));
skb_pull(skb, offset);
skb_postpull_rcsum(skb, skb_transport_header(skb),
offset);
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb->encapsulation = 0;
__skb_tunnel_rx(skb, skb->dev, net);
netif_rx(skb);
return -1;
}
opt->srcrt = skb_network_header_len(skb);
opt->lastopt = opt->srcrt;
skb->transport_header += (hdr->hdrlen + 1) << 3;
opt->nhoff = (&hdr->nexthdr) - skb_network_header(skb);
return 1;
}
n = (hdr->hdrlen << 3) - hdr->pad - (16 - hdr->cmpre);
r = do_div(n, (16 - hdr->cmpri));
/* checks if calculation was without remainder and n fits into
* unsigned char which is segments_left field. Should not be
* higher than that.
*/
if (r || (n + 1) > 255) {
kfree_skb(skb);
return -1;
}
if (hdr->segments_left > n + 1) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
((&hdr->segments_left) -
skb_network_header(skb)));
return -1;
}
hdr->segments_left--;
i = n - hdr->segments_left;
buf = kcalloc(struct_size(hdr, segments.addr, n + 2), 2, GFP_ATOMIC);
if (unlikely(!buf)) {
kfree_skb(skb);
return -1;
}
ohdr = (struct ipv6_rpl_sr_hdr *)buf;
ipv6_rpl_srh_decompress(ohdr, hdr, &ipv6_hdr(skb)->daddr, n);
chdr = (struct ipv6_rpl_sr_hdr *)(buf + ((ohdr->hdrlen + 1) << 3));
if (ipv6_addr_is_multicast(&ohdr->rpl_segaddr[i])) {
kfree_skb(skb);
kfree(buf);
return -1;
}
err = ipv6_chk_rpl_srh_loop(net, ohdr->rpl_segaddr, n + 1);
if (err) {
icmpv6_send(skb, ICMPV6_PARAMPROB, 0, 0);
kfree_skb(skb);
kfree(buf);
return -1;
}
swap(ipv6_hdr(skb)->daddr, ohdr->rpl_segaddr[i]);
ipv6_rpl_srh_compress(chdr, ohdr, &ipv6_hdr(skb)->daddr, n);
oldhdr = ipv6_hdr(skb);
skb_pull(skb, ((hdr->hdrlen + 1) << 3));
skb_postpull_rcsum(skb, oldhdr,
sizeof(struct ipv6hdr) + ((hdr->hdrlen + 1) << 3));
if (unlikely(!hdr->segments_left)) {
if (pskb_expand_head(skb, sizeof(struct ipv6hdr) + ((chdr->hdrlen + 1) << 3), 0,
GFP_ATOMIC)) {
__IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
kfree(buf);
return -1;
}
oldhdr = ipv6_hdr(skb);
}
skb_push(skb, ((chdr->hdrlen + 1) << 3) + sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
skb_mac_header_rebuild(skb);
skb_set_transport_header(skb, sizeof(struct ipv6hdr));
memmove(ipv6_hdr(skb), oldhdr, sizeof(struct ipv6hdr));
memcpy(skb_transport_header(skb), chdr, (chdr->hdrlen + 1) << 3);
ipv6_hdr(skb)->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
skb_postpush_rcsum(skb, ipv6_hdr(skb),
sizeof(struct ipv6hdr) + ((chdr->hdrlen + 1) << 3));
kfree(buf);
ip6_route_input(skb);
if (skb_dst(skb)->error) {
dst_input(skb);
return -1;
}
if (skb_dst(skb)->dev->flags & IFF_LOOPBACK) {
if (ipv6_hdr(skb)->hop_limit <= 1) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
icmpv6_send(skb, ICMPV6_TIME_EXCEED,
ICMPV6_EXC_HOPLIMIT, 0);
kfree_skb(skb);
return -1;
}
ipv6_hdr(skb)->hop_limit--;
skb_pull(skb, sizeof(struct ipv6hdr));
goto looped_back;
}
dst_input(skb);
return -1;
}
/********************************
Routing header.
********************************/
/* called with rcu_read_lock() */
static int ipv6_rthdr_rcv(struct sk_buff *skb)
{
struct inet6_dev *idev = __in6_dev_get(skb->dev);
struct inet6_skb_parm *opt = IP6CB(skb);
struct in6_addr *addr = NULL;
int n, i;
struct ipv6_rt_hdr *hdr;
struct rt0_hdr *rthdr;
struct net *net = dev_net(skb->dev);
int accept_source_route = net->ipv6.devconf_all->accept_source_route;
if (idev && accept_source_route > idev->cnf.accept_source_route)
accept_source_route = idev->cnf.accept_source_route;
if (!pskb_may_pull(skb, skb_transport_offset(skb) + 8) ||
!pskb_may_pull(skb, (skb_transport_offset(skb) +
((skb_transport_header(skb)[1] + 1) << 3)))) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
kfree_skb(skb);
return -1;
}
hdr = (struct ipv6_rt_hdr *)skb_transport_header(skb);
if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr) ||
skb->pkt_type != PACKET_HOST) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INADDRERRORS);
kfree_skb(skb);
return -1;
}
switch (hdr->type) {
case IPV6_SRCRT_TYPE_4:
/* segment routing */
return ipv6_srh_rcv(skb);
case IPV6_SRCRT_TYPE_3:
/* rpl segment routing */
return ipv6_rpl_srh_rcv(skb);
default:
break;
}
looped_back:
if (hdr->segments_left == 0) {
switch (hdr->type) {
#if IS_ENABLED(CONFIG_IPV6_MIP6)
case IPV6_SRCRT_TYPE_2:
/* Silently discard type 2 header unless it was
* processed by own
*/
if (!addr) {
__IP6_INC_STATS(net, idev,
IPSTATS_MIB_INADDRERRORS);
kfree_skb(skb);
return -1;
}
break;
#endif
default:
break;
}
opt->lastopt = opt->srcrt = skb_network_header_len(skb);
skb->transport_header += (hdr->hdrlen + 1) << 3;
opt->dst0 = opt->dst1;
opt->dst1 = 0;
opt->nhoff = (&hdr->nexthdr) - skb_network_header(skb);
return 1;
}
switch (hdr->type) {
#if IS_ENABLED(CONFIG_IPV6_MIP6)
case IPV6_SRCRT_TYPE_2:
if (accept_source_route < 0)
goto unknown_rh;
/* Silently discard invalid RTH type 2 */
if (hdr->hdrlen != 2 || hdr->segments_left != 1) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
kfree_skb(skb);
return -1;
}
break;
#endif
default:
goto unknown_rh;
}
/*
* This is the routing header forwarding algorithm from
* RFC 2460, page 16.
*/
n = hdr->hdrlen >> 1;
if (hdr->segments_left > n) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
((&hdr->segments_left) -
skb_network_header(skb)));
return -1;
}
/* We are about to mangle packet header. Be careful!
Do not damage packets queued somewhere.
*/
if (skb_cloned(skb)) {
/* the copy is a forwarded packet */
if (pskb_expand_head(skb, 0, 0, GFP_ATOMIC)) {
__IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return -1;
}
hdr = (struct ipv6_rt_hdr *)skb_transport_header(skb);
}
if (skb->ip_summed == CHECKSUM_COMPLETE)
skb->ip_summed = CHECKSUM_NONE;
i = n - --hdr->segments_left;
rthdr = (struct rt0_hdr *) hdr;
addr = rthdr->addr;
addr += i - 1;
switch (hdr->type) {
#if IS_ENABLED(CONFIG_IPV6_MIP6)
case IPV6_SRCRT_TYPE_2:
if (xfrm6_input_addr(skb, (xfrm_address_t *)addr,
(xfrm_address_t *)&ipv6_hdr(skb)->saddr,
IPPROTO_ROUTING) < 0) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INADDRERRORS);
kfree_skb(skb);
return -1;
}
if (!ipv6_chk_home_addr(dev_net(skb_dst(skb)->dev), addr)) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INADDRERRORS);
kfree_skb(skb);
return -1;
}
break;
#endif
default:
break;
}
if (ipv6_addr_is_multicast(addr)) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INADDRERRORS);
kfree_skb(skb);
return -1;
}
swap(*addr, ipv6_hdr(skb)->daddr);
ip6_route_input(skb);
if (skb_dst(skb)->error) {
skb_push(skb, skb->data - skb_network_header(skb));
dst_input(skb);
return -1;
}
if (skb_dst(skb)->dev->flags&IFF_LOOPBACK) {
if (ipv6_hdr(skb)->hop_limit <= 1) {
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT,
0);
kfree_skb(skb);
return -1;
}
ipv6_hdr(skb)->hop_limit--;
goto looped_back;
}
skb_push(skb, skb->data - skb_network_header(skb));
dst_input(skb);
return -1;
unknown_rh:
__IP6_INC_STATS(net, idev, IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
(&hdr->type) - skb_network_header(skb));
return -1;
}
static const struct inet6_protocol rthdr_protocol = {
.handler = ipv6_rthdr_rcv,
.flags = INET6_PROTO_NOPOLICY,
};
static const struct inet6_protocol destopt_protocol = {
.handler = ipv6_destopt_rcv,
.flags = INET6_PROTO_NOPOLICY,
};
static const struct inet6_protocol nodata_protocol = {
.handler = dst_discard,
.flags = INET6_PROTO_NOPOLICY,
};
int __init ipv6_exthdrs_init(void)
{
int ret;
ret = inet6_add_protocol(&rthdr_protocol, IPPROTO_ROUTING);
if (ret)
goto out;
ret = inet6_add_protocol(&destopt_protocol, IPPROTO_DSTOPTS);
if (ret)
goto out_rthdr;
ret = inet6_add_protocol(&nodata_protocol, IPPROTO_NONE);
if (ret)
goto out_destopt;
out:
return ret;
out_destopt:
inet6_del_protocol(&destopt_protocol, IPPROTO_DSTOPTS);
out_rthdr:
inet6_del_protocol(&rthdr_protocol, IPPROTO_ROUTING);
goto out;
};
void ipv6_exthdrs_exit(void)
{
inet6_del_protocol(&nodata_protocol, IPPROTO_NONE);
inet6_del_protocol(&destopt_protocol, IPPROTO_DSTOPTS);
inet6_del_protocol(&rthdr_protocol, IPPROTO_ROUTING);
}
/**********************************
Hop-by-hop options.
**********************************/
/*
* Note: we cannot rely on skb_dst(skb) before we assign it in ip6_route_input().
*/
static inline struct net *ipv6_skb_net(struct sk_buff *skb)
{
return skb_dst(skb) ? dev_net(skb_dst(skb)->dev) : dev_net(skb->dev);
}
/* Router Alert as of RFC 2711 */
static bool ipv6_hop_ra(struct sk_buff *skb, int optoff)
{
const unsigned char *nh = skb_network_header(skb);
if (nh[optoff + 1] == 2) {
IP6CB(skb)->flags |= IP6SKB_ROUTERALERT;
memcpy(&IP6CB(skb)->ra, nh + optoff + 2, sizeof(IP6CB(skb)->ra));
return true;
}
net_dbg_ratelimited("ipv6_hop_ra: wrong RA length %d\n",
nh[optoff + 1]);
kfree_skb_reason(skb, SKB_DROP_REASON_IP_INHDR);
return false;
}
/* IOAM */
static bool ipv6_hop_ioam(struct sk_buff *skb, int optoff)
{
struct ioam6_trace_hdr *trace;
struct ioam6_namespace *ns;
struct ioam6_hdr *hdr;
/* Bad alignment (must be 4n-aligned) */
if (optoff & 3)
goto drop;
/* Ignore if IOAM is not enabled on ingress */
if (!__in6_dev_get(skb->dev)->cnf.ioam6_enabled)
goto ignore;
/* Truncated Option header */
hdr = (struct ioam6_hdr *)(skb_network_header(skb) + optoff);
if (hdr->opt_len < 2)
goto drop;
switch (hdr->type) {
case IOAM6_TYPE_PREALLOC:
/* Truncated Pre-allocated Trace header */
if (hdr->opt_len < 2 + sizeof(*trace))
goto drop;
/* Malformed Pre-allocated Trace header */
trace = (struct ioam6_trace_hdr *)((u8 *)hdr + sizeof(*hdr));
if (hdr->opt_len < 2 + sizeof(*trace) + trace->remlen * 4)
goto drop;
/* Ignore if the IOAM namespace is unknown */
ns = ioam6_namespace(ipv6_skb_net(skb), trace->namespace_id);
if (!ns)
goto ignore;
if (!skb_valid_dst(skb))
ip6_route_input(skb);
ioam6_fill_trace_data(skb, ns, trace, true);
break;
default:
break;
}
ignore:
return true;
drop:
kfree_skb_reason(skb, SKB_DROP_REASON_IP_INHDR);
return false;
}
/* Jumbo payload */
static bool ipv6_hop_jumbo(struct sk_buff *skb, int optoff)
{
const unsigned char *nh = skb_network_header(skb);
SKB_DR(reason);
u32 pkt_len;
if (nh[optoff + 1] != 4 || (optoff & 3) != 2) {
net_dbg_ratelimited("ipv6_hop_jumbo: wrong jumbo opt length/alignment %d\n",
nh[optoff+1]);
SKB_DR_SET(reason, IP_INHDR);
goto drop;
}
pkt_len = ntohl(*(__be32 *)(nh + optoff + 2));
if (pkt_len <= IPV6_MAXPLEN) {
icmpv6_param_prob_reason(skb, ICMPV6_HDR_FIELD, optoff + 2,
SKB_DROP_REASON_IP_INHDR);
return false;
}
if (ipv6_hdr(skb)->payload_len) {
icmpv6_param_prob_reason(skb, ICMPV6_HDR_FIELD, optoff,
SKB_DROP_REASON_IP_INHDR);
return false;
}
if (pkt_len > skb->len - sizeof(struct ipv6hdr)) {
SKB_DR_SET(reason, PKT_TOO_SMALL);
goto drop;
}
if (pskb_trim_rcsum(skb, pkt_len + sizeof(struct ipv6hdr)))
goto drop;
IP6CB(skb)->flags |= IP6SKB_JUMBOGRAM;
return true;
drop:
kfree_skb_reason(skb, reason);
return false;
}
/* CALIPSO RFC 5570 */
static bool ipv6_hop_calipso(struct sk_buff *skb, int optoff)
{
const unsigned char *nh = skb_network_header(skb);
if (nh[optoff + 1] < 8)
goto drop;
if (nh[optoff + 6] * 4 + 8 > nh[optoff + 1])
goto drop;
if (!calipso_validate(skb, nh + optoff))
goto drop;
return true;
drop:
kfree_skb_reason(skb, SKB_DROP_REASON_IP_INHDR);
return false;
}
int ipv6_parse_hopopts(struct sk_buff *skb)
{
struct inet6_skb_parm *opt = IP6CB(skb);
struct net *net = dev_net(skb->dev);
int extlen;
/*
* skb_network_header(skb) is equal to skb->data, and
* skb_network_header_len(skb) is always equal to
* sizeof(struct ipv6hdr) by definition of
* hop-by-hop options.
*/
if (!pskb_may_pull(skb, sizeof(struct ipv6hdr) + 8) ||
!pskb_may_pull(skb, (sizeof(struct ipv6hdr) +
((skb_transport_header(skb)[1] + 1) << 3)))) {
fail_and_free:
kfree_skb(skb);
return -1;
}
extlen = (skb_transport_header(skb)[1] + 1) << 3;
if (extlen > net->ipv6.sysctl.max_hbh_opts_len)
goto fail_and_free;
opt->flags |= IP6SKB_HOPBYHOP;
if (ip6_parse_tlv(true, skb, net->ipv6.sysctl.max_hbh_opts_cnt)) {
skb->transport_header += extlen;
opt = IP6CB(skb);
opt->nhoff = sizeof(struct ipv6hdr);
return 1;
}
return -1;
}
/*
* Creating outbound headers.
*
* "build" functions work when skb is filled from head to tail (datagram)
* "push" functions work when headers are added from tail to head (tcp)
*
* In both cases we assume, that caller reserved enough room
* for headers.
*/
static void ipv6_push_rthdr0(struct sk_buff *skb, u8 *proto,
struct ipv6_rt_hdr *opt,
struct in6_addr **addr_p, struct in6_addr *saddr)
{
struct rt0_hdr *phdr, *ihdr;
int hops;
ihdr = (struct rt0_hdr *) opt;
phdr = skb_push(skb, (ihdr->rt_hdr.hdrlen + 1) << 3);
memcpy(phdr, ihdr, sizeof(struct rt0_hdr));
hops = ihdr->rt_hdr.hdrlen >> 1;
if (hops > 1)
memcpy(phdr->addr, ihdr->addr + 1,
(hops - 1) * sizeof(struct in6_addr));
phdr->addr[hops - 1] = **addr_p;
*addr_p = ihdr->addr;
phdr->rt_hdr.nexthdr = *proto;
*proto = NEXTHDR_ROUTING;
}
static void ipv6_push_rthdr4(struct sk_buff *skb, u8 *proto,
struct ipv6_rt_hdr *opt,
struct in6_addr **addr_p, struct in6_addr *saddr)
{
struct ipv6_sr_hdr *sr_phdr, *sr_ihdr;
int plen, hops;
sr_ihdr = (struct ipv6_sr_hdr *)opt;
plen = (sr_ihdr->hdrlen + 1) << 3;
sr_phdr = skb_push(skb, plen);
memcpy(sr_phdr, sr_ihdr, sizeof(struct ipv6_sr_hdr));
hops = sr_ihdr->first_segment + 1;
memcpy(sr_phdr->segments + 1, sr_ihdr->segments + 1,
(hops - 1) * sizeof(struct in6_addr));
sr_phdr->segments[0] = **addr_p;
*addr_p = &sr_ihdr->segments[sr_ihdr->segments_left];
if (sr_ihdr->hdrlen > hops * 2) {
int tlvs_offset, tlvs_length;
tlvs_offset = (1 + hops * 2) << 3;
tlvs_length = (sr_ihdr->hdrlen - hops * 2) << 3;
memcpy((char *)sr_phdr + tlvs_offset,
(char *)sr_ihdr + tlvs_offset, tlvs_length);
}
#ifdef CONFIG_IPV6_SEG6_HMAC
if (sr_has_hmac(sr_phdr)) {
struct net *net = NULL;
if (skb->dev)
net = dev_net(skb->dev);
else if (skb->sk)
net = sock_net(skb->sk);
WARN_ON(!net);
if (net)
seg6_push_hmac(net, saddr, sr_phdr);
}
#endif
sr_phdr->nexthdr = *proto;
*proto = NEXTHDR_ROUTING;
}
static void ipv6_push_rthdr(struct sk_buff *skb, u8 *proto,
struct ipv6_rt_hdr *opt,
struct in6_addr **addr_p, struct in6_addr *saddr)
{
switch (opt->type) {
case IPV6_SRCRT_TYPE_0:
case IPV6_SRCRT_STRICT:
case IPV6_SRCRT_TYPE_2:
ipv6_push_rthdr0(skb, proto, opt, addr_p, saddr);
break;
case IPV6_SRCRT_TYPE_4:
ipv6_push_rthdr4(skb, proto, opt, addr_p, saddr);
break;
default:
break;
}
}
static void ipv6_push_exthdr(struct sk_buff *skb, u8 *proto, u8 type, struct ipv6_opt_hdr *opt)
{
struct ipv6_opt_hdr *h = skb_push(skb, ipv6_optlen(opt));
memcpy(h, opt, ipv6_optlen(opt));
h->nexthdr = *proto;
*proto = type;
}
void ipv6_push_nfrag_opts(struct sk_buff *skb, struct ipv6_txoptions *opt,
u8 *proto,
struct in6_addr **daddr, struct in6_addr *saddr)
{
if (opt->srcrt) {
ipv6_push_rthdr(skb, proto, opt->srcrt, daddr, saddr);
/*
* IPV6_RTHDRDSTOPTS is ignored
* unless IPV6_RTHDR is set (RFC3542).
*/
if (opt->dst0opt)
ipv6_push_exthdr(skb, proto, NEXTHDR_DEST, opt->dst0opt);
}
if (opt->hopopt)
ipv6_push_exthdr(skb, proto, NEXTHDR_HOP, opt->hopopt);
}
void ipv6_push_frag_opts(struct sk_buff *skb, struct ipv6_txoptions *opt, u8 *proto)
{
if (opt->dst1opt)
ipv6_push_exthdr(skb, proto, NEXTHDR_DEST, opt->dst1opt);
}
EXPORT_SYMBOL(ipv6_push_frag_opts);
struct ipv6_txoptions *
ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt)
{
struct ipv6_txoptions *opt2;
opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC);
if (opt2) {
long dif = (char *)opt2 - (char *)opt;
memcpy(opt2, opt, opt->tot_len);
if (opt2->hopopt)
*((char **)&opt2->hopopt) += dif;
if (opt2->dst0opt)
*((char **)&opt2->dst0opt) += dif;
if (opt2->dst1opt)
*((char **)&opt2->dst1opt) += dif;
if (opt2->srcrt)
*((char **)&opt2->srcrt) += dif;
refcount_set(&opt2->refcnt, 1);
}
return opt2;
}
EXPORT_SYMBOL_GPL(ipv6_dup_options);
static void ipv6_renew_option(int renewtype,
struct ipv6_opt_hdr **dest,
struct ipv6_opt_hdr *old,
struct ipv6_opt_hdr *new,
int newtype, char **p)
{
struct ipv6_opt_hdr *src;
src = (renewtype == newtype ? new : old);
if (!src)
return;
memcpy(*p, src, ipv6_optlen(src));
*dest = (struct ipv6_opt_hdr *)*p;
*p += CMSG_ALIGN(ipv6_optlen(*dest));
}
/**
* ipv6_renew_options - replace a specific ext hdr with a new one.
*
* @sk: sock from which to allocate memory
* @opt: original options
* @newtype: option type to replace in @opt
* @newopt: new option of type @newtype to replace (user-mem)
*
* Returns a new set of options which is a copy of @opt with the
* option type @newtype replaced with @newopt.
*
* @opt may be NULL, in which case a new set of options is returned
* containing just @newopt.
*
* @newopt may be NULL, in which case the specified option type is
* not copied into the new set of options.
*
* The new set of options is allocated from the socket option memory
* buffer of @sk.
*/
struct ipv6_txoptions *
ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt,
int newtype, struct ipv6_opt_hdr *newopt)
{
int tot_len = 0;
char *p;
struct ipv6_txoptions *opt2;
if (opt) {
if (newtype != IPV6_HOPOPTS && opt->hopopt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->hopopt));
if (newtype != IPV6_RTHDRDSTOPTS && opt->dst0opt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst0opt));
if (newtype != IPV6_RTHDR && opt->srcrt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->srcrt));
if (newtype != IPV6_DSTOPTS && opt->dst1opt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst1opt));
}
if (newopt)
tot_len += CMSG_ALIGN(ipv6_optlen(newopt));
if (!tot_len)
return NULL;
tot_len += sizeof(*opt2);
opt2 = sock_kmalloc(sk, tot_len, GFP_ATOMIC);
if (!opt2)
return ERR_PTR(-ENOBUFS);
memset(opt2, 0, tot_len);
refcount_set(&opt2->refcnt, 1);
opt2->tot_len = tot_len;
p = (char *)(opt2 + 1);
ipv6_renew_option(IPV6_HOPOPTS, &opt2->hopopt,
(opt ? opt->hopopt : NULL),
newopt, newtype, &p);
ipv6_renew_option(IPV6_RTHDRDSTOPTS, &opt2->dst0opt,
(opt ? opt->dst0opt : NULL),
newopt, newtype, &p);
ipv6_renew_option(IPV6_RTHDR,
(struct ipv6_opt_hdr **)&opt2->srcrt,
(opt ? (struct ipv6_opt_hdr *)opt->srcrt : NULL),
newopt, newtype, &p);
ipv6_renew_option(IPV6_DSTOPTS, &opt2->dst1opt,
(opt ? opt->dst1opt : NULL),
newopt, newtype, &p);
opt2->opt_nflen = (opt2->hopopt ? ipv6_optlen(opt2->hopopt) : 0) +
(opt2->dst0opt ? ipv6_optlen(opt2->dst0opt) : 0) +
(opt2->srcrt ? ipv6_optlen(opt2->srcrt) : 0);
opt2->opt_flen = (opt2->dst1opt ? ipv6_optlen(opt2->dst1opt) : 0);
return opt2;
}
struct ipv6_txoptions *__ipv6_fixup_options(struct ipv6_txoptions *opt_space,
struct ipv6_txoptions *opt)
{
/*
* ignore the dest before srcrt unless srcrt is being included.
* --yoshfuji
*/
if (opt->dst0opt && !opt->srcrt) {
if (opt_space != opt) {
memcpy(opt_space, opt, sizeof(*opt_space));
opt = opt_space;
}
opt->opt_nflen -= ipv6_optlen(opt->dst0opt);
opt->dst0opt = NULL;
}
return opt;
}
EXPORT_SYMBOL_GPL(__ipv6_fixup_options);
/**
* fl6_update_dst - update flowi destination address with info given
* by srcrt option, if any.
*
* @fl6: flowi6 for which daddr is to be updated
* @opt: struct ipv6_txoptions in which to look for srcrt opt
* @orig: copy of original daddr address if modified
*
* Returns NULL if no txoptions or no srcrt, otherwise returns orig
* and initial value of fl6->daddr set in orig
*/
struct in6_addr *fl6_update_dst(struct flowi6 *fl6,
const struct ipv6_txoptions *opt,
struct in6_addr *orig)
{
if (!opt || !opt->srcrt)
return NULL;
*orig = fl6->daddr;
switch (opt->srcrt->type) {
case IPV6_SRCRT_TYPE_0:
case IPV6_SRCRT_STRICT:
case IPV6_SRCRT_TYPE_2:
fl6->daddr = *((struct rt0_hdr *)opt->srcrt)->addr;
break;
case IPV6_SRCRT_TYPE_4:
{
struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)opt->srcrt;
fl6->daddr = srh->segments[srh->segments_left];
break;
}
default:
return NULL;
}
return orig;
}
EXPORT_SYMBOL_GPL(fl6_update_dst);
| linux-master | net/ipv6/exthdrs.c |
// SPDX-License-Identifier: GPL-2.0
/*
* IPv6 Address Label subsystem
* for the IPv6 "Default" Source Address Selection
*
* Copyright (C)2007 USAGI/WIDE Project
*/
/*
* Author:
* YOSHIFUJI Hideaki @ USAGI/WIDE Project <[email protected]>
*/
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/rcupdate.h>
#include <linux/in6.h>
#include <linux/slab.h>
#include <net/addrconf.h>
#include <linux/if_addrlabel.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#if 0
#define ADDRLABEL(x...) printk(x)
#else
#define ADDRLABEL(x...) do { ; } while (0)
#endif
/*
* Policy Table
*/
struct ip6addrlbl_entry {
struct in6_addr prefix;
int prefixlen;
int ifindex;
int addrtype;
u32 label;
struct hlist_node list;
struct rcu_head rcu;
};
/*
* Default policy table (RFC6724 + extensions)
*
* prefix addr_type label
* -------------------------------------------------------------------------
* ::1/128 LOOPBACK 0
* ::/0 N/A 1
* 2002::/16 N/A 2
* ::/96 COMPATv4 3
* ::ffff:0:0/96 V4MAPPED 4
* fc00::/7 N/A 5 ULA (RFC 4193)
* 2001::/32 N/A 6 Teredo (RFC 4380)
* 2001:10::/28 N/A 7 ORCHID (RFC 4843)
* fec0::/10 N/A 11 Site-local
* (deprecated by RFC3879)
* 3ffe::/16 N/A 12 6bone
*
* Note: 0xffffffff is used if we do not have any policies.
* Note: Labels for ULA and 6to4 are different from labels listed in RFC6724.
*/
#define IPV6_ADDR_LABEL_DEFAULT 0xffffffffUL
static const __net_initconst struct ip6addrlbl_init_table
{
const struct in6_addr *prefix;
int prefixlen;
u32 label;
} ip6addrlbl_init_table[] = {
{ /* ::/0 */
.prefix = &in6addr_any,
.label = 1,
}, { /* fc00::/7 */
.prefix = &(struct in6_addr){ { { 0xfc } } } ,
.prefixlen = 7,
.label = 5,
}, { /* fec0::/10 */
.prefix = &(struct in6_addr){ { { 0xfe, 0xc0 } } },
.prefixlen = 10,
.label = 11,
}, { /* 2002::/16 */
.prefix = &(struct in6_addr){ { { 0x20, 0x02 } } },
.prefixlen = 16,
.label = 2,
}, { /* 3ffe::/16 */
.prefix = &(struct in6_addr){ { { 0x3f, 0xfe } } },
.prefixlen = 16,
.label = 12,
}, { /* 2001::/32 */
.prefix = &(struct in6_addr){ { { 0x20, 0x01 } } },
.prefixlen = 32,
.label = 6,
}, { /* 2001:10::/28 */
.prefix = &(struct in6_addr){ { { 0x20, 0x01, 0x00, 0x10 } } },
.prefixlen = 28,
.label = 7,
}, { /* ::ffff:0:0 */
.prefix = &(struct in6_addr){ { { [10] = 0xff, [11] = 0xff } } },
.prefixlen = 96,
.label = 4,
}, { /* ::/96 */
.prefix = &in6addr_any,
.prefixlen = 96,
.label = 3,
}, { /* ::1/128 */
.prefix = &in6addr_loopback,
.prefixlen = 128,
.label = 0,
}
};
/* Find label */
static bool __ip6addrlbl_match(const struct ip6addrlbl_entry *p,
const struct in6_addr *addr,
int addrtype, int ifindex)
{
if (p->ifindex && p->ifindex != ifindex)
return false;
if (p->addrtype && p->addrtype != addrtype)
return false;
if (!ipv6_prefix_equal(addr, &p->prefix, p->prefixlen))
return false;
return true;
}
static struct ip6addrlbl_entry *__ipv6_addr_label(struct net *net,
const struct in6_addr *addr,
int type, int ifindex)
{
struct ip6addrlbl_entry *p;
hlist_for_each_entry_rcu(p, &net->ipv6.ip6addrlbl_table.head, list) {
if (__ip6addrlbl_match(p, addr, type, ifindex))
return p;
}
return NULL;
}
u32 ipv6_addr_label(struct net *net,
const struct in6_addr *addr, int type, int ifindex)
{
u32 label;
struct ip6addrlbl_entry *p;
type &= IPV6_ADDR_MAPPED | IPV6_ADDR_COMPATv4 | IPV6_ADDR_LOOPBACK;
rcu_read_lock();
p = __ipv6_addr_label(net, addr, type, ifindex);
label = p ? p->label : IPV6_ADDR_LABEL_DEFAULT;
rcu_read_unlock();
ADDRLABEL(KERN_DEBUG "%s(addr=%pI6, type=%d, ifindex=%d) => %08x\n",
__func__, addr, type, ifindex, label);
return label;
}
/* allocate one entry */
static struct ip6addrlbl_entry *ip6addrlbl_alloc(const struct in6_addr *prefix,
int prefixlen, int ifindex,
u32 label)
{
struct ip6addrlbl_entry *newp;
int addrtype;
ADDRLABEL(KERN_DEBUG "%s(prefix=%pI6, prefixlen=%d, ifindex=%d, label=%u)\n",
__func__, prefix, prefixlen, ifindex, (unsigned int)label);
addrtype = ipv6_addr_type(prefix) & (IPV6_ADDR_MAPPED | IPV6_ADDR_COMPATv4 | IPV6_ADDR_LOOPBACK);
switch (addrtype) {
case IPV6_ADDR_MAPPED:
if (prefixlen > 96)
return ERR_PTR(-EINVAL);
if (prefixlen < 96)
addrtype = 0;
break;
case IPV6_ADDR_COMPATv4:
if (prefixlen != 96)
addrtype = 0;
break;
case IPV6_ADDR_LOOPBACK:
if (prefixlen != 128)
addrtype = 0;
break;
}
newp = kmalloc(sizeof(*newp), GFP_KERNEL);
if (!newp)
return ERR_PTR(-ENOMEM);
ipv6_addr_prefix(&newp->prefix, prefix, prefixlen);
newp->prefixlen = prefixlen;
newp->ifindex = ifindex;
newp->addrtype = addrtype;
newp->label = label;
INIT_HLIST_NODE(&newp->list);
return newp;
}
/* add a label */
static int __ip6addrlbl_add(struct net *net, struct ip6addrlbl_entry *newp,
int replace)
{
struct ip6addrlbl_entry *last = NULL, *p = NULL;
struct hlist_node *n;
int ret = 0;
ADDRLABEL(KERN_DEBUG "%s(newp=%p, replace=%d)\n", __func__, newp,
replace);
hlist_for_each_entry_safe(p, n, &net->ipv6.ip6addrlbl_table.head, list) {
if (p->prefixlen == newp->prefixlen &&
p->ifindex == newp->ifindex &&
ipv6_addr_equal(&p->prefix, &newp->prefix)) {
if (!replace) {
ret = -EEXIST;
goto out;
}
hlist_replace_rcu(&p->list, &newp->list);
kfree_rcu(p, rcu);
goto out;
} else if ((p->prefixlen == newp->prefixlen && !p->ifindex) ||
(p->prefixlen < newp->prefixlen)) {
hlist_add_before_rcu(&newp->list, &p->list);
goto out;
}
last = p;
}
if (last)
hlist_add_behind_rcu(&newp->list, &last->list);
else
hlist_add_head_rcu(&newp->list, &net->ipv6.ip6addrlbl_table.head);
out:
if (!ret)
net->ipv6.ip6addrlbl_table.seq++;
return ret;
}
/* add a label */
static int ip6addrlbl_add(struct net *net,
const struct in6_addr *prefix, int prefixlen,
int ifindex, u32 label, int replace)
{
struct ip6addrlbl_entry *newp;
int ret = 0;
ADDRLABEL(KERN_DEBUG "%s(prefix=%pI6, prefixlen=%d, ifindex=%d, label=%u, replace=%d)\n",
__func__, prefix, prefixlen, ifindex, (unsigned int)label,
replace);
newp = ip6addrlbl_alloc(prefix, prefixlen, ifindex, label);
if (IS_ERR(newp))
return PTR_ERR(newp);
spin_lock(&net->ipv6.ip6addrlbl_table.lock);
ret = __ip6addrlbl_add(net, newp, replace);
spin_unlock(&net->ipv6.ip6addrlbl_table.lock);
if (ret)
kfree(newp);
return ret;
}
/* remove a label */
static int __ip6addrlbl_del(struct net *net,
const struct in6_addr *prefix, int prefixlen,
int ifindex)
{
struct ip6addrlbl_entry *p = NULL;
struct hlist_node *n;
int ret = -ESRCH;
ADDRLABEL(KERN_DEBUG "%s(prefix=%pI6, prefixlen=%d, ifindex=%d)\n",
__func__, prefix, prefixlen, ifindex);
hlist_for_each_entry_safe(p, n, &net->ipv6.ip6addrlbl_table.head, list) {
if (p->prefixlen == prefixlen &&
p->ifindex == ifindex &&
ipv6_addr_equal(&p->prefix, prefix)) {
hlist_del_rcu(&p->list);
kfree_rcu(p, rcu);
ret = 0;
break;
}
}
return ret;
}
static int ip6addrlbl_del(struct net *net,
const struct in6_addr *prefix, int prefixlen,
int ifindex)
{
struct in6_addr prefix_buf;
int ret;
ADDRLABEL(KERN_DEBUG "%s(prefix=%pI6, prefixlen=%d, ifindex=%d)\n",
__func__, prefix, prefixlen, ifindex);
ipv6_addr_prefix(&prefix_buf, prefix, prefixlen);
spin_lock(&net->ipv6.ip6addrlbl_table.lock);
ret = __ip6addrlbl_del(net, &prefix_buf, prefixlen, ifindex);
spin_unlock(&net->ipv6.ip6addrlbl_table.lock);
return ret;
}
/* add default label */
static int __net_init ip6addrlbl_net_init(struct net *net)
{
struct ip6addrlbl_entry *p = NULL;
struct hlist_node *n;
int err;
int i;
ADDRLABEL(KERN_DEBUG "%s\n", __func__);
spin_lock_init(&net->ipv6.ip6addrlbl_table.lock);
INIT_HLIST_HEAD(&net->ipv6.ip6addrlbl_table.head);
for (i = 0; i < ARRAY_SIZE(ip6addrlbl_init_table); i++) {
err = ip6addrlbl_add(net,
ip6addrlbl_init_table[i].prefix,
ip6addrlbl_init_table[i].prefixlen,
0,
ip6addrlbl_init_table[i].label, 0);
if (err)
goto err_ip6addrlbl_add;
}
return 0;
err_ip6addrlbl_add:
hlist_for_each_entry_safe(p, n, &net->ipv6.ip6addrlbl_table.head, list) {
hlist_del_rcu(&p->list);
kfree_rcu(p, rcu);
}
return err;
}
static void __net_exit ip6addrlbl_net_exit(struct net *net)
{
struct ip6addrlbl_entry *p = NULL;
struct hlist_node *n;
/* Remove all labels belonging to the exiting net */
spin_lock(&net->ipv6.ip6addrlbl_table.lock);
hlist_for_each_entry_safe(p, n, &net->ipv6.ip6addrlbl_table.head, list) {
hlist_del_rcu(&p->list);
kfree_rcu(p, rcu);
}
spin_unlock(&net->ipv6.ip6addrlbl_table.lock);
}
static struct pernet_operations ipv6_addr_label_ops = {
.init = ip6addrlbl_net_init,
.exit = ip6addrlbl_net_exit,
};
int __init ipv6_addr_label_init(void)
{
return register_pernet_subsys(&ipv6_addr_label_ops);
}
void ipv6_addr_label_cleanup(void)
{
unregister_pernet_subsys(&ipv6_addr_label_ops);
}
static const struct nla_policy ifal_policy[IFAL_MAX+1] = {
[IFAL_ADDRESS] = { .len = sizeof(struct in6_addr), },
[IFAL_LABEL] = { .len = sizeof(u32), },
};
static bool addrlbl_ifindex_exists(struct net *net, int ifindex)
{
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_index_rcu(net, ifindex);
rcu_read_unlock();
return dev != NULL;
}
static int ip6addrlbl_newdel(struct sk_buff *skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(skb->sk);
struct ifaddrlblmsg *ifal;
struct nlattr *tb[IFAL_MAX+1];
struct in6_addr *pfx;
u32 label;
int err = 0;
err = nlmsg_parse_deprecated(nlh, sizeof(*ifal), tb, IFAL_MAX,
ifal_policy, extack);
if (err < 0)
return err;
ifal = nlmsg_data(nlh);
if (ifal->ifal_family != AF_INET6 ||
ifal->ifal_prefixlen > 128)
return -EINVAL;
if (!tb[IFAL_ADDRESS])
return -EINVAL;
pfx = nla_data(tb[IFAL_ADDRESS]);
if (!tb[IFAL_LABEL])
return -EINVAL;
label = nla_get_u32(tb[IFAL_LABEL]);
if (label == IPV6_ADDR_LABEL_DEFAULT)
return -EINVAL;
switch (nlh->nlmsg_type) {
case RTM_NEWADDRLABEL:
if (ifal->ifal_index &&
!addrlbl_ifindex_exists(net, ifal->ifal_index))
return -EINVAL;
err = ip6addrlbl_add(net, pfx, ifal->ifal_prefixlen,
ifal->ifal_index, label,
nlh->nlmsg_flags & NLM_F_REPLACE);
break;
case RTM_DELADDRLABEL:
err = ip6addrlbl_del(net, pfx, ifal->ifal_prefixlen,
ifal->ifal_index);
break;
default:
err = -EOPNOTSUPP;
}
return err;
}
static void ip6addrlbl_putmsg(struct nlmsghdr *nlh,
int prefixlen, int ifindex, u32 lseq)
{
struct ifaddrlblmsg *ifal = nlmsg_data(nlh);
ifal->ifal_family = AF_INET6;
ifal->__ifal_reserved = 0;
ifal->ifal_prefixlen = prefixlen;
ifal->ifal_flags = 0;
ifal->ifal_index = ifindex;
ifal->ifal_seq = lseq;
};
static int ip6addrlbl_fill(struct sk_buff *skb,
struct ip6addrlbl_entry *p,
u32 lseq,
u32 portid, u32 seq, int event,
unsigned int flags)
{
struct nlmsghdr *nlh = nlmsg_put(skb, portid, seq, event,
sizeof(struct ifaddrlblmsg), flags);
if (!nlh)
return -EMSGSIZE;
ip6addrlbl_putmsg(nlh, p->prefixlen, p->ifindex, lseq);
if (nla_put_in6_addr(skb, IFAL_ADDRESS, &p->prefix) < 0 ||
nla_put_u32(skb, IFAL_LABEL, p->label) < 0) {
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
nlmsg_end(skb, nlh);
return 0;
}
static int ip6addrlbl_valid_dump_req(const struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct ifaddrlblmsg *ifal;
if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*ifal))) {
NL_SET_ERR_MSG_MOD(extack, "Invalid header for address label dump request");
return -EINVAL;
}
ifal = nlmsg_data(nlh);
if (ifal->__ifal_reserved || ifal->ifal_prefixlen ||
ifal->ifal_flags || ifal->ifal_index || ifal->ifal_seq) {
NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for address label dump request");
return -EINVAL;
}
if (nlmsg_attrlen(nlh, sizeof(*ifal))) {
NL_SET_ERR_MSG_MOD(extack, "Invalid data after header for address label dump request");
return -EINVAL;
}
return 0;
}
static int ip6addrlbl_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
const struct nlmsghdr *nlh = cb->nlh;
struct net *net = sock_net(skb->sk);
struct ip6addrlbl_entry *p;
int idx = 0, s_idx = cb->args[0];
int err;
if (cb->strict_check) {
err = ip6addrlbl_valid_dump_req(nlh, cb->extack);
if (err < 0)
return err;
}
rcu_read_lock();
hlist_for_each_entry_rcu(p, &net->ipv6.ip6addrlbl_table.head, list) {
if (idx >= s_idx) {
err = ip6addrlbl_fill(skb, p,
net->ipv6.ip6addrlbl_table.seq,
NETLINK_CB(cb->skb).portid,
nlh->nlmsg_seq,
RTM_NEWADDRLABEL,
NLM_F_MULTI);
if (err < 0)
break;
}
idx++;
}
rcu_read_unlock();
cb->args[0] = idx;
return skb->len;
}
static inline int ip6addrlbl_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct ifaddrlblmsg))
+ nla_total_size(16) /* IFAL_ADDRESS */
+ nla_total_size(4); /* IFAL_LABEL */
}
static int ip6addrlbl_valid_get_req(struct sk_buff *skb,
const struct nlmsghdr *nlh,
struct nlattr **tb,
struct netlink_ext_ack *extack)
{
struct ifaddrlblmsg *ifal;
int i, err;
if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*ifal))) {
NL_SET_ERR_MSG_MOD(extack, "Invalid header for addrlabel get request");
return -EINVAL;
}
if (!netlink_strict_get_check(skb))
return nlmsg_parse_deprecated(nlh, sizeof(*ifal), tb,
IFAL_MAX, ifal_policy, extack);
ifal = nlmsg_data(nlh);
if (ifal->__ifal_reserved || ifal->ifal_flags || ifal->ifal_seq) {
NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for addrlabel get request");
return -EINVAL;
}
err = nlmsg_parse_deprecated_strict(nlh, sizeof(*ifal), tb, IFAL_MAX,
ifal_policy, extack);
if (err)
return err;
for (i = 0; i <= IFAL_MAX; i++) {
if (!tb[i])
continue;
switch (i) {
case IFAL_ADDRESS:
break;
default:
NL_SET_ERR_MSG_MOD(extack, "Unsupported attribute in addrlabel get request");
return -EINVAL;
}
}
return 0;
}
static int ip6addrlbl_get(struct sk_buff *in_skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(in_skb->sk);
struct ifaddrlblmsg *ifal;
struct nlattr *tb[IFAL_MAX+1];
struct in6_addr *addr;
u32 lseq;
int err = 0;
struct ip6addrlbl_entry *p;
struct sk_buff *skb;
err = ip6addrlbl_valid_get_req(in_skb, nlh, tb, extack);
if (err < 0)
return err;
ifal = nlmsg_data(nlh);
if (ifal->ifal_family != AF_INET6 ||
ifal->ifal_prefixlen != 128)
return -EINVAL;
if (ifal->ifal_index &&
!addrlbl_ifindex_exists(net, ifal->ifal_index))
return -EINVAL;
if (!tb[IFAL_ADDRESS])
return -EINVAL;
addr = nla_data(tb[IFAL_ADDRESS]);
skb = nlmsg_new(ip6addrlbl_msgsize(), GFP_KERNEL);
if (!skb)
return -ENOBUFS;
err = -ESRCH;
rcu_read_lock();
p = __ipv6_addr_label(net, addr, ipv6_addr_type(addr), ifal->ifal_index);
lseq = net->ipv6.ip6addrlbl_table.seq;
if (p)
err = ip6addrlbl_fill(skb, p, lseq,
NETLINK_CB(in_skb).portid,
nlh->nlmsg_seq,
RTM_NEWADDRLABEL, 0);
rcu_read_unlock();
if (err < 0) {
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
} else {
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
}
return err;
}
int __init ipv6_addr_label_rtnl_register(void)
{
int ret;
ret = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_NEWADDRLABEL,
ip6addrlbl_newdel,
NULL, RTNL_FLAG_DOIT_UNLOCKED);
if (ret < 0)
return ret;
ret = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_DELADDRLABEL,
ip6addrlbl_newdel,
NULL, RTNL_FLAG_DOIT_UNLOCKED);
if (ret < 0)
return ret;
ret = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETADDRLABEL,
ip6addrlbl_get,
ip6addrlbl_dump, RTNL_FLAG_DOIT_UNLOCKED);
return ret;
}
| linux-master | net/ipv6/addrlabel.c |
// SPDX-License-Identifier: GPL-2.0
/*
* xfrm6_policy.c: based on xfrm4_policy.c
*
* Authors:
* Mitsuru KANDA @USAGI
* Kazunori MIYAZAWA @USAGI
* Kunihiro Ishiguro <[email protected]>
* IPv6 support
* YOSHIFUJI Hideaki
* Split up af-specific portion
*
*/
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <net/addrconf.h>
#include <net/dst.h>
#include <net/xfrm.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/ip6_route.h>
#include <net/l3mdev.h>
static struct dst_entry *xfrm6_dst_lookup(struct net *net, int tos, int oif,
const xfrm_address_t *saddr,
const xfrm_address_t *daddr,
u32 mark)
{
struct flowi6 fl6;
struct dst_entry *dst;
int err;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_l3mdev = l3mdev_master_ifindex_by_index(net, oif);
fl6.flowi6_mark = mark;
memcpy(&fl6.daddr, daddr, sizeof(fl6.daddr));
if (saddr)
memcpy(&fl6.saddr, saddr, sizeof(fl6.saddr));
dst = ip6_route_output(net, NULL, &fl6);
err = dst->error;
if (dst->error) {
dst_release(dst);
dst = ERR_PTR(err);
}
return dst;
}
static int xfrm6_get_saddr(struct net *net, int oif,
xfrm_address_t *saddr, xfrm_address_t *daddr,
u32 mark)
{
struct dst_entry *dst;
struct net_device *dev;
dst = xfrm6_dst_lookup(net, 0, oif, NULL, daddr, mark);
if (IS_ERR(dst))
return -EHOSTUNREACH;
dev = ip6_dst_idev(dst)->dev;
ipv6_dev_get_saddr(dev_net(dev), dev, &daddr->in6, 0, &saddr->in6);
dst_release(dst);
return 0;
}
static int xfrm6_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
const struct flowi *fl)
{
struct rt6_info *rt = (struct rt6_info *)xdst->route;
xdst->u.dst.dev = dev;
netdev_hold(dev, &xdst->u.dst.dev_tracker, GFP_ATOMIC);
xdst->u.rt6.rt6i_idev = in6_dev_get(dev);
if (!xdst->u.rt6.rt6i_idev) {
netdev_put(dev, &xdst->u.dst.dev_tracker);
return -ENODEV;
}
/* Sheit... I remember I did this right. Apparently,
* it was magically lost, so this code needs audit */
xdst->u.rt6.rt6i_flags = rt->rt6i_flags & (RTF_ANYCAST |
RTF_LOCAL);
xdst->route_cookie = rt6_get_cookie(rt);
xdst->u.rt6.rt6i_gateway = rt->rt6i_gateway;
xdst->u.rt6.rt6i_dst = rt->rt6i_dst;
xdst->u.rt6.rt6i_src = rt->rt6i_src;
rt6_uncached_list_add(&xdst->u.rt6);
return 0;
}
static void xfrm6_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu,
bool confirm_neigh)
{
struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
struct dst_entry *path = xdst->route;
path->ops->update_pmtu(path, sk, skb, mtu, confirm_neigh);
}
static void xfrm6_redirect(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb)
{
struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
struct dst_entry *path = xdst->route;
path->ops->redirect(path, sk, skb);
}
static void xfrm6_dst_destroy(struct dst_entry *dst)
{
struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
if (likely(xdst->u.rt6.rt6i_idev))
in6_dev_put(xdst->u.rt6.rt6i_idev);
dst_destroy_metrics_generic(dst);
rt6_uncached_list_del(&xdst->u.rt6);
xfrm_dst_destroy(xdst);
}
static void xfrm6_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
{
struct xfrm_dst *xdst;
xdst = (struct xfrm_dst *)dst;
if (xdst->u.rt6.rt6i_idev->dev == dev) {
struct inet6_dev *loopback_idev =
in6_dev_get(dev_net(dev)->loopback_dev);
do {
in6_dev_put(xdst->u.rt6.rt6i_idev);
xdst->u.rt6.rt6i_idev = loopback_idev;
in6_dev_hold(loopback_idev);
xdst = (struct xfrm_dst *)xfrm_dst_child(&xdst->u.dst);
} while (xdst->u.dst.xfrm);
__in6_dev_put(loopback_idev);
}
xfrm_dst_ifdown(dst, dev);
}
static struct dst_ops xfrm6_dst_ops_template = {
.family = AF_INET6,
.update_pmtu = xfrm6_update_pmtu,
.redirect = xfrm6_redirect,
.cow_metrics = dst_cow_metrics_generic,
.destroy = xfrm6_dst_destroy,
.ifdown = xfrm6_dst_ifdown,
.local_out = __ip6_local_out,
.gc_thresh = 32768,
};
static const struct xfrm_policy_afinfo xfrm6_policy_afinfo = {
.dst_ops = &xfrm6_dst_ops_template,
.dst_lookup = xfrm6_dst_lookup,
.get_saddr = xfrm6_get_saddr,
.fill_dst = xfrm6_fill_dst,
.blackhole_route = ip6_blackhole_route,
};
static int __init xfrm6_policy_init(void)
{
return xfrm_policy_register_afinfo(&xfrm6_policy_afinfo, AF_INET6);
}
static void xfrm6_policy_fini(void)
{
xfrm_policy_unregister_afinfo(&xfrm6_policy_afinfo);
}
#ifdef CONFIG_SYSCTL
static struct ctl_table xfrm6_policy_table[] = {
{
.procname = "xfrm6_gc_thresh",
.data = &init_net.xfrm.xfrm6_dst_ops.gc_thresh,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{ }
};
static int __net_init xfrm6_net_sysctl_init(struct net *net)
{
struct ctl_table *table;
struct ctl_table_header *hdr;
table = xfrm6_policy_table;
if (!net_eq(net, &init_net)) {
table = kmemdup(table, sizeof(xfrm6_policy_table), GFP_KERNEL);
if (!table)
goto err_alloc;
table[0].data = &net->xfrm.xfrm6_dst_ops.gc_thresh;
}
hdr = register_net_sysctl_sz(net, "net/ipv6", table,
ARRAY_SIZE(xfrm6_policy_table));
if (!hdr)
goto err_reg;
net->ipv6.sysctl.xfrm6_hdr = hdr;
return 0;
err_reg:
if (!net_eq(net, &init_net))
kfree(table);
err_alloc:
return -ENOMEM;
}
static void __net_exit xfrm6_net_sysctl_exit(struct net *net)
{
struct ctl_table *table;
if (!net->ipv6.sysctl.xfrm6_hdr)
return;
table = net->ipv6.sysctl.xfrm6_hdr->ctl_table_arg;
unregister_net_sysctl_table(net->ipv6.sysctl.xfrm6_hdr);
if (!net_eq(net, &init_net))
kfree(table);
}
#else /* CONFIG_SYSCTL */
static inline int xfrm6_net_sysctl_init(struct net *net)
{
return 0;
}
static inline void xfrm6_net_sysctl_exit(struct net *net)
{
}
#endif
static int __net_init xfrm6_net_init(struct net *net)
{
int ret;
memcpy(&net->xfrm.xfrm6_dst_ops, &xfrm6_dst_ops_template,
sizeof(xfrm6_dst_ops_template));
ret = dst_entries_init(&net->xfrm.xfrm6_dst_ops);
if (ret)
return ret;
ret = xfrm6_net_sysctl_init(net);
if (ret)
dst_entries_destroy(&net->xfrm.xfrm6_dst_ops);
return ret;
}
static void __net_exit xfrm6_net_exit(struct net *net)
{
xfrm6_net_sysctl_exit(net);
dst_entries_destroy(&net->xfrm.xfrm6_dst_ops);
}
static struct pernet_operations xfrm6_net_ops = {
.init = xfrm6_net_init,
.exit = xfrm6_net_exit,
};
int __init xfrm6_init(void)
{
int ret;
ret = xfrm6_policy_init();
if (ret)
goto out;
ret = xfrm6_state_init();
if (ret)
goto out_policy;
ret = xfrm6_protocol_init();
if (ret)
goto out_state;
ret = register_pernet_subsys(&xfrm6_net_ops);
if (ret)
goto out_protocol;
out:
return ret;
out_protocol:
xfrm6_protocol_fini();
out_state:
xfrm6_state_fini();
out_policy:
xfrm6_policy_fini();
goto out;
}
void xfrm6_fini(void)
{
unregister_pernet_subsys(&xfrm6_net_ops);
xfrm6_protocol_fini();
xfrm6_policy_fini();
xfrm6_state_fini();
}
| linux-master | net/ipv6/xfrm6_policy.c |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* IPV6 GSO/GRO offload support
* Linux INET6 implementation
*
* IPV6 Extension Header GSO/GRO support
*/
#include <net/protocol.h>
#include "ip6_offload.h"
static const struct net_offload rthdr_offload = {
.flags = INET6_PROTO_GSO_EXTHDR,
};
static const struct net_offload dstopt_offload = {
.flags = INET6_PROTO_GSO_EXTHDR,
};
int __init ipv6_exthdrs_offload_init(void)
{
int ret;
ret = inet6_add_offload(&rthdr_offload, IPPROTO_ROUTING);
if (ret)
goto out;
ret = inet6_add_offload(&dstopt_offload, IPPROTO_DSTOPTS);
if (ret)
goto out_rt;
out:
return ret;
out_rt:
inet6_del_offload(&rthdr_offload, IPPROTO_ROUTING);
goto out;
}
| linux-master | net/ipv6/exthdrs_offload.c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.