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