Merge tag 's390-5.14-1' of git://git.kernel.org/pub/scm/linux/kernel/git/s390/linux
[linux-2.6-microblaze.git] / net / netfilter / nft_last.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/kernel.h>
3 #include <linux/init.h>
4 #include <linux/module.h>
5 #include <linux/netlink.h>
6 #include <linux/netfilter.h>
7 #include <linux/netfilter/nf_tables.h>
8 #include <net/netfilter/nf_tables_core.h>
9 #include <net/netfilter/nf_tables.h>
10
11 struct nft_last_priv {
12         unsigned long   last_jiffies;
13         unsigned int    last_set;
14 };
15
16 static const struct nla_policy nft_last_policy[NFTA_LAST_MAX + 1] = {
17         [NFTA_LAST_SET] = { .type = NLA_U32 },
18         [NFTA_LAST_MSECS] = { .type = NLA_U64 },
19 };
20
21 static int nft_last_init(const struct nft_ctx *ctx, const struct nft_expr *expr,
22                          const struct nlattr * const tb[])
23 {
24         struct nft_last_priv *priv = nft_expr_priv(expr);
25         u64 last_jiffies;
26         int err;
27
28         if (tb[NFTA_LAST_MSECS]) {
29                 err = nf_msecs_to_jiffies64(tb[NFTA_LAST_MSECS], &last_jiffies);
30                 if (err < 0)
31                         return err;
32
33                 priv->last_jiffies = jiffies + (unsigned long)last_jiffies;
34                 priv->last_set = 1;
35         }
36
37         return 0;
38 }
39
40 static void nft_last_eval(const struct nft_expr *expr,
41                           struct nft_regs *regs, const struct nft_pktinfo *pkt)
42 {
43         struct nft_last_priv *priv = nft_expr_priv(expr);
44
45         priv->last_jiffies = jiffies;
46         priv->last_set = 1;
47 }
48
49 static int nft_last_dump(struct sk_buff *skb, const struct nft_expr *expr)
50 {
51         struct nft_last_priv *priv = nft_expr_priv(expr);
52         __be64 msecs;
53
54         if (time_before(jiffies, priv->last_jiffies))
55                 priv->last_set = 0;
56
57         if (priv->last_set)
58                 msecs = nf_jiffies64_to_msecs(jiffies - priv->last_jiffies);
59         else
60                 msecs = 0;
61
62         if (nla_put_be32(skb, NFTA_LAST_SET, htonl(priv->last_set)) ||
63             nla_put_be64(skb, NFTA_LAST_MSECS, msecs, NFTA_LAST_PAD))
64                 goto nla_put_failure;
65
66         return 0;
67
68 nla_put_failure:
69         return -1;
70 }
71
72 static const struct nft_expr_ops nft_last_ops = {
73         .type           = &nft_last_type,
74         .size           = NFT_EXPR_SIZE(sizeof(struct nft_last_priv)),
75         .eval           = nft_last_eval,
76         .init           = nft_last_init,
77         .dump           = nft_last_dump,
78 };
79
80 struct nft_expr_type nft_last_type __read_mostly = {
81         .name           = "last",
82         .ops            = &nft_last_ops,
83         .policy         = nft_last_policy,
84         .maxattr        = NFTA_LAST_MAX,
85         .flags          = NFT_EXPR_STATEFUL,
86         .owner          = THIS_MODULE,
87 };