Merge branch 'linus' into locking/core, to resolve conflicts
[sfrench/cifs-2.6.git] / include / net / netfilter / nf_tables.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _NET_NF_TABLES_H
3 #define _NET_NF_TABLES_H
4
5 #include <linux/module.h>
6 #include <linux/list.h>
7 #include <linux/netfilter.h>
8 #include <linux/netfilter/nfnetlink.h>
9 #include <linux/netfilter/x_tables.h>
10 #include <linux/netfilter/nf_tables.h>
11 #include <linux/u64_stats_sync.h>
12 #include <net/netlink.h>
13
14 #define NFT_JUMP_STACK_SIZE     16
15
16 struct nft_pktinfo {
17         struct sk_buff                  *skb;
18         bool                            tprot_set;
19         u8                              tprot;
20         /* for x_tables compatibility */
21         struct xt_action_param          xt;
22 };
23
24 static inline struct net *nft_net(const struct nft_pktinfo *pkt)
25 {
26         return pkt->xt.state->net;
27 }
28
29 static inline unsigned int nft_hook(const struct nft_pktinfo *pkt)
30 {
31         return pkt->xt.state->hook;
32 }
33
34 static inline u8 nft_pf(const struct nft_pktinfo *pkt)
35 {
36         return pkt->xt.state->pf;
37 }
38
39 static inline const struct net_device *nft_in(const struct nft_pktinfo *pkt)
40 {
41         return pkt->xt.state->in;
42 }
43
44 static inline const struct net_device *nft_out(const struct nft_pktinfo *pkt)
45 {
46         return pkt->xt.state->out;
47 }
48
49 static inline void nft_set_pktinfo(struct nft_pktinfo *pkt,
50                                    struct sk_buff *skb,
51                                    const struct nf_hook_state *state)
52 {
53         pkt->skb = skb;
54         pkt->xt.state = state;
55 }
56
57 static inline void nft_set_pktinfo_proto_unspec(struct nft_pktinfo *pkt,
58                                                 struct sk_buff *skb)
59 {
60         pkt->tprot_set = false;
61         pkt->tprot = 0;
62         pkt->xt.thoff = 0;
63         pkt->xt.fragoff = 0;
64 }
65
66 static inline void nft_set_pktinfo_unspec(struct nft_pktinfo *pkt,
67                                           struct sk_buff *skb,
68                                           const struct nf_hook_state *state)
69 {
70         nft_set_pktinfo(pkt, skb, state);
71         nft_set_pktinfo_proto_unspec(pkt, skb);
72 }
73
74 /**
75  *      struct nft_verdict - nf_tables verdict
76  *
77  *      @code: nf_tables/netfilter verdict code
78  *      @chain: destination chain for NFT_JUMP/NFT_GOTO
79  */
80 struct nft_verdict {
81         u32                             code;
82         struct nft_chain                *chain;
83 };
84
85 struct nft_data {
86         union {
87                 u32                     data[4];
88                 struct nft_verdict      verdict;
89         };
90 } __attribute__((aligned(__alignof__(u64))));
91
92 /**
93  *      struct nft_regs - nf_tables register set
94  *
95  *      @data: data registers
96  *      @verdict: verdict register
97  *
98  *      The first four data registers alias to the verdict register.
99  */
100 struct nft_regs {
101         union {
102                 u32                     data[20];
103                 struct nft_verdict      verdict;
104         };
105 };
106
107 /* Store/load an u16 or u8 integer to/from the u32 data register.
108  *
109  * Note, when using concatenations, register allocation happens at 32-bit
110  * level. So for store instruction, pad the rest part with zero to avoid
111  * garbage values.
112  */
113
114 static inline void nft_reg_store16(u32 *dreg, u16 val)
115 {
116         *dreg = 0;
117         *(u16 *)dreg = val;
118 }
119
120 static inline void nft_reg_store8(u32 *dreg, u8 val)
121 {
122         *dreg = 0;
123         *(u8 *)dreg = val;
124 }
125
126 static inline u16 nft_reg_load16(u32 *sreg)
127 {
128         return *(u16 *)sreg;
129 }
130
131 static inline u8 nft_reg_load8(u32 *sreg)
132 {
133         return *(u8 *)sreg;
134 }
135
136 static inline void nft_data_copy(u32 *dst, const struct nft_data *src,
137                                  unsigned int len)
138 {
139         memcpy(dst, src, len);
140 }
141
142 static inline void nft_data_debug(const struct nft_data *data)
143 {
144         pr_debug("data[0]=%x data[1]=%x data[2]=%x data[3]=%x\n",
145                  data->data[0], data->data[1],
146                  data->data[2], data->data[3]);
147 }
148
149 /**
150  *      struct nft_ctx - nf_tables rule/set context
151  *
152  *      @net: net namespace
153  *      @afi: address family info
154  *      @table: the table the chain is contained in
155  *      @chain: the chain the rule is contained in
156  *      @nla: netlink attributes
157  *      @portid: netlink portID of the original message
158  *      @seq: netlink sequence number
159  *      @report: notify via unicast netlink message
160  */
161 struct nft_ctx {
162         struct net                      *net;
163         struct nft_af_info              *afi;
164         struct nft_table                *table;
165         struct nft_chain                *chain;
166         const struct nlattr * const     *nla;
167         u32                             portid;
168         u32                             seq;
169         bool                            report;
170 };
171
172 struct nft_data_desc {
173         enum nft_data_types             type;
174         unsigned int                    len;
175 };
176
177 int nft_data_init(const struct nft_ctx *ctx,
178                   struct nft_data *data, unsigned int size,
179                   struct nft_data_desc *desc, const struct nlattr *nla);
180 void nft_data_release(const struct nft_data *data, enum nft_data_types type);
181 int nft_data_dump(struct sk_buff *skb, int attr, const struct nft_data *data,
182                   enum nft_data_types type, unsigned int len);
183
184 static inline enum nft_data_types nft_dreg_to_type(enum nft_registers reg)
185 {
186         return reg == NFT_REG_VERDICT ? NFT_DATA_VERDICT : NFT_DATA_VALUE;
187 }
188
189 static inline enum nft_registers nft_type_to_reg(enum nft_data_types type)
190 {
191         return type == NFT_DATA_VERDICT ? NFT_REG_VERDICT : NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE;
192 }
193
194 int nft_parse_u32_check(const struct nlattr *attr, int max, u32 *dest);
195 unsigned int nft_parse_register(const struct nlattr *attr);
196 int nft_dump_register(struct sk_buff *skb, unsigned int attr, unsigned int reg);
197
198 int nft_validate_register_load(enum nft_registers reg, unsigned int len);
199 int nft_validate_register_store(const struct nft_ctx *ctx,
200                                 enum nft_registers reg,
201                                 const struct nft_data *data,
202                                 enum nft_data_types type, unsigned int len);
203
204 /**
205  *      struct nft_userdata - user defined data associated with an object
206  *
207  *      @len: length of the data
208  *      @data: content
209  *
210  *      The presence of user data is indicated in an object specific fashion,
211  *      so a length of zero can't occur and the value "len" indicates data
212  *      of length len + 1.
213  */
214 struct nft_userdata {
215         u8                      len;
216         unsigned char           data[0];
217 };
218
219 /**
220  *      struct nft_set_elem - generic representation of set elements
221  *
222  *      @key: element key
223  *      @priv: element private data and extensions
224  */
225 struct nft_set_elem {
226         union {
227                 u32             buf[NFT_DATA_VALUE_MAXLEN / sizeof(u32)];
228                 struct nft_data val;
229         } key;
230         void                    *priv;
231 };
232
233 struct nft_set;
234 struct nft_set_iter {
235         u8              genmask;
236         unsigned int    count;
237         unsigned int    skip;
238         int             err;
239         int             (*fn)(const struct nft_ctx *ctx,
240                               struct nft_set *set,
241                               const struct nft_set_iter *iter,
242                               struct nft_set_elem *elem);
243 };
244
245 /**
246  *      struct nft_set_desc - description of set elements
247  *
248  *      @klen: key length
249  *      @dlen: data length
250  *      @size: number of set elements
251  */
252 struct nft_set_desc {
253         unsigned int            klen;
254         unsigned int            dlen;
255         unsigned int            size;
256 };
257
258 /**
259  *      enum nft_set_class - performance class
260  *
261  *      @NFT_LOOKUP_O_1: constant, O(1)
262  *      @NFT_LOOKUP_O_LOG_N: logarithmic, O(log N)
263  *      @NFT_LOOKUP_O_N: linear, O(N)
264  */
265 enum nft_set_class {
266         NFT_SET_CLASS_O_1,
267         NFT_SET_CLASS_O_LOG_N,
268         NFT_SET_CLASS_O_N,
269 };
270
271 /**
272  *      struct nft_set_estimate - estimation of memory and performance
273  *                                characteristics
274  *
275  *      @size: required memory
276  *      @lookup: lookup performance class
277  *      @space: memory class
278  */
279 struct nft_set_estimate {
280         unsigned int            size;
281         enum nft_set_class      lookup;
282         enum nft_set_class      space;
283 };
284
285 /**
286  *      struct nft_set_type - nf_tables set type
287  *
288  *      @select_ops: function to select nft_set_ops
289  *      @ops: default ops, used when no select_ops functions is present
290  *      @list: used internally
291  *      @owner: module reference
292  */
293 struct nft_set_type {
294         const struct nft_set_ops        *(*select_ops)(const struct nft_ctx *,
295                                                        const struct nft_set_desc *desc,
296                                                        u32 flags);
297         const struct nft_set_ops        *ops;
298         struct list_head                list;
299         struct module                   *owner;
300 };
301
302 struct nft_set_ext;
303 struct nft_expr;
304
305 /**
306  *      struct nft_set_ops - nf_tables set operations
307  *
308  *      @lookup: look up an element within the set
309  *      @insert: insert new element into set
310  *      @activate: activate new element in the next generation
311  *      @deactivate: lookup for element and deactivate it in the next generation
312  *      @flush: deactivate element in the next generation
313  *      @remove: remove element from set
314  *      @walk: iterate over all set elemeennts
315  *      @privsize: function to return size of set private data
316  *      @init: initialize private data of new set instance
317  *      @destroy: destroy private data of set instance
318  *      @elemsize: element private size
319  *      @features: features supported by the implementation
320  */
321 struct nft_set_ops {
322         bool                            (*lookup)(const struct net *net,
323                                                   const struct nft_set *set,
324                                                   const u32 *key,
325                                                   const struct nft_set_ext **ext);
326         bool                            (*update)(struct nft_set *set,
327                                                   const u32 *key,
328                                                   void *(*new)(struct nft_set *,
329                                                                const struct nft_expr *,
330                                                                struct nft_regs *),
331                                                   const struct nft_expr *expr,
332                                                   struct nft_regs *regs,
333                                                   const struct nft_set_ext **ext);
334
335         int                             (*insert)(const struct net *net,
336                                                   const struct nft_set *set,
337                                                   const struct nft_set_elem *elem,
338                                                   struct nft_set_ext **ext);
339         void                            (*activate)(const struct net *net,
340                                                     const struct nft_set *set,
341                                                     const struct nft_set_elem *elem);
342         void *                          (*deactivate)(const struct net *net,
343                                                       const struct nft_set *set,
344                                                       const struct nft_set_elem *elem);
345         bool                            (*flush)(const struct net *net,
346                                                  const struct nft_set *set,
347                                                  void *priv);
348         void                            (*remove)(const struct net *net,
349                                                   const struct nft_set *set,
350                                                   const struct nft_set_elem *elem);
351         void                            (*walk)(const struct nft_ctx *ctx,
352                                                 struct nft_set *set,
353                                                 struct nft_set_iter *iter);
354
355         unsigned int                    (*privsize)(const struct nlattr * const nla[],
356                                                     const struct nft_set_desc *desc);
357         bool                            (*estimate)(const struct nft_set_desc *desc,
358                                                     u32 features,
359                                                     struct nft_set_estimate *est);
360         int                             (*init)(const struct nft_set *set,
361                                                 const struct nft_set_desc *desc,
362                                                 const struct nlattr * const nla[]);
363         void                            (*destroy)(const struct nft_set *set);
364
365         unsigned int                    elemsize;
366         u32                             features;
367         const struct nft_set_type       *type;
368 };
369
370 int nft_register_set(struct nft_set_type *type);
371 void nft_unregister_set(struct nft_set_type *type);
372
373 /**
374  *      struct nft_set - nf_tables set instance
375  *
376  *      @list: table set list node
377  *      @bindings: list of set bindings
378  *      @name: name of the set
379  *      @ktype: key type (numeric type defined by userspace, not used in the kernel)
380  *      @dtype: data type (verdict or numeric type defined by userspace)
381  *      @objtype: object type (see NFT_OBJECT_* definitions)
382  *      @size: maximum set size
383  *      @nelems: number of elements
384  *      @ndeact: number of deactivated elements queued for removal
385  *      @timeout: default timeout value in jiffies
386  *      @gc_int: garbage collection interval in msecs
387  *      @policy: set parameterization (see enum nft_set_policies)
388  *      @udlen: user data length
389  *      @udata: user data
390  *      @ops: set ops
391  *      @flags: set flags
392  *      @genmask: generation mask
393  *      @klen: key length
394  *      @dlen: data length
395  *      @data: private set data
396  */
397 struct nft_set {
398         struct list_head                list;
399         struct list_head                bindings;
400         char                            *name;
401         u32                             ktype;
402         u32                             dtype;
403         u32                             objtype;
404         u32                             size;
405         atomic_t                        nelems;
406         u32                             ndeact;
407         u64                             timeout;
408         u32                             gc_int;
409         u16                             policy;
410         u16                             udlen;
411         unsigned char                   *udata;
412         /* runtime data below here */
413         const struct nft_set_ops        *ops ____cacheline_aligned;
414         u16                             flags:14,
415                                         genmask:2;
416         u8                              klen;
417         u8                              dlen;
418         unsigned char                   data[]
419                 __attribute__((aligned(__alignof__(u64))));
420 };
421
422 static inline void *nft_set_priv(const struct nft_set *set)
423 {
424         return (void *)set->data;
425 }
426
427 static inline struct nft_set *nft_set_container_of(const void *priv)
428 {
429         return (void *)priv - offsetof(struct nft_set, data);
430 }
431
432 struct nft_set *nft_set_lookup(const struct net *net,
433                                const struct nft_table *table,
434                                const struct nlattr *nla_set_name,
435                                const struct nlattr *nla_set_id,
436                                u8 genmask);
437
438 static inline unsigned long nft_set_gc_interval(const struct nft_set *set)
439 {
440         return set->gc_int ? msecs_to_jiffies(set->gc_int) : HZ;
441 }
442
443 /**
444  *      struct nft_set_binding - nf_tables set binding
445  *
446  *      @list: set bindings list node
447  *      @chain: chain containing the rule bound to the set
448  *      @flags: set action flags
449  *
450  *      A set binding contains all information necessary for validation
451  *      of new elements added to a bound set.
452  */
453 struct nft_set_binding {
454         struct list_head                list;
455         const struct nft_chain          *chain;
456         u32                             flags;
457 };
458
459 int nf_tables_bind_set(const struct nft_ctx *ctx, struct nft_set *set,
460                        struct nft_set_binding *binding);
461 void nf_tables_unbind_set(const struct nft_ctx *ctx, struct nft_set *set,
462                           struct nft_set_binding *binding);
463
464 /**
465  *      enum nft_set_extensions - set extension type IDs
466  *
467  *      @NFT_SET_EXT_KEY: element key
468  *      @NFT_SET_EXT_DATA: mapping data
469  *      @NFT_SET_EXT_FLAGS: element flags
470  *      @NFT_SET_EXT_TIMEOUT: element timeout
471  *      @NFT_SET_EXT_EXPIRATION: element expiration time
472  *      @NFT_SET_EXT_USERDATA: user data associated with the element
473  *      @NFT_SET_EXT_EXPR: expression assiociated with the element
474  *      @NFT_SET_EXT_OBJREF: stateful object reference associated with element
475  *      @NFT_SET_EXT_NUM: number of extension types
476  */
477 enum nft_set_extensions {
478         NFT_SET_EXT_KEY,
479         NFT_SET_EXT_DATA,
480         NFT_SET_EXT_FLAGS,
481         NFT_SET_EXT_TIMEOUT,
482         NFT_SET_EXT_EXPIRATION,
483         NFT_SET_EXT_USERDATA,
484         NFT_SET_EXT_EXPR,
485         NFT_SET_EXT_OBJREF,
486         NFT_SET_EXT_NUM
487 };
488
489 /**
490  *      struct nft_set_ext_type - set extension type
491  *
492  *      @len: fixed part length of the extension
493  *      @align: alignment requirements of the extension
494  */
495 struct nft_set_ext_type {
496         u8      len;
497         u8      align;
498 };
499
500 extern const struct nft_set_ext_type nft_set_ext_types[];
501
502 /**
503  *      struct nft_set_ext_tmpl - set extension template
504  *
505  *      @len: length of extension area
506  *      @offset: offsets of individual extension types
507  */
508 struct nft_set_ext_tmpl {
509         u16     len;
510         u8      offset[NFT_SET_EXT_NUM];
511 };
512
513 /**
514  *      struct nft_set_ext - set extensions
515  *
516  *      @genmask: generation mask
517  *      @offset: offsets of individual extension types
518  *      @data: beginning of extension data
519  */
520 struct nft_set_ext {
521         u8      genmask;
522         u8      offset[NFT_SET_EXT_NUM];
523         char    data[0];
524 };
525
526 static inline void nft_set_ext_prepare(struct nft_set_ext_tmpl *tmpl)
527 {
528         memset(tmpl, 0, sizeof(*tmpl));
529         tmpl->len = sizeof(struct nft_set_ext);
530 }
531
532 static inline void nft_set_ext_add_length(struct nft_set_ext_tmpl *tmpl, u8 id,
533                                           unsigned int len)
534 {
535         tmpl->len        = ALIGN(tmpl->len, nft_set_ext_types[id].align);
536         BUG_ON(tmpl->len > U8_MAX);
537         tmpl->offset[id] = tmpl->len;
538         tmpl->len       += nft_set_ext_types[id].len + len;
539 }
540
541 static inline void nft_set_ext_add(struct nft_set_ext_tmpl *tmpl, u8 id)
542 {
543         nft_set_ext_add_length(tmpl, id, 0);
544 }
545
546 static inline void nft_set_ext_init(struct nft_set_ext *ext,
547                                     const struct nft_set_ext_tmpl *tmpl)
548 {
549         memcpy(ext->offset, tmpl->offset, sizeof(ext->offset));
550 }
551
552 static inline bool __nft_set_ext_exists(const struct nft_set_ext *ext, u8 id)
553 {
554         return !!ext->offset[id];
555 }
556
557 static inline bool nft_set_ext_exists(const struct nft_set_ext *ext, u8 id)
558 {
559         return ext && __nft_set_ext_exists(ext, id);
560 }
561
562 static inline void *nft_set_ext(const struct nft_set_ext *ext, u8 id)
563 {
564         return (void *)ext + ext->offset[id];
565 }
566
567 static inline struct nft_data *nft_set_ext_key(const struct nft_set_ext *ext)
568 {
569         return nft_set_ext(ext, NFT_SET_EXT_KEY);
570 }
571
572 static inline struct nft_data *nft_set_ext_data(const struct nft_set_ext *ext)
573 {
574         return nft_set_ext(ext, NFT_SET_EXT_DATA);
575 }
576
577 static inline u8 *nft_set_ext_flags(const struct nft_set_ext *ext)
578 {
579         return nft_set_ext(ext, NFT_SET_EXT_FLAGS);
580 }
581
582 static inline u64 *nft_set_ext_timeout(const struct nft_set_ext *ext)
583 {
584         return nft_set_ext(ext, NFT_SET_EXT_TIMEOUT);
585 }
586
587 static inline unsigned long *nft_set_ext_expiration(const struct nft_set_ext *ext)
588 {
589         return nft_set_ext(ext, NFT_SET_EXT_EXPIRATION);
590 }
591
592 static inline struct nft_userdata *nft_set_ext_userdata(const struct nft_set_ext *ext)
593 {
594         return nft_set_ext(ext, NFT_SET_EXT_USERDATA);
595 }
596
597 static inline struct nft_expr *nft_set_ext_expr(const struct nft_set_ext *ext)
598 {
599         return nft_set_ext(ext, NFT_SET_EXT_EXPR);
600 }
601
602 static inline bool nft_set_elem_expired(const struct nft_set_ext *ext)
603 {
604         return nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION) &&
605                time_is_before_eq_jiffies(*nft_set_ext_expiration(ext));
606 }
607
608 static inline struct nft_set_ext *nft_set_elem_ext(const struct nft_set *set,
609                                                    void *elem)
610 {
611         return elem + set->ops->elemsize;
612 }
613
614 static inline struct nft_object **nft_set_ext_obj(const struct nft_set_ext *ext)
615 {
616         return nft_set_ext(ext, NFT_SET_EXT_OBJREF);
617 }
618
619 void *nft_set_elem_init(const struct nft_set *set,
620                         const struct nft_set_ext_tmpl *tmpl,
621                         const u32 *key, const u32 *data,
622                         u64 timeout, gfp_t gfp);
623 void nft_set_elem_destroy(const struct nft_set *set, void *elem,
624                           bool destroy_expr);
625
626 /**
627  *      struct nft_set_gc_batch_head - nf_tables set garbage collection batch
628  *
629  *      @rcu: rcu head
630  *      @set: set the elements belong to
631  *      @cnt: count of elements
632  */
633 struct nft_set_gc_batch_head {
634         struct rcu_head                 rcu;
635         const struct nft_set            *set;
636         unsigned int                    cnt;
637 };
638
639 #define NFT_SET_GC_BATCH_SIZE   ((PAGE_SIZE -                             \
640                                   sizeof(struct nft_set_gc_batch_head)) / \
641                                  sizeof(void *))
642
643 /**
644  *      struct nft_set_gc_batch - nf_tables set garbage collection batch
645  *
646  *      @head: GC batch head
647  *      @elems: garbage collection elements
648  */
649 struct nft_set_gc_batch {
650         struct nft_set_gc_batch_head    head;
651         void                            *elems[NFT_SET_GC_BATCH_SIZE];
652 };
653
654 struct nft_set_gc_batch *nft_set_gc_batch_alloc(const struct nft_set *set,
655                                                 gfp_t gfp);
656 void nft_set_gc_batch_release(struct rcu_head *rcu);
657
658 static inline void nft_set_gc_batch_complete(struct nft_set_gc_batch *gcb)
659 {
660         if (gcb != NULL)
661                 call_rcu(&gcb->head.rcu, nft_set_gc_batch_release);
662 }
663
664 static inline struct nft_set_gc_batch *
665 nft_set_gc_batch_check(const struct nft_set *set, struct nft_set_gc_batch *gcb,
666                        gfp_t gfp)
667 {
668         if (gcb != NULL) {
669                 if (gcb->head.cnt + 1 < ARRAY_SIZE(gcb->elems))
670                         return gcb;
671                 nft_set_gc_batch_complete(gcb);
672         }
673         return nft_set_gc_batch_alloc(set, gfp);
674 }
675
676 static inline void nft_set_gc_batch_add(struct nft_set_gc_batch *gcb,
677                                         void *elem)
678 {
679         gcb->elems[gcb->head.cnt++] = elem;
680 }
681
682 /**
683  *      struct nft_expr_type - nf_tables expression type
684  *
685  *      @select_ops: function to select nft_expr_ops
686  *      @ops: default ops, used when no select_ops functions is present
687  *      @list: used internally
688  *      @name: Identifier
689  *      @owner: module reference
690  *      @policy: netlink attribute policy
691  *      @maxattr: highest netlink attribute number
692  *      @family: address family for AF-specific types
693  *      @flags: expression type flags
694  */
695 struct nft_expr_type {
696         const struct nft_expr_ops       *(*select_ops)(const struct nft_ctx *,
697                                                        const struct nlattr * const tb[]);
698         const struct nft_expr_ops       *ops;
699         struct list_head                list;
700         const char                      *name;
701         struct module                   *owner;
702         const struct nla_policy         *policy;
703         unsigned int                    maxattr;
704         u8                              family;
705         u8                              flags;
706 };
707
708 #define NFT_EXPR_STATEFUL               0x1
709
710 /**
711  *      struct nft_expr_ops - nf_tables expression operations
712  *
713  *      @eval: Expression evaluation function
714  *      @size: full expression size, including private data size
715  *      @init: initialization function
716  *      @destroy: destruction function
717  *      @dump: function to dump parameters
718  *      @type: expression type
719  *      @validate: validate expression, called during loop detection
720  *      @data: extra data to attach to this expression operation
721  */
722 struct nft_expr;
723 struct nft_expr_ops {
724         void                            (*eval)(const struct nft_expr *expr,
725                                                 struct nft_regs *regs,
726                                                 const struct nft_pktinfo *pkt);
727         int                             (*clone)(struct nft_expr *dst,
728                                                  const struct nft_expr *src);
729         unsigned int                    size;
730
731         int                             (*init)(const struct nft_ctx *ctx,
732                                                 const struct nft_expr *expr,
733                                                 const struct nlattr * const tb[]);
734         void                            (*destroy)(const struct nft_ctx *ctx,
735                                                    const struct nft_expr *expr);
736         int                             (*dump)(struct sk_buff *skb,
737                                                 const struct nft_expr *expr);
738         int                             (*validate)(const struct nft_ctx *ctx,
739                                                     const struct nft_expr *expr,
740                                                     const struct nft_data **data);
741         const struct nft_expr_type      *type;
742         void                            *data;
743 };
744
745 #define NFT_EXPR_MAXATTR                16
746 #define NFT_EXPR_SIZE(size)             (sizeof(struct nft_expr) + \
747                                          ALIGN(size, __alignof__(struct nft_expr)))
748
749 /**
750  *      struct nft_expr - nf_tables expression
751  *
752  *      @ops: expression ops
753  *      @data: expression private data
754  */
755 struct nft_expr {
756         const struct nft_expr_ops       *ops;
757         unsigned char                   data[];
758 };
759
760 static inline void *nft_expr_priv(const struct nft_expr *expr)
761 {
762         return (void *)expr->data;
763 }
764
765 struct nft_expr *nft_expr_init(const struct nft_ctx *ctx,
766                                const struct nlattr *nla);
767 void nft_expr_destroy(const struct nft_ctx *ctx, struct nft_expr *expr);
768 int nft_expr_dump(struct sk_buff *skb, unsigned int attr,
769                   const struct nft_expr *expr);
770
771 static inline int nft_expr_clone(struct nft_expr *dst, struct nft_expr *src)
772 {
773         int err;
774
775         if (src->ops->clone) {
776                 dst->ops = src->ops;
777                 err = src->ops->clone(dst, src);
778                 if (err < 0)
779                         return err;
780         } else {
781                 memcpy(dst, src, src->ops->size);
782         }
783
784         __module_get(src->ops->type->owner);
785         return 0;
786 }
787
788 /**
789  *      struct nft_rule - nf_tables rule
790  *
791  *      @list: used internally
792  *      @handle: rule handle
793  *      @genmask: generation mask
794  *      @dlen: length of expression data
795  *      @udata: user data is appended to the rule
796  *      @data: expression data
797  */
798 struct nft_rule {
799         struct list_head                list;
800         u64                             handle:42,
801                                         genmask:2,
802                                         dlen:12,
803                                         udata:1;
804         unsigned char                   data[]
805                 __attribute__((aligned(__alignof__(struct nft_expr))));
806 };
807
808 static inline struct nft_expr *nft_expr_first(const struct nft_rule *rule)
809 {
810         return (struct nft_expr *)&rule->data[0];
811 }
812
813 static inline struct nft_expr *nft_expr_next(const struct nft_expr *expr)
814 {
815         return ((void *)expr) + expr->ops->size;
816 }
817
818 static inline struct nft_expr *nft_expr_last(const struct nft_rule *rule)
819 {
820         return (struct nft_expr *)&rule->data[rule->dlen];
821 }
822
823 static inline struct nft_userdata *nft_userdata(const struct nft_rule *rule)
824 {
825         return (void *)&rule->data[rule->dlen];
826 }
827
828 /*
829  * The last pointer isn't really necessary, but the compiler isn't able to
830  * determine that the result of nft_expr_last() is always the same since it
831  * can't assume that the dlen value wasn't changed within calls in the loop.
832  */
833 #define nft_rule_for_each_expr(expr, last, rule) \
834         for ((expr) = nft_expr_first(rule), (last) = nft_expr_last(rule); \
835              (expr) != (last); \
836              (expr) = nft_expr_next(expr))
837
838 enum nft_chain_flags {
839         NFT_BASE_CHAIN                  = 0x1,
840 };
841
842 /**
843  *      struct nft_chain - nf_tables chain
844  *
845  *      @rules: list of rules in the chain
846  *      @list: used internally
847  *      @table: table that this chain belongs to
848  *      @handle: chain handle
849  *      @use: number of jump references to this chain
850  *      @level: length of longest path to this chain
851  *      @flags: bitmask of enum nft_chain_flags
852  *      @name: name of the chain
853  */
854 struct nft_chain {
855         struct list_head                rules;
856         struct list_head                list;
857         struct nft_table                *table;
858         u64                             handle;
859         u32                             use;
860         u16                             level;
861         u8                              flags:6,
862                                         genmask:2;
863         char                            *name;
864 };
865
866 enum nft_chain_type {
867         NFT_CHAIN_T_DEFAULT = 0,
868         NFT_CHAIN_T_ROUTE,
869         NFT_CHAIN_T_NAT,
870         NFT_CHAIN_T_MAX
871 };
872
873 /**
874  *      struct nf_chain_type - nf_tables chain type info
875  *
876  *      @name: name of the type
877  *      @type: numeric identifier
878  *      @family: address family
879  *      @owner: module owner
880  *      @hook_mask: mask of valid hooks
881  *      @hooks: hookfn overrides
882  */
883 struct nf_chain_type {
884         const char                      *name;
885         enum nft_chain_type             type;
886         int                             family;
887         struct module                   *owner;
888         unsigned int                    hook_mask;
889         nf_hookfn                       *hooks[NF_MAX_HOOKS];
890 };
891
892 int nft_chain_validate_dependency(const struct nft_chain *chain,
893                                   enum nft_chain_type type);
894 int nft_chain_validate_hooks(const struct nft_chain *chain,
895                              unsigned int hook_flags);
896
897 struct nft_stats {
898         u64                     bytes;
899         u64                     pkts;
900         struct u64_stats_sync   syncp;
901 };
902
903 #define NFT_HOOK_OPS_MAX                2
904
905 /**
906  *      struct nft_base_chain - nf_tables base chain
907  *
908  *      @ops: netfilter hook ops
909  *      @type: chain type
910  *      @policy: default policy
911  *      @stats: per-cpu chain stats
912  *      @chain: the chain
913  *      @dev_name: device name that this base chain is attached to (if any)
914  */
915 struct nft_base_chain {
916         struct nf_hook_ops              ops[NFT_HOOK_OPS_MAX];
917         const struct nf_chain_type      *type;
918         u8                              policy;
919         u8                              flags;
920         struct nft_stats __percpu       *stats;
921         struct nft_chain                chain;
922         char                            dev_name[IFNAMSIZ];
923 };
924
925 static inline struct nft_base_chain *nft_base_chain(const struct nft_chain *chain)
926 {
927         return container_of(chain, struct nft_base_chain, chain);
928 }
929
930 static inline bool nft_is_base_chain(const struct nft_chain *chain)
931 {
932         return chain->flags & NFT_BASE_CHAIN;
933 }
934
935 int __nft_release_basechain(struct nft_ctx *ctx);
936
937 unsigned int nft_do_chain(struct nft_pktinfo *pkt, void *priv);
938
939 /**
940  *      struct nft_table - nf_tables table
941  *
942  *      @list: used internally
943  *      @chains: chains in the table
944  *      @sets: sets in the table
945  *      @objects: stateful objects in the table
946  *      @hgenerator: handle generator state
947  *      @use: number of chain references to this table
948  *      @flags: table flag (see enum nft_table_flags)
949  *      @genmask: generation mask
950  *      @name: name of the table
951  */
952 struct nft_table {
953         struct list_head                list;
954         struct list_head                chains;
955         struct list_head                sets;
956         struct list_head                objects;
957         u64                             hgenerator;
958         u32                             use;
959         u16                             flags:14,
960                                         genmask:2;
961         char                            *name;
962 };
963
964 enum nft_af_flags {
965         NFT_AF_NEEDS_DEV        = (1 << 0),
966 };
967
968 /**
969  *      struct nft_af_info - nf_tables address family info
970  *
971  *      @list: used internally
972  *      @family: address family
973  *      @nhooks: number of hooks in this family
974  *      @owner: module owner
975  *      @tables: used internally
976  *      @flags: family flags
977  *      @nops: number of hook ops in this family
978  *      @hook_ops_init: initialization function for chain hook ops
979  *      @hooks: hookfn overrides for packet validation
980  */
981 struct nft_af_info {
982         struct list_head                list;
983         int                             family;
984         unsigned int                    nhooks;
985         struct module                   *owner;
986         struct list_head                tables;
987         u32                             flags;
988         unsigned int                    nops;
989         void                            (*hook_ops_init)(struct nf_hook_ops *,
990                                                          unsigned int);
991         nf_hookfn                       *hooks[NF_MAX_HOOKS];
992 };
993
994 int nft_register_afinfo(struct net *, struct nft_af_info *);
995 void nft_unregister_afinfo(struct net *, struct nft_af_info *);
996
997 int nft_register_chain_type(const struct nf_chain_type *);
998 void nft_unregister_chain_type(const struct nf_chain_type *);
999
1000 int nft_register_expr(struct nft_expr_type *);
1001 void nft_unregister_expr(struct nft_expr_type *);
1002
1003 int nft_verdict_dump(struct sk_buff *skb, int type,
1004                      const struct nft_verdict *v);
1005
1006 /**
1007  *      struct nft_object - nf_tables stateful object
1008  *
1009  *      @list: table stateful object list node
1010  *      @table: table this object belongs to
1011  *      @name: name of this stateful object
1012  *      @genmask: generation mask
1013  *      @use: number of references to this stateful object
1014  *      @data: object data, layout depends on type
1015  *      @ops: object operations
1016  *      @data: pointer to object data
1017  */
1018 struct nft_object {
1019         struct list_head                list;
1020         char                            *name;
1021         struct nft_table                *table;
1022         u32                             genmask:2,
1023                                         use:30;
1024         /* runtime data below here */
1025         const struct nft_object_ops     *ops ____cacheline_aligned;
1026         unsigned char                   data[]
1027                 __attribute__((aligned(__alignof__(u64))));
1028 };
1029
1030 static inline void *nft_obj_data(const struct nft_object *obj)
1031 {
1032         return (void *)obj->data;
1033 }
1034
1035 #define nft_expr_obj(expr)      *((struct nft_object **)nft_expr_priv(expr))
1036
1037 struct nft_object *nf_tables_obj_lookup(const struct nft_table *table,
1038                                         const struct nlattr *nla, u32 objtype,
1039                                         u8 genmask);
1040
1041 void nft_obj_notify(struct net *net, struct nft_table *table,
1042                     struct nft_object *obj, u32 portid, u32 seq,
1043                     int event, int family, int report, gfp_t gfp);
1044
1045 /**
1046  *      struct nft_object_type - stateful object type
1047  *
1048  *      @select_ops: function to select nft_object_ops
1049  *      @ops: default ops, used when no select_ops functions is present
1050  *      @list: list node in list of object types
1051  *      @type: stateful object numeric type
1052  *      @owner: module owner
1053  *      @maxattr: maximum netlink attribute
1054  *      @policy: netlink attribute policy
1055  */
1056 struct nft_object_type {
1057         const struct nft_object_ops     *(*select_ops)(const struct nft_ctx *,
1058                                                        const struct nlattr * const tb[]);
1059         const struct nft_object_ops     *ops;
1060         struct list_head                list;
1061         u32                             type;
1062         unsigned int                    maxattr;
1063         struct module                   *owner;
1064         const struct nla_policy         *policy;
1065 };
1066
1067 /**
1068  *      struct nft_object_ops - stateful object operations
1069  *
1070  *      @eval: stateful object evaluation function
1071  *      @size: stateful object size
1072  *      @init: initialize object from netlink attributes
1073  *      @destroy: release existing stateful object
1074  *      @dump: netlink dump stateful object
1075  */
1076 struct nft_object_ops {
1077         void                            (*eval)(struct nft_object *obj,
1078                                                 struct nft_regs *regs,
1079                                                 const struct nft_pktinfo *pkt);
1080         unsigned int                    size;
1081         int                             (*init)(const struct nft_ctx *ctx,
1082                                                 const struct nlattr *const tb[],
1083                                                 struct nft_object *obj);
1084         void                            (*destroy)(struct nft_object *obj);
1085         int                             (*dump)(struct sk_buff *skb,
1086                                                 struct nft_object *obj,
1087                                                 bool reset);
1088         const struct nft_object_type    *type;
1089 };
1090
1091 int nft_register_obj(struct nft_object_type *obj_type);
1092 void nft_unregister_obj(struct nft_object_type *obj_type);
1093
1094 /**
1095  *      struct nft_traceinfo - nft tracing information and state
1096  *
1097  *      @pkt: pktinfo currently processed
1098  *      @basechain: base chain currently processed
1099  *      @chain: chain currently processed
1100  *      @rule:  rule that was evaluated
1101  *      @verdict: verdict given by rule
1102  *      @type: event type (enum nft_trace_types)
1103  *      @packet_dumped: packet headers sent in a previous traceinfo message
1104  *      @trace: other struct members are initialised
1105  */
1106 struct nft_traceinfo {
1107         const struct nft_pktinfo        *pkt;
1108         const struct nft_base_chain     *basechain;
1109         const struct nft_chain          *chain;
1110         const struct nft_rule           *rule;
1111         const struct nft_verdict        *verdict;
1112         enum nft_trace_types            type;
1113         bool                            packet_dumped;
1114         bool                            trace;
1115 };
1116
1117 void nft_trace_init(struct nft_traceinfo *info, const struct nft_pktinfo *pkt,
1118                     const struct nft_verdict *verdict,
1119                     const struct nft_chain *basechain);
1120
1121 void nft_trace_notify(struct nft_traceinfo *info);
1122
1123 #define nft_dereference(p)                                      \
1124         nfnl_dereference(p, NFNL_SUBSYS_NFTABLES)
1125
1126 #define MODULE_ALIAS_NFT_FAMILY(family) \
1127         MODULE_ALIAS("nft-afinfo-" __stringify(family))
1128
1129 #define MODULE_ALIAS_NFT_CHAIN(family, name) \
1130         MODULE_ALIAS("nft-chain-" __stringify(family) "-" name)
1131
1132 #define MODULE_ALIAS_NFT_AF_EXPR(family, name) \
1133         MODULE_ALIAS("nft-expr-" __stringify(family) "-" name)
1134
1135 #define MODULE_ALIAS_NFT_EXPR(name) \
1136         MODULE_ALIAS("nft-expr-" name)
1137
1138 #define MODULE_ALIAS_NFT_SET() \
1139         MODULE_ALIAS("nft-set")
1140
1141 #define MODULE_ALIAS_NFT_OBJ(type) \
1142         MODULE_ALIAS("nft-obj-" __stringify(type))
1143
1144 /*
1145  * The gencursor defines two generations, the currently active and the
1146  * next one. Objects contain a bitmask of 2 bits specifying the generations
1147  * they're active in. A set bit means they're inactive in the generation
1148  * represented by that bit.
1149  *
1150  * New objects start out as inactive in the current and active in the
1151  * next generation. When committing the ruleset the bitmask is cleared,
1152  * meaning they're active in all generations. When removing an object,
1153  * it is set inactive in the next generation. After committing the ruleset,
1154  * the objects are removed.
1155  */
1156 static inline unsigned int nft_gencursor_next(const struct net *net)
1157 {
1158         return net->nft.gencursor + 1 == 1 ? 1 : 0;
1159 }
1160
1161 static inline u8 nft_genmask_next(const struct net *net)
1162 {
1163         return 1 << nft_gencursor_next(net);
1164 }
1165
1166 static inline u8 nft_genmask_cur(const struct net *net)
1167 {
1168         /* Use READ_ONCE() to prevent refetching the value for atomicity */
1169         return 1 << READ_ONCE(net->nft.gencursor);
1170 }
1171
1172 #define NFT_GENMASK_ANY         ((1 << 0) | (1 << 1))
1173
1174 /*
1175  * Generic transaction helpers
1176  */
1177
1178 /* Check if this object is currently active. */
1179 #define nft_is_active(__net, __obj)                             \
1180         (((__obj)->genmask & nft_genmask_cur(__net)) == 0)
1181
1182 /* Check if this object is active in the next generation. */
1183 #define nft_is_active_next(__net, __obj)                        \
1184         (((__obj)->genmask & nft_genmask_next(__net)) == 0)
1185
1186 /* This object becomes active in the next generation. */
1187 #define nft_activate_next(__net, __obj)                         \
1188         (__obj)->genmask = nft_genmask_cur(__net)
1189
1190 /* This object becomes inactive in the next generation. */
1191 #define nft_deactivate_next(__net, __obj)                       \
1192         (__obj)->genmask = nft_genmask_next(__net)
1193
1194 /* After committing the ruleset, clear the stale generation bit. */
1195 #define nft_clear(__net, __obj)                                 \
1196         (__obj)->genmask &= ~nft_genmask_next(__net)
1197 #define nft_active_genmask(__obj, __genmask)                    \
1198         !((__obj)->genmask & __genmask)
1199
1200 /*
1201  * Set element transaction helpers
1202  */
1203
1204 static inline bool nft_set_elem_active(const struct nft_set_ext *ext,
1205                                        u8 genmask)
1206 {
1207         return !(ext->genmask & genmask);
1208 }
1209
1210 static inline void nft_set_elem_change_active(const struct net *net,
1211                                               const struct nft_set *set,
1212                                               struct nft_set_ext *ext)
1213 {
1214         ext->genmask ^= nft_genmask_next(net);
1215 }
1216
1217 /*
1218  * We use a free bit in the genmask field to indicate the element
1219  * is busy, meaning it is currently being processed either by
1220  * the netlink API or GC.
1221  *
1222  * Even though the genmask is only a single byte wide, this works
1223  * because the extension structure if fully constant once initialized,
1224  * so there are no non-atomic write accesses unless it is already
1225  * marked busy.
1226  */
1227 #define NFT_SET_ELEM_BUSY_MASK  (1 << 2)
1228
1229 #if defined(__LITTLE_ENDIAN_BITFIELD)
1230 #define NFT_SET_ELEM_BUSY_BIT   2
1231 #elif defined(__BIG_ENDIAN_BITFIELD)
1232 #define NFT_SET_ELEM_BUSY_BIT   (BITS_PER_LONG - BITS_PER_BYTE + 2)
1233 #else
1234 #error
1235 #endif
1236
1237 static inline int nft_set_elem_mark_busy(struct nft_set_ext *ext)
1238 {
1239         unsigned long *word = (unsigned long *)ext;
1240
1241         BUILD_BUG_ON(offsetof(struct nft_set_ext, genmask) != 0);
1242         return test_and_set_bit(NFT_SET_ELEM_BUSY_BIT, word);
1243 }
1244
1245 static inline void nft_set_elem_clear_busy(struct nft_set_ext *ext)
1246 {
1247         unsigned long *word = (unsigned long *)ext;
1248
1249         clear_bit(NFT_SET_ELEM_BUSY_BIT, word);
1250 }
1251
1252 /**
1253  *      struct nft_trans - nf_tables object update in transaction
1254  *
1255  *      @list: used internally
1256  *      @msg_type: message type
1257  *      @ctx: transaction context
1258  *      @data: internal information related to the transaction
1259  */
1260 struct nft_trans {
1261         struct list_head                list;
1262         int                             msg_type;
1263         struct nft_ctx                  ctx;
1264         char                            data[0];
1265 };
1266
1267 struct nft_trans_rule {
1268         struct nft_rule                 *rule;
1269         u32                             rule_id;
1270 };
1271
1272 #define nft_trans_rule(trans)   \
1273         (((struct nft_trans_rule *)trans->data)->rule)
1274 #define nft_trans_rule_id(trans)        \
1275         (((struct nft_trans_rule *)trans->data)->rule_id)
1276
1277 struct nft_trans_set {
1278         struct nft_set                  *set;
1279         u32                             set_id;
1280 };
1281
1282 #define nft_trans_set(trans)    \
1283         (((struct nft_trans_set *)trans->data)->set)
1284 #define nft_trans_set_id(trans) \
1285         (((struct nft_trans_set *)trans->data)->set_id)
1286
1287 struct nft_trans_chain {
1288         bool                            update;
1289         char                            *name;
1290         struct nft_stats __percpu       *stats;
1291         u8                              policy;
1292 };
1293
1294 #define nft_trans_chain_update(trans)   \
1295         (((struct nft_trans_chain *)trans->data)->update)
1296 #define nft_trans_chain_name(trans)     \
1297         (((struct nft_trans_chain *)trans->data)->name)
1298 #define nft_trans_chain_stats(trans)    \
1299         (((struct nft_trans_chain *)trans->data)->stats)
1300 #define nft_trans_chain_policy(trans)   \
1301         (((struct nft_trans_chain *)trans->data)->policy)
1302
1303 struct nft_trans_table {
1304         bool                            update;
1305         bool                            enable;
1306 };
1307
1308 #define nft_trans_table_update(trans)   \
1309         (((struct nft_trans_table *)trans->data)->update)
1310 #define nft_trans_table_enable(trans)   \
1311         (((struct nft_trans_table *)trans->data)->enable)
1312
1313 struct nft_trans_elem {
1314         struct nft_set                  *set;
1315         struct nft_set_elem             elem;
1316 };
1317
1318 #define nft_trans_elem_set(trans)       \
1319         (((struct nft_trans_elem *)trans->data)->set)
1320 #define nft_trans_elem(trans)   \
1321         (((struct nft_trans_elem *)trans->data)->elem)
1322
1323 struct nft_trans_obj {
1324         struct nft_object               *obj;
1325 };
1326
1327 #define nft_trans_obj(trans)    \
1328         (((struct nft_trans_obj *)trans->data)->obj)
1329
1330 #endif /* _NET_NF_TABLES_H */