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