OSDN Git Service

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