Merge branch 'next-lockdown' of git://git.kernel.org/pub/scm/linux/kernel/git/jmorris...
[linux-2.6-microblaze.git] / net / netfilter / nf_tables_api.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2007-2009 Patrick McHardy <kaber@trash.net>
4  *
5  * Development of this code funded by Astaro AG (http://www.astaro.com/)
6  */
7
8 #include <linux/module.h>
9 #include <linux/init.h>
10 #include <linux/list.h>
11 #include <linux/skbuff.h>
12 #include <linux/netlink.h>
13 #include <linux/vmalloc.h>
14 #include <linux/rhashtable.h>
15 #include <linux/netfilter.h>
16 #include <linux/netfilter/nfnetlink.h>
17 #include <linux/netfilter/nf_tables.h>
18 #include <net/netfilter/nf_flow_table.h>
19 #include <net/netfilter/nf_tables_core.h>
20 #include <net/netfilter/nf_tables.h>
21 #include <net/netfilter/nf_tables_offload.h>
22 #include <net/net_namespace.h>
23 #include <net/sock.h>
24
25 static LIST_HEAD(nf_tables_expressions);
26 static LIST_HEAD(nf_tables_objects);
27 static LIST_HEAD(nf_tables_flowtables);
28 static LIST_HEAD(nf_tables_destroy_list);
29 static DEFINE_SPINLOCK(nf_tables_destroy_list_lock);
30 static u64 table_handle;
31
32 enum {
33         NFT_VALIDATE_SKIP       = 0,
34         NFT_VALIDATE_NEED,
35         NFT_VALIDATE_DO,
36 };
37
38 static struct rhltable nft_objname_ht;
39
40 static u32 nft_chain_hash(const void *data, u32 len, u32 seed);
41 static u32 nft_chain_hash_obj(const void *data, u32 len, u32 seed);
42 static int nft_chain_hash_cmp(struct rhashtable_compare_arg *, const void *);
43
44 static u32 nft_objname_hash(const void *data, u32 len, u32 seed);
45 static u32 nft_objname_hash_obj(const void *data, u32 len, u32 seed);
46 static int nft_objname_hash_cmp(struct rhashtable_compare_arg *, const void *);
47
48 static const struct rhashtable_params nft_chain_ht_params = {
49         .head_offset            = offsetof(struct nft_chain, rhlhead),
50         .key_offset             = offsetof(struct nft_chain, name),
51         .hashfn                 = nft_chain_hash,
52         .obj_hashfn             = nft_chain_hash_obj,
53         .obj_cmpfn              = nft_chain_hash_cmp,
54         .automatic_shrinking    = true,
55 };
56
57 static const struct rhashtable_params nft_objname_ht_params = {
58         .head_offset            = offsetof(struct nft_object, rhlhead),
59         .key_offset             = offsetof(struct nft_object, key),
60         .hashfn                 = nft_objname_hash,
61         .obj_hashfn             = nft_objname_hash_obj,
62         .obj_cmpfn              = nft_objname_hash_cmp,
63         .automatic_shrinking    = true,
64 };
65
66 static void nft_validate_state_update(struct net *net, u8 new_validate_state)
67 {
68         switch (net->nft.validate_state) {
69         case NFT_VALIDATE_SKIP:
70                 WARN_ON_ONCE(new_validate_state == NFT_VALIDATE_DO);
71                 break;
72         case NFT_VALIDATE_NEED:
73                 break;
74         case NFT_VALIDATE_DO:
75                 if (new_validate_state == NFT_VALIDATE_NEED)
76                         return;
77         }
78
79         net->nft.validate_state = new_validate_state;
80 }
81 static void nf_tables_trans_destroy_work(struct work_struct *w);
82 static DECLARE_WORK(trans_destroy_work, nf_tables_trans_destroy_work);
83
84 static void nft_ctx_init(struct nft_ctx *ctx,
85                          struct net *net,
86                          const struct sk_buff *skb,
87                          const struct nlmsghdr *nlh,
88                          u8 family,
89                          struct nft_table *table,
90                          struct nft_chain *chain,
91                          const struct nlattr * const *nla)
92 {
93         ctx->net        = net;
94         ctx->family     = family;
95         ctx->level      = 0;
96         ctx->table      = table;
97         ctx->chain      = chain;
98         ctx->nla        = nla;
99         ctx->portid     = NETLINK_CB(skb).portid;
100         ctx->report     = nlmsg_report(nlh);
101         ctx->flags      = nlh->nlmsg_flags;
102         ctx->seq        = nlh->nlmsg_seq;
103 }
104
105 static struct nft_trans *nft_trans_alloc_gfp(const struct nft_ctx *ctx,
106                                              int msg_type, u32 size, gfp_t gfp)
107 {
108         struct nft_trans *trans;
109
110         trans = kzalloc(sizeof(struct nft_trans) + size, gfp);
111         if (trans == NULL)
112                 return NULL;
113
114         trans->msg_type = msg_type;
115         trans->ctx      = *ctx;
116
117         return trans;
118 }
119
120 static struct nft_trans *nft_trans_alloc(const struct nft_ctx *ctx,
121                                          int msg_type, u32 size)
122 {
123         return nft_trans_alloc_gfp(ctx, msg_type, size, GFP_KERNEL);
124 }
125
126 static void nft_trans_destroy(struct nft_trans *trans)
127 {
128         list_del(&trans->list);
129         kfree(trans);
130 }
131
132 static void nft_set_trans_bind(const struct nft_ctx *ctx, struct nft_set *set)
133 {
134         struct net *net = ctx->net;
135         struct nft_trans *trans;
136
137         if (!nft_set_is_anonymous(set))
138                 return;
139
140         list_for_each_entry_reverse(trans, &net->nft.commit_list, list) {
141                 switch (trans->msg_type) {
142                 case NFT_MSG_NEWSET:
143                         if (nft_trans_set(trans) == set)
144                                 nft_trans_set_bound(trans) = true;
145                         break;
146                 case NFT_MSG_NEWSETELEM:
147                         if (nft_trans_elem_set(trans) == set)
148                                 nft_trans_elem_set_bound(trans) = true;
149                         break;
150                 }
151         }
152 }
153
154 static int nf_tables_register_hook(struct net *net,
155                                    const struct nft_table *table,
156                                    struct nft_chain *chain)
157 {
158         const struct nft_base_chain *basechain;
159         const struct nf_hook_ops *ops;
160
161         if (table->flags & NFT_TABLE_F_DORMANT ||
162             !nft_is_base_chain(chain))
163                 return 0;
164
165         basechain = nft_base_chain(chain);
166         ops = &basechain->ops;
167
168         if (basechain->type->ops_register)
169                 return basechain->type->ops_register(net, ops);
170
171         return nf_register_net_hook(net, ops);
172 }
173
174 static void nf_tables_unregister_hook(struct net *net,
175                                       const struct nft_table *table,
176                                       struct nft_chain *chain)
177 {
178         const struct nft_base_chain *basechain;
179         const struct nf_hook_ops *ops;
180
181         if (table->flags & NFT_TABLE_F_DORMANT ||
182             !nft_is_base_chain(chain))
183                 return;
184         basechain = nft_base_chain(chain);
185         ops = &basechain->ops;
186
187         if (basechain->type->ops_unregister)
188                 return basechain->type->ops_unregister(net, ops);
189
190         nf_unregister_net_hook(net, ops);
191 }
192
193 static int nft_trans_table_add(struct nft_ctx *ctx, int msg_type)
194 {
195         struct nft_trans *trans;
196
197         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_table));
198         if (trans == NULL)
199                 return -ENOMEM;
200
201         if (msg_type == NFT_MSG_NEWTABLE)
202                 nft_activate_next(ctx->net, ctx->table);
203
204         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
205         return 0;
206 }
207
208 static int nft_deltable(struct nft_ctx *ctx)
209 {
210         int err;
211
212         err = nft_trans_table_add(ctx, NFT_MSG_DELTABLE);
213         if (err < 0)
214                 return err;
215
216         nft_deactivate_next(ctx->net, ctx->table);
217         return err;
218 }
219
220 static struct nft_trans *nft_trans_chain_add(struct nft_ctx *ctx, int msg_type)
221 {
222         struct nft_trans *trans;
223
224         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_chain));
225         if (trans == NULL)
226                 return ERR_PTR(-ENOMEM);
227
228         if (msg_type == NFT_MSG_NEWCHAIN)
229                 nft_activate_next(ctx->net, ctx->chain);
230
231         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
232         return trans;
233 }
234
235 static int nft_delchain(struct nft_ctx *ctx)
236 {
237         struct nft_trans *trans;
238
239         trans = nft_trans_chain_add(ctx, NFT_MSG_DELCHAIN);
240         if (IS_ERR(trans))
241                 return PTR_ERR(trans);
242
243         ctx->table->use--;
244         nft_deactivate_next(ctx->net, ctx->chain);
245
246         return 0;
247 }
248
249 static void nft_rule_expr_activate(const struct nft_ctx *ctx,
250                                    struct nft_rule *rule)
251 {
252         struct nft_expr *expr;
253
254         expr = nft_expr_first(rule);
255         while (expr != nft_expr_last(rule) && expr->ops) {
256                 if (expr->ops->activate)
257                         expr->ops->activate(ctx, expr);
258
259                 expr = nft_expr_next(expr);
260         }
261 }
262
263 static void nft_rule_expr_deactivate(const struct nft_ctx *ctx,
264                                      struct nft_rule *rule,
265                                      enum nft_trans_phase phase)
266 {
267         struct nft_expr *expr;
268
269         expr = nft_expr_first(rule);
270         while (expr != nft_expr_last(rule) && expr->ops) {
271                 if (expr->ops->deactivate)
272                         expr->ops->deactivate(ctx, expr, phase);
273
274                 expr = nft_expr_next(expr);
275         }
276 }
277
278 static int
279 nf_tables_delrule_deactivate(struct nft_ctx *ctx, struct nft_rule *rule)
280 {
281         /* You cannot delete the same rule twice */
282         if (nft_is_active_next(ctx->net, rule)) {
283                 nft_deactivate_next(ctx->net, rule);
284                 ctx->chain->use--;
285                 return 0;
286         }
287         return -ENOENT;
288 }
289
290 static struct nft_trans *nft_trans_rule_add(struct nft_ctx *ctx, int msg_type,
291                                             struct nft_rule *rule)
292 {
293         struct nft_trans *trans;
294
295         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_rule));
296         if (trans == NULL)
297                 return NULL;
298
299         if (msg_type == NFT_MSG_NEWRULE && ctx->nla[NFTA_RULE_ID] != NULL) {
300                 nft_trans_rule_id(trans) =
301                         ntohl(nla_get_be32(ctx->nla[NFTA_RULE_ID]));
302         }
303         nft_trans_rule(trans) = rule;
304         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
305
306         return trans;
307 }
308
309 static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule)
310 {
311         struct nft_trans *trans;
312         int err;
313
314         trans = nft_trans_rule_add(ctx, NFT_MSG_DELRULE, rule);
315         if (trans == NULL)
316                 return -ENOMEM;
317
318         err = nf_tables_delrule_deactivate(ctx, rule);
319         if (err < 0) {
320                 nft_trans_destroy(trans);
321                 return err;
322         }
323         nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_PREPARE);
324
325         return 0;
326 }
327
328 static int nft_delrule_by_chain(struct nft_ctx *ctx)
329 {
330         struct nft_rule *rule;
331         int err;
332
333         list_for_each_entry(rule, &ctx->chain->rules, list) {
334                 if (!nft_is_active_next(ctx->net, rule))
335                         continue;
336
337                 err = nft_delrule(ctx, rule);
338                 if (err < 0)
339                         return err;
340         }
341         return 0;
342 }
343
344 static int nft_trans_set_add(const struct nft_ctx *ctx, int msg_type,
345                              struct nft_set *set)
346 {
347         struct nft_trans *trans;
348
349         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_set));
350         if (trans == NULL)
351                 return -ENOMEM;
352
353         if (msg_type == NFT_MSG_NEWSET && ctx->nla[NFTA_SET_ID] != NULL) {
354                 nft_trans_set_id(trans) =
355                         ntohl(nla_get_be32(ctx->nla[NFTA_SET_ID]));
356                 nft_activate_next(ctx->net, set);
357         }
358         nft_trans_set(trans) = set;
359         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
360
361         return 0;
362 }
363
364 static int nft_delset(const struct nft_ctx *ctx, struct nft_set *set)
365 {
366         int err;
367
368         err = nft_trans_set_add(ctx, NFT_MSG_DELSET, set);
369         if (err < 0)
370                 return err;
371
372         nft_deactivate_next(ctx->net, set);
373         ctx->table->use--;
374
375         return err;
376 }
377
378 static int nft_trans_obj_add(struct nft_ctx *ctx, int msg_type,
379                              struct nft_object *obj)
380 {
381         struct nft_trans *trans;
382
383         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_obj));
384         if (trans == NULL)
385                 return -ENOMEM;
386
387         if (msg_type == NFT_MSG_NEWOBJ)
388                 nft_activate_next(ctx->net, obj);
389
390         nft_trans_obj(trans) = obj;
391         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
392
393         return 0;
394 }
395
396 static int nft_delobj(struct nft_ctx *ctx, struct nft_object *obj)
397 {
398         int err;
399
400         err = nft_trans_obj_add(ctx, NFT_MSG_DELOBJ, obj);
401         if (err < 0)
402                 return err;
403
404         nft_deactivate_next(ctx->net, obj);
405         ctx->table->use--;
406
407         return err;
408 }
409
410 static int nft_trans_flowtable_add(struct nft_ctx *ctx, int msg_type,
411                                    struct nft_flowtable *flowtable)
412 {
413         struct nft_trans *trans;
414
415         trans = nft_trans_alloc(ctx, msg_type,
416                                 sizeof(struct nft_trans_flowtable));
417         if (trans == NULL)
418                 return -ENOMEM;
419
420         if (msg_type == NFT_MSG_NEWFLOWTABLE)
421                 nft_activate_next(ctx->net, flowtable);
422
423         nft_trans_flowtable(trans) = flowtable;
424         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
425
426         return 0;
427 }
428
429 static int nft_delflowtable(struct nft_ctx *ctx,
430                             struct nft_flowtable *flowtable)
431 {
432         int err;
433
434         err = nft_trans_flowtable_add(ctx, NFT_MSG_DELFLOWTABLE, flowtable);
435         if (err < 0)
436                 return err;
437
438         nft_deactivate_next(ctx->net, flowtable);
439         ctx->table->use--;
440
441         return err;
442 }
443
444 /*
445  * Tables
446  */
447
448 static struct nft_table *nft_table_lookup(const struct net *net,
449                                           const struct nlattr *nla,
450                                           u8 family, u8 genmask)
451 {
452         struct nft_table *table;
453
454         if (nla == NULL)
455                 return ERR_PTR(-EINVAL);
456
457         list_for_each_entry_rcu(table, &net->nft.tables, list) {
458                 if (!nla_strcmp(nla, table->name) &&
459                     table->family == family &&
460                     nft_active_genmask(table, genmask))
461                         return table;
462         }
463
464         return ERR_PTR(-ENOENT);
465 }
466
467 static struct nft_table *nft_table_lookup_byhandle(const struct net *net,
468                                                    const struct nlattr *nla,
469                                                    u8 genmask)
470 {
471         struct nft_table *table;
472
473         list_for_each_entry(table, &net->nft.tables, list) {
474                 if (be64_to_cpu(nla_get_be64(nla)) == table->handle &&
475                     nft_active_genmask(table, genmask))
476                         return table;
477         }
478
479         return ERR_PTR(-ENOENT);
480 }
481
482 static inline u64 nf_tables_alloc_handle(struct nft_table *table)
483 {
484         return ++table->hgenerator;
485 }
486
487 static const struct nft_chain_type *chain_type[NFPROTO_NUMPROTO][NFT_CHAIN_T_MAX];
488
489 static const struct nft_chain_type *
490 __nf_tables_chain_type_lookup(const struct nlattr *nla, u8 family)
491 {
492         int i;
493
494         for (i = 0; i < NFT_CHAIN_T_MAX; i++) {
495                 if (chain_type[family][i] != NULL &&
496                     !nla_strcmp(nla, chain_type[family][i]->name))
497                         return chain_type[family][i];
498         }
499         return NULL;
500 }
501
502 /*
503  * Loading a module requires dropping mutex that guards the
504  * transaction.
505  * We first need to abort any pending transactions as once
506  * mutex is unlocked a different client could start a new
507  * transaction.  It must not see any 'future generation'
508  * changes * as these changes will never happen.
509  */
510 #ifdef CONFIG_MODULES
511 static int __nf_tables_abort(struct net *net);
512
513 static void nft_request_module(struct net *net, const char *fmt, ...)
514 {
515         char module_name[MODULE_NAME_LEN];
516         va_list args;
517         int ret;
518
519         __nf_tables_abort(net);
520
521         va_start(args, fmt);
522         ret = vsnprintf(module_name, MODULE_NAME_LEN, fmt, args);
523         va_end(args);
524         if (WARN(ret >= MODULE_NAME_LEN, "truncated: '%s' (len %d)", module_name, ret))
525                 return;
526
527         mutex_unlock(&net->nft.commit_mutex);
528         request_module("%s", module_name);
529         mutex_lock(&net->nft.commit_mutex);
530 }
531 #endif
532
533 static void lockdep_nfnl_nft_mutex_not_held(void)
534 {
535 #ifdef CONFIG_PROVE_LOCKING
536         WARN_ON_ONCE(lockdep_nfnl_is_held(NFNL_SUBSYS_NFTABLES));
537 #endif
538 }
539
540 static const struct nft_chain_type *
541 nf_tables_chain_type_lookup(struct net *net, const struct nlattr *nla,
542                             u8 family, bool autoload)
543 {
544         const struct nft_chain_type *type;
545
546         type = __nf_tables_chain_type_lookup(nla, family);
547         if (type != NULL)
548                 return type;
549
550         lockdep_nfnl_nft_mutex_not_held();
551 #ifdef CONFIG_MODULES
552         if (autoload) {
553                 nft_request_module(net, "nft-chain-%u-%.*s", family,
554                                    nla_len(nla), (const char *)nla_data(nla));
555                 type = __nf_tables_chain_type_lookup(nla, family);
556                 if (type != NULL)
557                         return ERR_PTR(-EAGAIN);
558         }
559 #endif
560         return ERR_PTR(-ENOENT);
561 }
562
563 static const struct nla_policy nft_table_policy[NFTA_TABLE_MAX + 1] = {
564         [NFTA_TABLE_NAME]       = { .type = NLA_STRING,
565                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
566         [NFTA_TABLE_FLAGS]      = { .type = NLA_U32 },
567         [NFTA_TABLE_HANDLE]     = { .type = NLA_U64 },
568 };
569
570 static int nf_tables_fill_table_info(struct sk_buff *skb, struct net *net,
571                                      u32 portid, u32 seq, int event, u32 flags,
572                                      int family, const struct nft_table *table)
573 {
574         struct nlmsghdr *nlh;
575         struct nfgenmsg *nfmsg;
576
577         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
578         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
579         if (nlh == NULL)
580                 goto nla_put_failure;
581
582         nfmsg = nlmsg_data(nlh);
583         nfmsg->nfgen_family     = family;
584         nfmsg->version          = NFNETLINK_V0;
585         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
586
587         if (nla_put_string(skb, NFTA_TABLE_NAME, table->name) ||
588             nla_put_be32(skb, NFTA_TABLE_FLAGS, htonl(table->flags)) ||
589             nla_put_be32(skb, NFTA_TABLE_USE, htonl(table->use)) ||
590             nla_put_be64(skb, NFTA_TABLE_HANDLE, cpu_to_be64(table->handle),
591                          NFTA_TABLE_PAD))
592                 goto nla_put_failure;
593
594         nlmsg_end(skb, nlh);
595         return 0;
596
597 nla_put_failure:
598         nlmsg_trim(skb, nlh);
599         return -1;
600 }
601
602 static void nf_tables_table_notify(const struct nft_ctx *ctx, int event)
603 {
604         struct sk_buff *skb;
605         int err;
606
607         if (!ctx->report &&
608             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
609                 return;
610
611         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
612         if (skb == NULL)
613                 goto err;
614
615         err = nf_tables_fill_table_info(skb, ctx->net, ctx->portid, ctx->seq,
616                                         event, 0, ctx->family, ctx->table);
617         if (err < 0) {
618                 kfree_skb(skb);
619                 goto err;
620         }
621
622         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
623                        ctx->report, GFP_KERNEL);
624         return;
625 err:
626         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
627 }
628
629 static int nf_tables_dump_tables(struct sk_buff *skb,
630                                  struct netlink_callback *cb)
631 {
632         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
633         const struct nft_table *table;
634         unsigned int idx = 0, s_idx = cb->args[0];
635         struct net *net = sock_net(skb->sk);
636         int family = nfmsg->nfgen_family;
637
638         rcu_read_lock();
639         cb->seq = net->nft.base_seq;
640
641         list_for_each_entry_rcu(table, &net->nft.tables, list) {
642                 if (family != NFPROTO_UNSPEC && family != table->family)
643                         continue;
644
645                 if (idx < s_idx)
646                         goto cont;
647                 if (idx > s_idx)
648                         memset(&cb->args[1], 0,
649                                sizeof(cb->args) - sizeof(cb->args[0]));
650                 if (!nft_is_active(net, table))
651                         continue;
652                 if (nf_tables_fill_table_info(skb, net,
653                                               NETLINK_CB(cb->skb).portid,
654                                               cb->nlh->nlmsg_seq,
655                                               NFT_MSG_NEWTABLE, NLM_F_MULTI,
656                                               table->family, table) < 0)
657                         goto done;
658
659                 nl_dump_check_consistent(cb, nlmsg_hdr(skb));
660 cont:
661                 idx++;
662         }
663 done:
664         rcu_read_unlock();
665         cb->args[0] = idx;
666         return skb->len;
667 }
668
669 static int nft_netlink_dump_start_rcu(struct sock *nlsk, struct sk_buff *skb,
670                                       const struct nlmsghdr *nlh,
671                                       struct netlink_dump_control *c)
672 {
673         int err;
674
675         if (!try_module_get(THIS_MODULE))
676                 return -EINVAL;
677
678         rcu_read_unlock();
679         err = netlink_dump_start(nlsk, skb, nlh, c);
680         rcu_read_lock();
681         module_put(THIS_MODULE);
682
683         return err;
684 }
685
686 /* called with rcu_read_lock held */
687 static int nf_tables_gettable(struct net *net, struct sock *nlsk,
688                               struct sk_buff *skb, const struct nlmsghdr *nlh,
689                               const struct nlattr * const nla[],
690                               struct netlink_ext_ack *extack)
691 {
692         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
693         u8 genmask = nft_genmask_cur(net);
694         const struct nft_table *table;
695         struct sk_buff *skb2;
696         int family = nfmsg->nfgen_family;
697         int err;
698
699         if (nlh->nlmsg_flags & NLM_F_DUMP) {
700                 struct netlink_dump_control c = {
701                         .dump = nf_tables_dump_tables,
702                         .module = THIS_MODULE,
703                 };
704
705                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
706         }
707
708         table = nft_table_lookup(net, nla[NFTA_TABLE_NAME], family, genmask);
709         if (IS_ERR(table)) {
710                 NL_SET_BAD_ATTR(extack, nla[NFTA_TABLE_NAME]);
711                 return PTR_ERR(table);
712         }
713
714         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
715         if (!skb2)
716                 return -ENOMEM;
717
718         err = nf_tables_fill_table_info(skb2, net, NETLINK_CB(skb).portid,
719                                         nlh->nlmsg_seq, NFT_MSG_NEWTABLE, 0,
720                                         family, table);
721         if (err < 0)
722                 goto err;
723
724         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
725
726 err:
727         kfree_skb(skb2);
728         return err;
729 }
730
731 static void nft_table_disable(struct net *net, struct nft_table *table, u32 cnt)
732 {
733         struct nft_chain *chain;
734         u32 i = 0;
735
736         list_for_each_entry(chain, &table->chains, list) {
737                 if (!nft_is_active_next(net, chain))
738                         continue;
739                 if (!nft_is_base_chain(chain))
740                         continue;
741
742                 if (cnt && i++ == cnt)
743                         break;
744
745                 nf_unregister_net_hook(net, &nft_base_chain(chain)->ops);
746         }
747 }
748
749 static int nf_tables_table_enable(struct net *net, struct nft_table *table)
750 {
751         struct nft_chain *chain;
752         int err, i = 0;
753
754         list_for_each_entry(chain, &table->chains, list) {
755                 if (!nft_is_active_next(net, chain))
756                         continue;
757                 if (!nft_is_base_chain(chain))
758                         continue;
759
760                 err = nf_register_net_hook(net, &nft_base_chain(chain)->ops);
761                 if (err < 0)
762                         goto err;
763
764                 i++;
765         }
766         return 0;
767 err:
768         if (i)
769                 nft_table_disable(net, table, i);
770         return err;
771 }
772
773 static void nf_tables_table_disable(struct net *net, struct nft_table *table)
774 {
775         nft_table_disable(net, table, 0);
776 }
777
778 static int nf_tables_updtable(struct nft_ctx *ctx)
779 {
780         struct nft_trans *trans;
781         u32 flags;
782         int ret = 0;
783
784         if (!ctx->nla[NFTA_TABLE_FLAGS])
785                 return 0;
786
787         flags = ntohl(nla_get_be32(ctx->nla[NFTA_TABLE_FLAGS]));
788         if (flags & ~NFT_TABLE_F_DORMANT)
789                 return -EINVAL;
790
791         if (flags == ctx->table->flags)
792                 return 0;
793
794         trans = nft_trans_alloc(ctx, NFT_MSG_NEWTABLE,
795                                 sizeof(struct nft_trans_table));
796         if (trans == NULL)
797                 return -ENOMEM;
798
799         if ((flags & NFT_TABLE_F_DORMANT) &&
800             !(ctx->table->flags & NFT_TABLE_F_DORMANT)) {
801                 nft_trans_table_enable(trans) = false;
802         } else if (!(flags & NFT_TABLE_F_DORMANT) &&
803                    ctx->table->flags & NFT_TABLE_F_DORMANT) {
804                 ret = nf_tables_table_enable(ctx->net, ctx->table);
805                 if (ret >= 0) {
806                         ctx->table->flags &= ~NFT_TABLE_F_DORMANT;
807                         nft_trans_table_enable(trans) = true;
808                 }
809         }
810         if (ret < 0)
811                 goto err;
812
813         nft_trans_table_update(trans) = true;
814         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
815         return 0;
816 err:
817         nft_trans_destroy(trans);
818         return ret;
819 }
820
821 static u32 nft_chain_hash(const void *data, u32 len, u32 seed)
822 {
823         const char *name = data;
824
825         return jhash(name, strlen(name), seed);
826 }
827
828 static u32 nft_chain_hash_obj(const void *data, u32 len, u32 seed)
829 {
830         const struct nft_chain *chain = data;
831
832         return nft_chain_hash(chain->name, 0, seed);
833 }
834
835 static int nft_chain_hash_cmp(struct rhashtable_compare_arg *arg,
836                               const void *ptr)
837 {
838         const struct nft_chain *chain = ptr;
839         const char *name = arg->key;
840
841         return strcmp(chain->name, name);
842 }
843
844 static u32 nft_objname_hash(const void *data, u32 len, u32 seed)
845 {
846         const struct nft_object_hash_key *k = data;
847
848         seed ^= hash_ptr(k->table, 32);
849
850         return jhash(k->name, strlen(k->name), seed);
851 }
852
853 static u32 nft_objname_hash_obj(const void *data, u32 len, u32 seed)
854 {
855         const struct nft_object *obj = data;
856
857         return nft_objname_hash(&obj->key, 0, seed);
858 }
859
860 static int nft_objname_hash_cmp(struct rhashtable_compare_arg *arg,
861                                 const void *ptr)
862 {
863         const struct nft_object_hash_key *k = arg->key;
864         const struct nft_object *obj = ptr;
865
866         if (obj->key.table != k->table)
867                 return -1;
868
869         return strcmp(obj->key.name, k->name);
870 }
871
872 static int nf_tables_newtable(struct net *net, struct sock *nlsk,
873                               struct sk_buff *skb, const struct nlmsghdr *nlh,
874                               const struct nlattr * const nla[],
875                               struct netlink_ext_ack *extack)
876 {
877         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
878         u8 genmask = nft_genmask_next(net);
879         int family = nfmsg->nfgen_family;
880         const struct nlattr *attr;
881         struct nft_table *table;
882         u32 flags = 0;
883         struct nft_ctx ctx;
884         int err;
885
886         lockdep_assert_held(&net->nft.commit_mutex);
887         attr = nla[NFTA_TABLE_NAME];
888         table = nft_table_lookup(net, attr, family, genmask);
889         if (IS_ERR(table)) {
890                 if (PTR_ERR(table) != -ENOENT)
891                         return PTR_ERR(table);
892         } else {
893                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
894                         NL_SET_BAD_ATTR(extack, attr);
895                         return -EEXIST;
896                 }
897                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
898                         return -EOPNOTSUPP;
899
900                 nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
901                 return nf_tables_updtable(&ctx);
902         }
903
904         if (nla[NFTA_TABLE_FLAGS]) {
905                 flags = ntohl(nla_get_be32(nla[NFTA_TABLE_FLAGS]));
906                 if (flags & ~NFT_TABLE_F_DORMANT)
907                         return -EINVAL;
908         }
909
910         err = -ENOMEM;
911         table = kzalloc(sizeof(*table), GFP_KERNEL);
912         if (table == NULL)
913                 goto err_kzalloc;
914
915         table->name = nla_strdup(attr, GFP_KERNEL);
916         if (table->name == NULL)
917                 goto err_strdup;
918
919         err = rhltable_init(&table->chains_ht, &nft_chain_ht_params);
920         if (err)
921                 goto err_chain_ht;
922
923         INIT_LIST_HEAD(&table->chains);
924         INIT_LIST_HEAD(&table->sets);
925         INIT_LIST_HEAD(&table->objects);
926         INIT_LIST_HEAD(&table->flowtables);
927         table->family = family;
928         table->flags = flags;
929         table->handle = ++table_handle;
930
931         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
932         err = nft_trans_table_add(&ctx, NFT_MSG_NEWTABLE);
933         if (err < 0)
934                 goto err_trans;
935
936         list_add_tail_rcu(&table->list, &net->nft.tables);
937         return 0;
938 err_trans:
939         rhltable_destroy(&table->chains_ht);
940 err_chain_ht:
941         kfree(table->name);
942 err_strdup:
943         kfree(table);
944 err_kzalloc:
945         return err;
946 }
947
948 static int nft_flush_table(struct nft_ctx *ctx)
949 {
950         struct nft_flowtable *flowtable, *nft;
951         struct nft_chain *chain, *nc;
952         struct nft_object *obj, *ne;
953         struct nft_set *set, *ns;
954         int err;
955
956         list_for_each_entry(chain, &ctx->table->chains, list) {
957                 if (!nft_is_active_next(ctx->net, chain))
958                         continue;
959
960                 ctx->chain = chain;
961
962                 err = nft_delrule_by_chain(ctx);
963                 if (err < 0)
964                         goto out;
965         }
966
967         list_for_each_entry_safe(set, ns, &ctx->table->sets, list) {
968                 if (!nft_is_active_next(ctx->net, set))
969                         continue;
970
971                 if (nft_set_is_anonymous(set) &&
972                     !list_empty(&set->bindings))
973                         continue;
974
975                 err = nft_delset(ctx, set);
976                 if (err < 0)
977                         goto out;
978         }
979
980         list_for_each_entry_safe(flowtable, nft, &ctx->table->flowtables, list) {
981                 err = nft_delflowtable(ctx, flowtable);
982                 if (err < 0)
983                         goto out;
984         }
985
986         list_for_each_entry_safe(obj, ne, &ctx->table->objects, list) {
987                 err = nft_delobj(ctx, obj);
988                 if (err < 0)
989                         goto out;
990         }
991
992         list_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {
993                 if (!nft_is_active_next(ctx->net, chain))
994                         continue;
995
996                 ctx->chain = chain;
997
998                 err = nft_delchain(ctx);
999                 if (err < 0)
1000                         goto out;
1001         }
1002
1003         err = nft_deltable(ctx);
1004 out:
1005         return err;
1006 }
1007
1008 static int nft_flush(struct nft_ctx *ctx, int family)
1009 {
1010         struct nft_table *table, *nt;
1011         const struct nlattr * const *nla = ctx->nla;
1012         int err = 0;
1013
1014         list_for_each_entry_safe(table, nt, &ctx->net->nft.tables, list) {
1015                 if (family != AF_UNSPEC && table->family != family)
1016                         continue;
1017
1018                 ctx->family = table->family;
1019
1020                 if (!nft_is_active_next(ctx->net, table))
1021                         continue;
1022
1023                 if (nla[NFTA_TABLE_NAME] &&
1024                     nla_strcmp(nla[NFTA_TABLE_NAME], table->name) != 0)
1025                         continue;
1026
1027                 ctx->table = table;
1028
1029                 err = nft_flush_table(ctx);
1030                 if (err < 0)
1031                         goto out;
1032         }
1033 out:
1034         return err;
1035 }
1036
1037 static int nf_tables_deltable(struct net *net, struct sock *nlsk,
1038                               struct sk_buff *skb, const struct nlmsghdr *nlh,
1039                               const struct nlattr * const nla[],
1040                               struct netlink_ext_ack *extack)
1041 {
1042         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1043         u8 genmask = nft_genmask_next(net);
1044         int family = nfmsg->nfgen_family;
1045         const struct nlattr *attr;
1046         struct nft_table *table;
1047         struct nft_ctx ctx;
1048
1049         nft_ctx_init(&ctx, net, skb, nlh, 0, NULL, NULL, nla);
1050         if (family == AF_UNSPEC ||
1051             (!nla[NFTA_TABLE_NAME] && !nla[NFTA_TABLE_HANDLE]))
1052                 return nft_flush(&ctx, family);
1053
1054         if (nla[NFTA_TABLE_HANDLE]) {
1055                 attr = nla[NFTA_TABLE_HANDLE];
1056                 table = nft_table_lookup_byhandle(net, attr, genmask);
1057         } else {
1058                 attr = nla[NFTA_TABLE_NAME];
1059                 table = nft_table_lookup(net, attr, family, genmask);
1060         }
1061
1062         if (IS_ERR(table)) {
1063                 NL_SET_BAD_ATTR(extack, attr);
1064                 return PTR_ERR(table);
1065         }
1066
1067         if (nlh->nlmsg_flags & NLM_F_NONREC &&
1068             table->use > 0)
1069                 return -EBUSY;
1070
1071         ctx.family = family;
1072         ctx.table = table;
1073
1074         return nft_flush_table(&ctx);
1075 }
1076
1077 static void nf_tables_table_destroy(struct nft_ctx *ctx)
1078 {
1079         if (WARN_ON(ctx->table->use > 0))
1080                 return;
1081
1082         rhltable_destroy(&ctx->table->chains_ht);
1083         kfree(ctx->table->name);
1084         kfree(ctx->table);
1085 }
1086
1087 void nft_register_chain_type(const struct nft_chain_type *ctype)
1088 {
1089         if (WARN_ON(ctype->family >= NFPROTO_NUMPROTO))
1090                 return;
1091
1092         nfnl_lock(NFNL_SUBSYS_NFTABLES);
1093         if (WARN_ON(chain_type[ctype->family][ctype->type] != NULL)) {
1094                 nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1095                 return;
1096         }
1097         chain_type[ctype->family][ctype->type] = ctype;
1098         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1099 }
1100 EXPORT_SYMBOL_GPL(nft_register_chain_type);
1101
1102 void nft_unregister_chain_type(const struct nft_chain_type *ctype)
1103 {
1104         nfnl_lock(NFNL_SUBSYS_NFTABLES);
1105         chain_type[ctype->family][ctype->type] = NULL;
1106         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1107 }
1108 EXPORT_SYMBOL_GPL(nft_unregister_chain_type);
1109
1110 /*
1111  * Chains
1112  */
1113
1114 static struct nft_chain *
1115 nft_chain_lookup_byhandle(const struct nft_table *table, u64 handle, u8 genmask)
1116 {
1117         struct nft_chain *chain;
1118
1119         list_for_each_entry(chain, &table->chains, list) {
1120                 if (chain->handle == handle &&
1121                     nft_active_genmask(chain, genmask))
1122                         return chain;
1123         }
1124
1125         return ERR_PTR(-ENOENT);
1126 }
1127
1128 static bool lockdep_commit_lock_is_held(const struct net *net)
1129 {
1130 #ifdef CONFIG_PROVE_LOCKING
1131         return lockdep_is_held(&net->nft.commit_mutex);
1132 #else
1133         return true;
1134 #endif
1135 }
1136
1137 static struct nft_chain *nft_chain_lookup(struct net *net,
1138                                           struct nft_table *table,
1139                                           const struct nlattr *nla, u8 genmask)
1140 {
1141         char search[NFT_CHAIN_MAXNAMELEN + 1];
1142         struct rhlist_head *tmp, *list;
1143         struct nft_chain *chain;
1144
1145         if (nla == NULL)
1146                 return ERR_PTR(-EINVAL);
1147
1148         nla_strlcpy(search, nla, sizeof(search));
1149
1150         WARN_ON(!rcu_read_lock_held() &&
1151                 !lockdep_commit_lock_is_held(net));
1152
1153         chain = ERR_PTR(-ENOENT);
1154         rcu_read_lock();
1155         list = rhltable_lookup(&table->chains_ht, search, nft_chain_ht_params);
1156         if (!list)
1157                 goto out_unlock;
1158
1159         rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) {
1160                 if (nft_active_genmask(chain, genmask))
1161                         goto out_unlock;
1162         }
1163         chain = ERR_PTR(-ENOENT);
1164 out_unlock:
1165         rcu_read_unlock();
1166         return chain;
1167 }
1168
1169 static const struct nla_policy nft_chain_policy[NFTA_CHAIN_MAX + 1] = {
1170         [NFTA_CHAIN_TABLE]      = { .type = NLA_STRING,
1171                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
1172         [NFTA_CHAIN_HANDLE]     = { .type = NLA_U64 },
1173         [NFTA_CHAIN_NAME]       = { .type = NLA_STRING,
1174                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
1175         [NFTA_CHAIN_HOOK]       = { .type = NLA_NESTED },
1176         [NFTA_CHAIN_POLICY]     = { .type = NLA_U32 },
1177         [NFTA_CHAIN_TYPE]       = { .type = NLA_STRING },
1178         [NFTA_CHAIN_COUNTERS]   = { .type = NLA_NESTED },
1179         [NFTA_CHAIN_FLAGS]      = { .type = NLA_U32 },
1180 };
1181
1182 static const struct nla_policy nft_hook_policy[NFTA_HOOK_MAX + 1] = {
1183         [NFTA_HOOK_HOOKNUM]     = { .type = NLA_U32 },
1184         [NFTA_HOOK_PRIORITY]    = { .type = NLA_U32 },
1185         [NFTA_HOOK_DEV]         = { .type = NLA_STRING,
1186                                     .len = IFNAMSIZ - 1 },
1187 };
1188
1189 static int nft_dump_stats(struct sk_buff *skb, struct nft_stats __percpu *stats)
1190 {
1191         struct nft_stats *cpu_stats, total;
1192         struct nlattr *nest;
1193         unsigned int seq;
1194         u64 pkts, bytes;
1195         int cpu;
1196
1197         if (!stats)
1198                 return 0;
1199
1200         memset(&total, 0, sizeof(total));
1201         for_each_possible_cpu(cpu) {
1202                 cpu_stats = per_cpu_ptr(stats, cpu);
1203                 do {
1204                         seq = u64_stats_fetch_begin_irq(&cpu_stats->syncp);
1205                         pkts = cpu_stats->pkts;
1206                         bytes = cpu_stats->bytes;
1207                 } while (u64_stats_fetch_retry_irq(&cpu_stats->syncp, seq));
1208                 total.pkts += pkts;
1209                 total.bytes += bytes;
1210         }
1211         nest = nla_nest_start_noflag(skb, NFTA_CHAIN_COUNTERS);
1212         if (nest == NULL)
1213                 goto nla_put_failure;
1214
1215         if (nla_put_be64(skb, NFTA_COUNTER_PACKETS, cpu_to_be64(total.pkts),
1216                          NFTA_COUNTER_PAD) ||
1217             nla_put_be64(skb, NFTA_COUNTER_BYTES, cpu_to_be64(total.bytes),
1218                          NFTA_COUNTER_PAD))
1219                 goto nla_put_failure;
1220
1221         nla_nest_end(skb, nest);
1222         return 0;
1223
1224 nla_put_failure:
1225         return -ENOSPC;
1226 }
1227
1228 static int nf_tables_fill_chain_info(struct sk_buff *skb, struct net *net,
1229                                      u32 portid, u32 seq, int event, u32 flags,
1230                                      int family, const struct nft_table *table,
1231                                      const struct nft_chain *chain)
1232 {
1233         struct nlmsghdr *nlh;
1234         struct nfgenmsg *nfmsg;
1235
1236         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
1237         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
1238         if (nlh == NULL)
1239                 goto nla_put_failure;
1240
1241         nfmsg = nlmsg_data(nlh);
1242         nfmsg->nfgen_family     = family;
1243         nfmsg->version          = NFNETLINK_V0;
1244         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
1245
1246         if (nla_put_string(skb, NFTA_CHAIN_TABLE, table->name))
1247                 goto nla_put_failure;
1248         if (nla_put_be64(skb, NFTA_CHAIN_HANDLE, cpu_to_be64(chain->handle),
1249                          NFTA_CHAIN_PAD))
1250                 goto nla_put_failure;
1251         if (nla_put_string(skb, NFTA_CHAIN_NAME, chain->name))
1252                 goto nla_put_failure;
1253
1254         if (nft_is_base_chain(chain)) {
1255                 const struct nft_base_chain *basechain = nft_base_chain(chain);
1256                 const struct nf_hook_ops *ops = &basechain->ops;
1257                 struct nft_stats __percpu *stats;
1258                 struct nlattr *nest;
1259
1260                 nest = nla_nest_start_noflag(skb, NFTA_CHAIN_HOOK);
1261                 if (nest == NULL)
1262                         goto nla_put_failure;
1263                 if (nla_put_be32(skb, NFTA_HOOK_HOOKNUM, htonl(ops->hooknum)))
1264                         goto nla_put_failure;
1265                 if (nla_put_be32(skb, NFTA_HOOK_PRIORITY, htonl(ops->priority)))
1266                         goto nla_put_failure;
1267                 if (basechain->dev_name[0] &&
1268                     nla_put_string(skb, NFTA_HOOK_DEV, basechain->dev_name))
1269                         goto nla_put_failure;
1270                 nla_nest_end(skb, nest);
1271
1272                 if (nla_put_be32(skb, NFTA_CHAIN_POLICY,
1273                                  htonl(basechain->policy)))
1274                         goto nla_put_failure;
1275
1276                 if (nla_put_string(skb, NFTA_CHAIN_TYPE, basechain->type->name))
1277                         goto nla_put_failure;
1278
1279                 stats = rcu_dereference_check(basechain->stats,
1280                                               lockdep_commit_lock_is_held(net));
1281                 if (nft_dump_stats(skb, stats))
1282                         goto nla_put_failure;
1283         }
1284
1285         if (nla_put_be32(skb, NFTA_CHAIN_USE, htonl(chain->use)))
1286                 goto nla_put_failure;
1287
1288         nlmsg_end(skb, nlh);
1289         return 0;
1290
1291 nla_put_failure:
1292         nlmsg_trim(skb, nlh);
1293         return -1;
1294 }
1295
1296 static void nf_tables_chain_notify(const struct nft_ctx *ctx, int event)
1297 {
1298         struct sk_buff *skb;
1299         int err;
1300
1301         if (!ctx->report &&
1302             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
1303                 return;
1304
1305         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1306         if (skb == NULL)
1307                 goto err;
1308
1309         err = nf_tables_fill_chain_info(skb, ctx->net, ctx->portid, ctx->seq,
1310                                         event, 0, ctx->family, ctx->table,
1311                                         ctx->chain);
1312         if (err < 0) {
1313                 kfree_skb(skb);
1314                 goto err;
1315         }
1316
1317         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
1318                        ctx->report, GFP_KERNEL);
1319         return;
1320 err:
1321         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
1322 }
1323
1324 static int nf_tables_dump_chains(struct sk_buff *skb,
1325                                  struct netlink_callback *cb)
1326 {
1327         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
1328         const struct nft_table *table;
1329         const struct nft_chain *chain;
1330         unsigned int idx = 0, s_idx = cb->args[0];
1331         struct net *net = sock_net(skb->sk);
1332         int family = nfmsg->nfgen_family;
1333
1334         rcu_read_lock();
1335         cb->seq = net->nft.base_seq;
1336
1337         list_for_each_entry_rcu(table, &net->nft.tables, list) {
1338                 if (family != NFPROTO_UNSPEC && family != table->family)
1339                         continue;
1340
1341                 list_for_each_entry_rcu(chain, &table->chains, list) {
1342                         if (idx < s_idx)
1343                                 goto cont;
1344                         if (idx > s_idx)
1345                                 memset(&cb->args[1], 0,
1346                                        sizeof(cb->args) - sizeof(cb->args[0]));
1347                         if (!nft_is_active(net, chain))
1348                                 continue;
1349                         if (nf_tables_fill_chain_info(skb, net,
1350                                                       NETLINK_CB(cb->skb).portid,
1351                                                       cb->nlh->nlmsg_seq,
1352                                                       NFT_MSG_NEWCHAIN,
1353                                                       NLM_F_MULTI,
1354                                                       table->family, table,
1355                                                       chain) < 0)
1356                                 goto done;
1357
1358                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
1359 cont:
1360                         idx++;
1361                 }
1362         }
1363 done:
1364         rcu_read_unlock();
1365         cb->args[0] = idx;
1366         return skb->len;
1367 }
1368
1369 /* called with rcu_read_lock held */
1370 static int nf_tables_getchain(struct net *net, struct sock *nlsk,
1371                               struct sk_buff *skb, const struct nlmsghdr *nlh,
1372                               const struct nlattr * const nla[],
1373                               struct netlink_ext_ack *extack)
1374 {
1375         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1376         u8 genmask = nft_genmask_cur(net);
1377         const struct nft_chain *chain;
1378         struct nft_table *table;
1379         struct sk_buff *skb2;
1380         int family = nfmsg->nfgen_family;
1381         int err;
1382
1383         if (nlh->nlmsg_flags & NLM_F_DUMP) {
1384                 struct netlink_dump_control c = {
1385                         .dump = nf_tables_dump_chains,
1386                         .module = THIS_MODULE,
1387                 };
1388
1389                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
1390         }
1391
1392         table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
1393         if (IS_ERR(table)) {
1394                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1395                 return PTR_ERR(table);
1396         }
1397
1398         chain = nft_chain_lookup(net, table, nla[NFTA_CHAIN_NAME], genmask);
1399         if (IS_ERR(chain)) {
1400                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_NAME]);
1401                 return PTR_ERR(chain);
1402         }
1403
1404         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
1405         if (!skb2)
1406                 return -ENOMEM;
1407
1408         err = nf_tables_fill_chain_info(skb2, net, NETLINK_CB(skb).portid,
1409                                         nlh->nlmsg_seq, NFT_MSG_NEWCHAIN, 0,
1410                                         family, table, chain);
1411         if (err < 0)
1412                 goto err;
1413
1414         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
1415
1416 err:
1417         kfree_skb(skb2);
1418         return err;
1419 }
1420
1421 static const struct nla_policy nft_counter_policy[NFTA_COUNTER_MAX + 1] = {
1422         [NFTA_COUNTER_PACKETS]  = { .type = NLA_U64 },
1423         [NFTA_COUNTER_BYTES]    = { .type = NLA_U64 },
1424 };
1425
1426 static struct nft_stats __percpu *nft_stats_alloc(const struct nlattr *attr)
1427 {
1428         struct nlattr *tb[NFTA_COUNTER_MAX+1];
1429         struct nft_stats __percpu *newstats;
1430         struct nft_stats *stats;
1431         int err;
1432
1433         err = nla_parse_nested_deprecated(tb, NFTA_COUNTER_MAX, attr,
1434                                           nft_counter_policy, NULL);
1435         if (err < 0)
1436                 return ERR_PTR(err);
1437
1438         if (!tb[NFTA_COUNTER_BYTES] || !tb[NFTA_COUNTER_PACKETS])
1439                 return ERR_PTR(-EINVAL);
1440
1441         newstats = netdev_alloc_pcpu_stats(struct nft_stats);
1442         if (newstats == NULL)
1443                 return ERR_PTR(-ENOMEM);
1444
1445         /* Restore old counters on this cpu, no problem. Per-cpu statistics
1446          * are not exposed to userspace.
1447          */
1448         preempt_disable();
1449         stats = this_cpu_ptr(newstats);
1450         stats->bytes = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_BYTES]));
1451         stats->pkts = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_PACKETS]));
1452         preempt_enable();
1453
1454         return newstats;
1455 }
1456
1457 static void nft_chain_stats_replace(struct nft_trans *trans)
1458 {
1459         struct nft_base_chain *chain = nft_base_chain(trans->ctx.chain);
1460
1461         if (!nft_trans_chain_stats(trans))
1462                 return;
1463
1464         rcu_swap_protected(chain->stats, nft_trans_chain_stats(trans),
1465                            lockdep_commit_lock_is_held(trans->ctx.net));
1466
1467         if (!nft_trans_chain_stats(trans))
1468                 static_branch_inc(&nft_counters_enabled);
1469 }
1470
1471 static void nf_tables_chain_free_chain_rules(struct nft_chain *chain)
1472 {
1473         struct nft_rule **g0 = rcu_dereference_raw(chain->rules_gen_0);
1474         struct nft_rule **g1 = rcu_dereference_raw(chain->rules_gen_1);
1475
1476         if (g0 != g1)
1477                 kvfree(g1);
1478         kvfree(g0);
1479
1480         /* should be NULL either via abort or via successful commit */
1481         WARN_ON_ONCE(chain->rules_next);
1482         kvfree(chain->rules_next);
1483 }
1484
1485 static void nf_tables_chain_destroy(struct nft_ctx *ctx)
1486 {
1487         struct nft_chain *chain = ctx->chain;
1488
1489         if (WARN_ON(chain->use > 0))
1490                 return;
1491
1492         /* no concurrent access possible anymore */
1493         nf_tables_chain_free_chain_rules(chain);
1494
1495         if (nft_is_base_chain(chain)) {
1496                 struct nft_base_chain *basechain = nft_base_chain(chain);
1497
1498                 module_put(basechain->type->owner);
1499                 if (rcu_access_pointer(basechain->stats)) {
1500                         static_branch_dec(&nft_counters_enabled);
1501                         free_percpu(rcu_dereference_raw(basechain->stats));
1502                 }
1503                 kfree(chain->name);
1504                 kfree(basechain);
1505         } else {
1506                 kfree(chain->name);
1507                 kfree(chain);
1508         }
1509 }
1510
1511 struct nft_chain_hook {
1512         u32                             num;
1513         s32                             priority;
1514         const struct nft_chain_type     *type;
1515         struct net_device               *dev;
1516 };
1517
1518 static int nft_chain_parse_hook(struct net *net,
1519                                 const struct nlattr * const nla[],
1520                                 struct nft_chain_hook *hook, u8 family,
1521                                 bool autoload)
1522 {
1523         struct nlattr *ha[NFTA_HOOK_MAX + 1];
1524         const struct nft_chain_type *type;
1525         struct net_device *dev;
1526         int err;
1527
1528         lockdep_assert_held(&net->nft.commit_mutex);
1529         lockdep_nfnl_nft_mutex_not_held();
1530
1531         err = nla_parse_nested_deprecated(ha, NFTA_HOOK_MAX,
1532                                           nla[NFTA_CHAIN_HOOK],
1533                                           nft_hook_policy, NULL);
1534         if (err < 0)
1535                 return err;
1536
1537         if (ha[NFTA_HOOK_HOOKNUM] == NULL ||
1538             ha[NFTA_HOOK_PRIORITY] == NULL)
1539                 return -EINVAL;
1540
1541         hook->num = ntohl(nla_get_be32(ha[NFTA_HOOK_HOOKNUM]));
1542         hook->priority = ntohl(nla_get_be32(ha[NFTA_HOOK_PRIORITY]));
1543
1544         type = chain_type[family][NFT_CHAIN_T_DEFAULT];
1545         if (nla[NFTA_CHAIN_TYPE]) {
1546                 type = nf_tables_chain_type_lookup(net, nla[NFTA_CHAIN_TYPE],
1547                                                    family, autoload);
1548                 if (IS_ERR(type))
1549                         return PTR_ERR(type);
1550         }
1551         if (hook->num > NF_MAX_HOOKS || !(type->hook_mask & (1 << hook->num)))
1552                 return -EOPNOTSUPP;
1553
1554         if (type->type == NFT_CHAIN_T_NAT &&
1555             hook->priority <= NF_IP_PRI_CONNTRACK)
1556                 return -EOPNOTSUPP;
1557
1558         if (!try_module_get(type->owner))
1559                 return -ENOENT;
1560
1561         hook->type = type;
1562
1563         hook->dev = NULL;
1564         if (family == NFPROTO_NETDEV) {
1565                 char ifname[IFNAMSIZ];
1566
1567                 if (!ha[NFTA_HOOK_DEV]) {
1568                         module_put(type->owner);
1569                         return -EOPNOTSUPP;
1570                 }
1571
1572                 nla_strlcpy(ifname, ha[NFTA_HOOK_DEV], IFNAMSIZ);
1573                 dev = __dev_get_by_name(net, ifname);
1574                 if (!dev) {
1575                         module_put(type->owner);
1576                         return -ENOENT;
1577                 }
1578                 hook->dev = dev;
1579         } else if (ha[NFTA_HOOK_DEV]) {
1580                 module_put(type->owner);
1581                 return -EOPNOTSUPP;
1582         }
1583
1584         return 0;
1585 }
1586
1587 static void nft_chain_release_hook(struct nft_chain_hook *hook)
1588 {
1589         module_put(hook->type->owner);
1590 }
1591
1592 struct nft_rules_old {
1593         struct rcu_head h;
1594         struct nft_rule **start;
1595 };
1596
1597 static struct nft_rule **nf_tables_chain_alloc_rules(const struct nft_chain *chain,
1598                                                      unsigned int alloc)
1599 {
1600         if (alloc > INT_MAX)
1601                 return NULL;
1602
1603         alloc += 1;     /* NULL, ends rules */
1604         if (sizeof(struct nft_rule *) > INT_MAX / alloc)
1605                 return NULL;
1606
1607         alloc *= sizeof(struct nft_rule *);
1608         alloc += sizeof(struct nft_rules_old);
1609
1610         return kvmalloc(alloc, GFP_KERNEL);
1611 }
1612
1613 static int nf_tables_addchain(struct nft_ctx *ctx, u8 family, u8 genmask,
1614                               u8 policy, u32 flags)
1615 {
1616         const struct nlattr * const *nla = ctx->nla;
1617         struct nft_table *table = ctx->table;
1618         struct nft_base_chain *basechain;
1619         struct nft_stats __percpu *stats;
1620         struct net *net = ctx->net;
1621         struct nft_trans *trans;
1622         struct nft_chain *chain;
1623         struct nft_rule **rules;
1624         int err;
1625
1626         if (table->use == UINT_MAX)
1627                 return -EOVERFLOW;
1628
1629         if (nla[NFTA_CHAIN_HOOK]) {
1630                 struct nft_chain_hook hook;
1631                 struct nf_hook_ops *ops;
1632
1633                 err = nft_chain_parse_hook(net, nla, &hook, family, true);
1634                 if (err < 0)
1635                         return err;
1636
1637                 basechain = kzalloc(sizeof(*basechain), GFP_KERNEL);
1638                 if (basechain == NULL) {
1639                         nft_chain_release_hook(&hook);
1640                         return -ENOMEM;
1641                 }
1642
1643                 if (hook.dev != NULL)
1644                         strncpy(basechain->dev_name, hook.dev->name, IFNAMSIZ);
1645
1646                 if (nla[NFTA_CHAIN_COUNTERS]) {
1647                         stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
1648                         if (IS_ERR(stats)) {
1649                                 nft_chain_release_hook(&hook);
1650                                 kfree(basechain);
1651                                 return PTR_ERR(stats);
1652                         }
1653                         rcu_assign_pointer(basechain->stats, stats);
1654                         static_branch_inc(&nft_counters_enabled);
1655                 }
1656
1657                 basechain->type = hook.type;
1658                 chain = &basechain->chain;
1659
1660                 ops             = &basechain->ops;
1661                 ops->pf         = family;
1662                 ops->hooknum    = hook.num;
1663                 ops->priority   = hook.priority;
1664                 ops->priv       = chain;
1665                 ops->hook       = hook.type->hooks[ops->hooknum];
1666                 ops->dev        = hook.dev;
1667
1668                 chain->flags |= NFT_BASE_CHAIN | flags;
1669                 basechain->policy = NF_ACCEPT;
1670                 if (chain->flags & NFT_CHAIN_HW_OFFLOAD &&
1671                     nft_chain_offload_priority(basechain) < 0)
1672                         return -EOPNOTSUPP;
1673
1674                 flow_block_init(&basechain->flow_block);
1675         } else {
1676                 chain = kzalloc(sizeof(*chain), GFP_KERNEL);
1677                 if (chain == NULL)
1678                         return -ENOMEM;
1679         }
1680         ctx->chain = chain;
1681
1682         INIT_LIST_HEAD(&chain->rules);
1683         chain->handle = nf_tables_alloc_handle(table);
1684         chain->table = table;
1685         chain->name = nla_strdup(nla[NFTA_CHAIN_NAME], GFP_KERNEL);
1686         if (!chain->name) {
1687                 err = -ENOMEM;
1688                 goto err1;
1689         }
1690
1691         rules = nf_tables_chain_alloc_rules(chain, 0);
1692         if (!rules) {
1693                 err = -ENOMEM;
1694                 goto err1;
1695         }
1696
1697         *rules = NULL;
1698         rcu_assign_pointer(chain->rules_gen_0, rules);
1699         rcu_assign_pointer(chain->rules_gen_1, rules);
1700
1701         err = nf_tables_register_hook(net, table, chain);
1702         if (err < 0)
1703                 goto err1;
1704
1705         err = rhltable_insert_key(&table->chains_ht, chain->name,
1706                                   &chain->rhlhead, nft_chain_ht_params);
1707         if (err)
1708                 goto err2;
1709
1710         trans = nft_trans_chain_add(ctx, NFT_MSG_NEWCHAIN);
1711         if (IS_ERR(trans)) {
1712                 err = PTR_ERR(trans);
1713                 rhltable_remove(&table->chains_ht, &chain->rhlhead,
1714                                 nft_chain_ht_params);
1715                 goto err2;
1716         }
1717
1718         nft_trans_chain_policy(trans) = -1;
1719         if (nft_is_base_chain(chain))
1720                 nft_trans_chain_policy(trans) = policy;
1721
1722         table->use++;
1723         list_add_tail_rcu(&chain->list, &table->chains);
1724
1725         return 0;
1726 err2:
1727         nf_tables_unregister_hook(net, table, chain);
1728 err1:
1729         nf_tables_chain_destroy(ctx);
1730
1731         return err;
1732 }
1733
1734 static int nf_tables_updchain(struct nft_ctx *ctx, u8 genmask, u8 policy,
1735                               u32 flags)
1736 {
1737         const struct nlattr * const *nla = ctx->nla;
1738         struct nft_table *table = ctx->table;
1739         struct nft_chain *chain = ctx->chain;
1740         struct nft_base_chain *basechain;
1741         struct nft_stats *stats = NULL;
1742         struct nft_chain_hook hook;
1743         struct nf_hook_ops *ops;
1744         struct nft_trans *trans;
1745         int err;
1746
1747         if (chain->flags ^ flags)
1748                 return -EOPNOTSUPP;
1749
1750         if (nla[NFTA_CHAIN_HOOK]) {
1751                 if (!nft_is_base_chain(chain))
1752                         return -EBUSY;
1753
1754                 err = nft_chain_parse_hook(ctx->net, nla, &hook, ctx->family,
1755                                            false);
1756                 if (err < 0)
1757                         return err;
1758
1759                 basechain = nft_base_chain(chain);
1760                 if (basechain->type != hook.type) {
1761                         nft_chain_release_hook(&hook);
1762                         return -EBUSY;
1763                 }
1764
1765                 ops = &basechain->ops;
1766                 if (ops->hooknum != hook.num ||
1767                     ops->priority != hook.priority ||
1768                     ops->dev != hook.dev) {
1769                         nft_chain_release_hook(&hook);
1770                         return -EBUSY;
1771                 }
1772                 nft_chain_release_hook(&hook);
1773         }
1774
1775         if (nla[NFTA_CHAIN_HANDLE] &&
1776             nla[NFTA_CHAIN_NAME]) {
1777                 struct nft_chain *chain2;
1778
1779                 chain2 = nft_chain_lookup(ctx->net, table,
1780                                           nla[NFTA_CHAIN_NAME], genmask);
1781                 if (!IS_ERR(chain2))
1782                         return -EEXIST;
1783         }
1784
1785         if (nla[NFTA_CHAIN_COUNTERS]) {
1786                 if (!nft_is_base_chain(chain))
1787                         return -EOPNOTSUPP;
1788
1789                 stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
1790                 if (IS_ERR(stats))
1791                         return PTR_ERR(stats);
1792         }
1793
1794         err = -ENOMEM;
1795         trans = nft_trans_alloc(ctx, NFT_MSG_NEWCHAIN,
1796                                 sizeof(struct nft_trans_chain));
1797         if (trans == NULL)
1798                 goto err;
1799
1800         nft_trans_chain_stats(trans) = stats;
1801         nft_trans_chain_update(trans) = true;
1802
1803         if (nla[NFTA_CHAIN_POLICY])
1804                 nft_trans_chain_policy(trans) = policy;
1805         else
1806                 nft_trans_chain_policy(trans) = -1;
1807
1808         if (nla[NFTA_CHAIN_HANDLE] &&
1809             nla[NFTA_CHAIN_NAME]) {
1810                 struct nft_trans *tmp;
1811                 char *name;
1812
1813                 err = -ENOMEM;
1814                 name = nla_strdup(nla[NFTA_CHAIN_NAME], GFP_KERNEL);
1815                 if (!name)
1816                         goto err;
1817
1818                 err = -EEXIST;
1819                 list_for_each_entry(tmp, &ctx->net->nft.commit_list, list) {
1820                         if (tmp->msg_type == NFT_MSG_NEWCHAIN &&
1821                             tmp->ctx.table == table &&
1822                             nft_trans_chain_update(tmp) &&
1823                             nft_trans_chain_name(tmp) &&
1824                             strcmp(name, nft_trans_chain_name(tmp)) == 0) {
1825                                 kfree(name);
1826                                 goto err;
1827                         }
1828                 }
1829
1830                 nft_trans_chain_name(trans) = name;
1831         }
1832         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
1833
1834         return 0;
1835 err:
1836         free_percpu(stats);
1837         kfree(trans);
1838         return err;
1839 }
1840
1841 static int nf_tables_newchain(struct net *net, struct sock *nlsk,
1842                               struct sk_buff *skb, const struct nlmsghdr *nlh,
1843                               const struct nlattr * const nla[],
1844                               struct netlink_ext_ack *extack)
1845 {
1846         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1847         u8 genmask = nft_genmask_next(net);
1848         int family = nfmsg->nfgen_family;
1849         const struct nlattr *attr;
1850         struct nft_table *table;
1851         struct nft_chain *chain;
1852         u8 policy = NF_ACCEPT;
1853         struct nft_ctx ctx;
1854         u64 handle = 0;
1855         u32 flags = 0;
1856
1857         lockdep_assert_held(&net->nft.commit_mutex);
1858
1859         table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
1860         if (IS_ERR(table)) {
1861                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1862                 return PTR_ERR(table);
1863         }
1864
1865         chain = NULL;
1866         attr = nla[NFTA_CHAIN_NAME];
1867
1868         if (nla[NFTA_CHAIN_HANDLE]) {
1869                 handle = be64_to_cpu(nla_get_be64(nla[NFTA_CHAIN_HANDLE]));
1870                 chain = nft_chain_lookup_byhandle(table, handle, genmask);
1871                 if (IS_ERR(chain)) {
1872                         NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_HANDLE]);
1873                         return PTR_ERR(chain);
1874                 }
1875                 attr = nla[NFTA_CHAIN_HANDLE];
1876         } else {
1877                 chain = nft_chain_lookup(net, table, attr, genmask);
1878                 if (IS_ERR(chain)) {
1879                         if (PTR_ERR(chain) != -ENOENT) {
1880                                 NL_SET_BAD_ATTR(extack, attr);
1881                                 return PTR_ERR(chain);
1882                         }
1883                         chain = NULL;
1884                 }
1885         }
1886
1887         if (nla[NFTA_CHAIN_POLICY]) {
1888                 if (chain != NULL &&
1889                     !nft_is_base_chain(chain)) {
1890                         NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_POLICY]);
1891                         return -EOPNOTSUPP;
1892                 }
1893
1894                 if (chain == NULL &&
1895                     nla[NFTA_CHAIN_HOOK] == NULL) {
1896                         NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_POLICY]);
1897                         return -EOPNOTSUPP;
1898                 }
1899
1900                 policy = ntohl(nla_get_be32(nla[NFTA_CHAIN_POLICY]));
1901                 switch (policy) {
1902                 case NF_DROP:
1903                 case NF_ACCEPT:
1904                         break;
1905                 default:
1906                         return -EINVAL;
1907                 }
1908         }
1909
1910         if (nla[NFTA_CHAIN_FLAGS])
1911                 flags = ntohl(nla_get_be32(nla[NFTA_CHAIN_FLAGS]));
1912         else if (chain)
1913                 flags = chain->flags;
1914
1915         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
1916
1917         if (chain != NULL) {
1918                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
1919                         NL_SET_BAD_ATTR(extack, attr);
1920                         return -EEXIST;
1921                 }
1922                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
1923                         return -EOPNOTSUPP;
1924
1925                 return nf_tables_updchain(&ctx, genmask, policy, flags);
1926         }
1927
1928         return nf_tables_addchain(&ctx, family, genmask, policy, flags);
1929 }
1930
1931 static int nf_tables_delchain(struct net *net, struct sock *nlsk,
1932                               struct sk_buff *skb, const struct nlmsghdr *nlh,
1933                               const struct nlattr * const nla[],
1934                               struct netlink_ext_ack *extack)
1935 {
1936         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1937         u8 genmask = nft_genmask_next(net);
1938         int family = nfmsg->nfgen_family;
1939         const struct nlattr *attr;
1940         struct nft_table *table;
1941         struct nft_chain *chain;
1942         struct nft_rule *rule;
1943         struct nft_ctx ctx;
1944         u64 handle;
1945         u32 use;
1946         int err;
1947
1948         table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
1949         if (IS_ERR(table)) {
1950                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1951                 return PTR_ERR(table);
1952         }
1953
1954         if (nla[NFTA_CHAIN_HANDLE]) {
1955                 attr = nla[NFTA_CHAIN_HANDLE];
1956                 handle = be64_to_cpu(nla_get_be64(attr));
1957                 chain = nft_chain_lookup_byhandle(table, handle, genmask);
1958         } else {
1959                 attr = nla[NFTA_CHAIN_NAME];
1960                 chain = nft_chain_lookup(net, table, attr, genmask);
1961         }
1962         if (IS_ERR(chain)) {
1963                 NL_SET_BAD_ATTR(extack, attr);
1964                 return PTR_ERR(chain);
1965         }
1966
1967         if (nlh->nlmsg_flags & NLM_F_NONREC &&
1968             chain->use > 0)
1969                 return -EBUSY;
1970
1971         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
1972
1973         use = chain->use;
1974         list_for_each_entry(rule, &chain->rules, list) {
1975                 if (!nft_is_active_next(net, rule))
1976                         continue;
1977                 use--;
1978
1979                 err = nft_delrule(&ctx, rule);
1980                 if (err < 0)
1981                         return err;
1982         }
1983
1984         /* There are rules and elements that are still holding references to us,
1985          * we cannot do a recursive removal in this case.
1986          */
1987         if (use > 0) {
1988                 NL_SET_BAD_ATTR(extack, attr);
1989                 return -EBUSY;
1990         }
1991
1992         return nft_delchain(&ctx);
1993 }
1994
1995 /*
1996  * Expressions
1997  */
1998
1999 /**
2000  *      nft_register_expr - register nf_tables expr type
2001  *      @ops: expr type
2002  *
2003  *      Registers the expr type for use with nf_tables. Returns zero on
2004  *      success or a negative errno code otherwise.
2005  */
2006 int nft_register_expr(struct nft_expr_type *type)
2007 {
2008         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2009         if (type->family == NFPROTO_UNSPEC)
2010                 list_add_tail_rcu(&type->list, &nf_tables_expressions);
2011         else
2012                 list_add_rcu(&type->list, &nf_tables_expressions);
2013         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2014         return 0;
2015 }
2016 EXPORT_SYMBOL_GPL(nft_register_expr);
2017
2018 /**
2019  *      nft_unregister_expr - unregister nf_tables expr type
2020  *      @ops: expr type
2021  *
2022  *      Unregisters the expr typefor use with nf_tables.
2023  */
2024 void nft_unregister_expr(struct nft_expr_type *type)
2025 {
2026         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2027         list_del_rcu(&type->list);
2028         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2029 }
2030 EXPORT_SYMBOL_GPL(nft_unregister_expr);
2031
2032 static const struct nft_expr_type *__nft_expr_type_get(u8 family,
2033                                                        struct nlattr *nla)
2034 {
2035         const struct nft_expr_type *type, *candidate = NULL;
2036
2037         list_for_each_entry(type, &nf_tables_expressions, list) {
2038                 if (!nla_strcmp(nla, type->name)) {
2039                         if (!type->family && !candidate)
2040                                 candidate = type;
2041                         else if (type->family == family)
2042                                 candidate = type;
2043                 }
2044         }
2045         return candidate;
2046 }
2047
2048 #ifdef CONFIG_MODULES
2049 static int nft_expr_type_request_module(struct net *net, u8 family,
2050                                         struct nlattr *nla)
2051 {
2052         nft_request_module(net, "nft-expr-%u-%.*s", family,
2053                            nla_len(nla), (char *)nla_data(nla));
2054         if (__nft_expr_type_get(family, nla))
2055                 return -EAGAIN;
2056
2057         return 0;
2058 }
2059 #endif
2060
2061 static const struct nft_expr_type *nft_expr_type_get(struct net *net,
2062                                                      u8 family,
2063                                                      struct nlattr *nla)
2064 {
2065         const struct nft_expr_type *type;
2066
2067         if (nla == NULL)
2068                 return ERR_PTR(-EINVAL);
2069
2070         type = __nft_expr_type_get(family, nla);
2071         if (type != NULL && try_module_get(type->owner))
2072                 return type;
2073
2074         lockdep_nfnl_nft_mutex_not_held();
2075 #ifdef CONFIG_MODULES
2076         if (type == NULL) {
2077                 if (nft_expr_type_request_module(net, family, nla) == -EAGAIN)
2078                         return ERR_PTR(-EAGAIN);
2079
2080                 nft_request_module(net, "nft-expr-%.*s",
2081                                    nla_len(nla), (char *)nla_data(nla));
2082                 if (__nft_expr_type_get(family, nla))
2083                         return ERR_PTR(-EAGAIN);
2084         }
2085 #endif
2086         return ERR_PTR(-ENOENT);
2087 }
2088
2089 static const struct nla_policy nft_expr_policy[NFTA_EXPR_MAX + 1] = {
2090         [NFTA_EXPR_NAME]        = { .type = NLA_STRING },
2091         [NFTA_EXPR_DATA]        = { .type = NLA_NESTED },
2092 };
2093
2094 static int nf_tables_fill_expr_info(struct sk_buff *skb,
2095                                     const struct nft_expr *expr)
2096 {
2097         if (nla_put_string(skb, NFTA_EXPR_NAME, expr->ops->type->name))
2098                 goto nla_put_failure;
2099
2100         if (expr->ops->dump) {
2101                 struct nlattr *data = nla_nest_start_noflag(skb,
2102                                                             NFTA_EXPR_DATA);
2103                 if (data == NULL)
2104                         goto nla_put_failure;
2105                 if (expr->ops->dump(skb, expr) < 0)
2106                         goto nla_put_failure;
2107                 nla_nest_end(skb, data);
2108         }
2109
2110         return skb->len;
2111
2112 nla_put_failure:
2113         return -1;
2114 };
2115
2116 int nft_expr_dump(struct sk_buff *skb, unsigned int attr,
2117                   const struct nft_expr *expr)
2118 {
2119         struct nlattr *nest;
2120
2121         nest = nla_nest_start_noflag(skb, attr);
2122         if (!nest)
2123                 goto nla_put_failure;
2124         if (nf_tables_fill_expr_info(skb, expr) < 0)
2125                 goto nla_put_failure;
2126         nla_nest_end(skb, nest);
2127         return 0;
2128
2129 nla_put_failure:
2130         return -1;
2131 }
2132
2133 struct nft_expr_info {
2134         const struct nft_expr_ops       *ops;
2135         struct nlattr                   *tb[NFT_EXPR_MAXATTR + 1];
2136 };
2137
2138 static int nf_tables_expr_parse(const struct nft_ctx *ctx,
2139                                 const struct nlattr *nla,
2140                                 struct nft_expr_info *info)
2141 {
2142         const struct nft_expr_type *type;
2143         const struct nft_expr_ops *ops;
2144         struct nlattr *tb[NFTA_EXPR_MAX + 1];
2145         int err;
2146
2147         err = nla_parse_nested_deprecated(tb, NFTA_EXPR_MAX, nla,
2148                                           nft_expr_policy, NULL);
2149         if (err < 0)
2150                 return err;
2151
2152         type = nft_expr_type_get(ctx->net, ctx->family, tb[NFTA_EXPR_NAME]);
2153         if (IS_ERR(type))
2154                 return PTR_ERR(type);
2155
2156         if (tb[NFTA_EXPR_DATA]) {
2157                 err = nla_parse_nested_deprecated(info->tb, type->maxattr,
2158                                                   tb[NFTA_EXPR_DATA],
2159                                                   type->policy, NULL);
2160                 if (err < 0)
2161                         goto err1;
2162         } else
2163                 memset(info->tb, 0, sizeof(info->tb[0]) * (type->maxattr + 1));
2164
2165         if (type->select_ops != NULL) {
2166                 ops = type->select_ops(ctx,
2167                                        (const struct nlattr * const *)info->tb);
2168                 if (IS_ERR(ops)) {
2169                         err = PTR_ERR(ops);
2170 #ifdef CONFIG_MODULES
2171                         if (err == -EAGAIN)
2172                                 nft_expr_type_request_module(ctx->net,
2173                                                              ctx->family,
2174                                                              tb[NFTA_EXPR_NAME]);
2175 #endif
2176                         goto err1;
2177                 }
2178         } else
2179                 ops = type->ops;
2180
2181         info->ops = ops;
2182         return 0;
2183
2184 err1:
2185         module_put(type->owner);
2186         return err;
2187 }
2188
2189 static int nf_tables_newexpr(const struct nft_ctx *ctx,
2190                              const struct nft_expr_info *info,
2191                              struct nft_expr *expr)
2192 {
2193         const struct nft_expr_ops *ops = info->ops;
2194         int err;
2195
2196         expr->ops = ops;
2197         if (ops->init) {
2198                 err = ops->init(ctx, expr, (const struct nlattr **)info->tb);
2199                 if (err < 0)
2200                         goto err1;
2201         }
2202
2203         return 0;
2204 err1:
2205         expr->ops = NULL;
2206         return err;
2207 }
2208
2209 static void nf_tables_expr_destroy(const struct nft_ctx *ctx,
2210                                    struct nft_expr *expr)
2211 {
2212         const struct nft_expr_type *type = expr->ops->type;
2213
2214         if (expr->ops->destroy)
2215                 expr->ops->destroy(ctx, expr);
2216         module_put(type->owner);
2217 }
2218
2219 struct nft_expr *nft_expr_init(const struct nft_ctx *ctx,
2220                                const struct nlattr *nla)
2221 {
2222         struct nft_expr_info info;
2223         struct nft_expr *expr;
2224         struct module *owner;
2225         int err;
2226
2227         err = nf_tables_expr_parse(ctx, nla, &info);
2228         if (err < 0)
2229                 goto err1;
2230
2231         err = -ENOMEM;
2232         expr = kzalloc(info.ops->size, GFP_KERNEL);
2233         if (expr == NULL)
2234                 goto err2;
2235
2236         err = nf_tables_newexpr(ctx, &info, expr);
2237         if (err < 0)
2238                 goto err3;
2239
2240         return expr;
2241 err3:
2242         kfree(expr);
2243 err2:
2244         owner = info.ops->type->owner;
2245         if (info.ops->type->release_ops)
2246                 info.ops->type->release_ops(info.ops);
2247
2248         module_put(owner);
2249 err1:
2250         return ERR_PTR(err);
2251 }
2252
2253 void nft_expr_destroy(const struct nft_ctx *ctx, struct nft_expr *expr)
2254 {
2255         nf_tables_expr_destroy(ctx, expr);
2256         kfree(expr);
2257 }
2258
2259 /*
2260  * Rules
2261  */
2262
2263 static struct nft_rule *__nft_rule_lookup(const struct nft_chain *chain,
2264                                           u64 handle)
2265 {
2266         struct nft_rule *rule;
2267
2268         // FIXME: this sucks
2269         list_for_each_entry_rcu(rule, &chain->rules, list) {
2270                 if (handle == rule->handle)
2271                         return rule;
2272         }
2273
2274         return ERR_PTR(-ENOENT);
2275 }
2276
2277 static struct nft_rule *nft_rule_lookup(const struct nft_chain *chain,
2278                                         const struct nlattr *nla)
2279 {
2280         if (nla == NULL)
2281                 return ERR_PTR(-EINVAL);
2282
2283         return __nft_rule_lookup(chain, be64_to_cpu(nla_get_be64(nla)));
2284 }
2285
2286 static const struct nla_policy nft_rule_policy[NFTA_RULE_MAX + 1] = {
2287         [NFTA_RULE_TABLE]       = { .type = NLA_STRING,
2288                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
2289         [NFTA_RULE_CHAIN]       = { .type = NLA_STRING,
2290                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
2291         [NFTA_RULE_HANDLE]      = { .type = NLA_U64 },
2292         [NFTA_RULE_EXPRESSIONS] = { .type = NLA_NESTED },
2293         [NFTA_RULE_COMPAT]      = { .type = NLA_NESTED },
2294         [NFTA_RULE_POSITION]    = { .type = NLA_U64 },
2295         [NFTA_RULE_USERDATA]    = { .type = NLA_BINARY,
2296                                     .len = NFT_USERDATA_MAXLEN },
2297         [NFTA_RULE_ID]          = { .type = NLA_U32 },
2298         [NFTA_RULE_POSITION_ID] = { .type = NLA_U32 },
2299 };
2300
2301 static int nf_tables_fill_rule_info(struct sk_buff *skb, struct net *net,
2302                                     u32 portid, u32 seq, int event,
2303                                     u32 flags, int family,
2304                                     const struct nft_table *table,
2305                                     const struct nft_chain *chain,
2306                                     const struct nft_rule *rule,
2307                                     const struct nft_rule *prule)
2308 {
2309         struct nlmsghdr *nlh;
2310         struct nfgenmsg *nfmsg;
2311         const struct nft_expr *expr, *next;
2312         struct nlattr *list;
2313         u16 type = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
2314
2315         nlh = nlmsg_put(skb, portid, seq, type, sizeof(struct nfgenmsg), flags);
2316         if (nlh == NULL)
2317                 goto nla_put_failure;
2318
2319         nfmsg = nlmsg_data(nlh);
2320         nfmsg->nfgen_family     = family;
2321         nfmsg->version          = NFNETLINK_V0;
2322         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
2323
2324         if (nla_put_string(skb, NFTA_RULE_TABLE, table->name))
2325                 goto nla_put_failure;
2326         if (nla_put_string(skb, NFTA_RULE_CHAIN, chain->name))
2327                 goto nla_put_failure;
2328         if (nla_put_be64(skb, NFTA_RULE_HANDLE, cpu_to_be64(rule->handle),
2329                          NFTA_RULE_PAD))
2330                 goto nla_put_failure;
2331
2332         if (event != NFT_MSG_DELRULE && prule) {
2333                 if (nla_put_be64(skb, NFTA_RULE_POSITION,
2334                                  cpu_to_be64(prule->handle),
2335                                  NFTA_RULE_PAD))
2336                         goto nla_put_failure;
2337         }
2338
2339         list = nla_nest_start_noflag(skb, NFTA_RULE_EXPRESSIONS);
2340         if (list == NULL)
2341                 goto nla_put_failure;
2342         nft_rule_for_each_expr(expr, next, rule) {
2343                 if (nft_expr_dump(skb, NFTA_LIST_ELEM, expr) < 0)
2344                         goto nla_put_failure;
2345         }
2346         nla_nest_end(skb, list);
2347
2348         if (rule->udata) {
2349                 struct nft_userdata *udata = nft_userdata(rule);
2350                 if (nla_put(skb, NFTA_RULE_USERDATA, udata->len + 1,
2351                             udata->data) < 0)
2352                         goto nla_put_failure;
2353         }
2354
2355         nlmsg_end(skb, nlh);
2356         return 0;
2357
2358 nla_put_failure:
2359         nlmsg_trim(skb, nlh);
2360         return -1;
2361 }
2362
2363 static void nf_tables_rule_notify(const struct nft_ctx *ctx,
2364                                   const struct nft_rule *rule, int event)
2365 {
2366         struct sk_buff *skb;
2367         int err;
2368
2369         if (!ctx->report &&
2370             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
2371                 return;
2372
2373         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
2374         if (skb == NULL)
2375                 goto err;
2376
2377         err = nf_tables_fill_rule_info(skb, ctx->net, ctx->portid, ctx->seq,
2378                                        event, 0, ctx->family, ctx->table,
2379                                        ctx->chain, rule, NULL);
2380         if (err < 0) {
2381                 kfree_skb(skb);
2382                 goto err;
2383         }
2384
2385         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
2386                        ctx->report, GFP_KERNEL);
2387         return;
2388 err:
2389         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
2390 }
2391
2392 struct nft_rule_dump_ctx {
2393         char *table;
2394         char *chain;
2395 };
2396
2397 static int __nf_tables_dump_rules(struct sk_buff *skb,
2398                                   unsigned int *idx,
2399                                   struct netlink_callback *cb,
2400                                   const struct nft_table *table,
2401                                   const struct nft_chain *chain)
2402 {
2403         struct net *net = sock_net(skb->sk);
2404         const struct nft_rule *rule, *prule;
2405         unsigned int s_idx = cb->args[0];
2406
2407         prule = NULL;
2408         list_for_each_entry_rcu(rule, &chain->rules, list) {
2409                 if (!nft_is_active(net, rule))
2410                         goto cont_skip;
2411                 if (*idx < s_idx)
2412                         goto cont;
2413                 if (*idx > s_idx) {
2414                         memset(&cb->args[1], 0,
2415                                         sizeof(cb->args) - sizeof(cb->args[0]));
2416                 }
2417                 if (nf_tables_fill_rule_info(skb, net, NETLINK_CB(cb->skb).portid,
2418                                         cb->nlh->nlmsg_seq,
2419                                         NFT_MSG_NEWRULE,
2420                                         NLM_F_MULTI | NLM_F_APPEND,
2421                                         table->family,
2422                                         table, chain, rule, prule) < 0)
2423                         return 1;
2424
2425                 nl_dump_check_consistent(cb, nlmsg_hdr(skb));
2426 cont:
2427                 prule = rule;
2428 cont_skip:
2429                 (*idx)++;
2430         }
2431         return 0;
2432 }
2433
2434 static int nf_tables_dump_rules(struct sk_buff *skb,
2435                                 struct netlink_callback *cb)
2436 {
2437         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
2438         const struct nft_rule_dump_ctx *ctx = cb->data;
2439         struct nft_table *table;
2440         const struct nft_chain *chain;
2441         unsigned int idx = 0;
2442         struct net *net = sock_net(skb->sk);
2443         int family = nfmsg->nfgen_family;
2444
2445         rcu_read_lock();
2446         cb->seq = net->nft.base_seq;
2447
2448         list_for_each_entry_rcu(table, &net->nft.tables, list) {
2449                 if (family != NFPROTO_UNSPEC && family != table->family)
2450                         continue;
2451
2452                 if (ctx && ctx->table && strcmp(ctx->table, table->name) != 0)
2453                         continue;
2454
2455                 if (ctx && ctx->table && ctx->chain) {
2456                         struct rhlist_head *list, *tmp;
2457
2458                         list = rhltable_lookup(&table->chains_ht, ctx->chain,
2459                                                nft_chain_ht_params);
2460                         if (!list)
2461                                 goto done;
2462
2463                         rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) {
2464                                 if (!nft_is_active(net, chain))
2465                                         continue;
2466                                 __nf_tables_dump_rules(skb, &idx,
2467                                                        cb, table, chain);
2468                                 break;
2469                         }
2470                         goto done;
2471                 }
2472
2473                 list_for_each_entry_rcu(chain, &table->chains, list) {
2474                         if (__nf_tables_dump_rules(skb, &idx, cb, table, chain))
2475                                 goto done;
2476                 }
2477
2478                 if (ctx && ctx->table)
2479                         break;
2480         }
2481 done:
2482         rcu_read_unlock();
2483
2484         cb->args[0] = idx;
2485         return skb->len;
2486 }
2487
2488 static int nf_tables_dump_rules_start(struct netlink_callback *cb)
2489 {
2490         const struct nlattr * const *nla = cb->data;
2491         struct nft_rule_dump_ctx *ctx = NULL;
2492
2493         if (nla[NFTA_RULE_TABLE] || nla[NFTA_RULE_CHAIN]) {
2494                 ctx = kzalloc(sizeof(*ctx), GFP_ATOMIC);
2495                 if (!ctx)
2496                         return -ENOMEM;
2497
2498                 if (nla[NFTA_RULE_TABLE]) {
2499                         ctx->table = nla_strdup(nla[NFTA_RULE_TABLE],
2500                                                         GFP_ATOMIC);
2501                         if (!ctx->table) {
2502                                 kfree(ctx);
2503                                 return -ENOMEM;
2504                         }
2505                 }
2506                 if (nla[NFTA_RULE_CHAIN]) {
2507                         ctx->chain = nla_strdup(nla[NFTA_RULE_CHAIN],
2508                                                 GFP_ATOMIC);
2509                         if (!ctx->chain) {
2510                                 kfree(ctx->table);
2511                                 kfree(ctx);
2512                                 return -ENOMEM;
2513                         }
2514                 }
2515         }
2516
2517         cb->data = ctx;
2518         return 0;
2519 }
2520
2521 static int nf_tables_dump_rules_done(struct netlink_callback *cb)
2522 {
2523         struct nft_rule_dump_ctx *ctx = cb->data;
2524
2525         if (ctx) {
2526                 kfree(ctx->table);
2527                 kfree(ctx->chain);
2528                 kfree(ctx);
2529         }
2530         return 0;
2531 }
2532
2533 /* called with rcu_read_lock held */
2534 static int nf_tables_getrule(struct net *net, struct sock *nlsk,
2535                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2536                              const struct nlattr * const nla[],
2537                              struct netlink_ext_ack *extack)
2538 {
2539         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2540         u8 genmask = nft_genmask_cur(net);
2541         const struct nft_chain *chain;
2542         const struct nft_rule *rule;
2543         struct nft_table *table;
2544         struct sk_buff *skb2;
2545         int family = nfmsg->nfgen_family;
2546         int err;
2547
2548         if (nlh->nlmsg_flags & NLM_F_DUMP) {
2549                 struct netlink_dump_control c = {
2550                         .start= nf_tables_dump_rules_start,
2551                         .dump = nf_tables_dump_rules,
2552                         .done = nf_tables_dump_rules_done,
2553                         .module = THIS_MODULE,
2554                         .data = (void *)nla,
2555                 };
2556
2557                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
2558         }
2559
2560         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2561         if (IS_ERR(table)) {
2562                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2563                 return PTR_ERR(table);
2564         }
2565
2566         chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
2567         if (IS_ERR(chain)) {
2568                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2569                 return PTR_ERR(chain);
2570         }
2571
2572         rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
2573         if (IS_ERR(rule)) {
2574                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2575                 return PTR_ERR(rule);
2576         }
2577
2578         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
2579         if (!skb2)
2580                 return -ENOMEM;
2581
2582         err = nf_tables_fill_rule_info(skb2, net, NETLINK_CB(skb).portid,
2583                                        nlh->nlmsg_seq, NFT_MSG_NEWRULE, 0,
2584                                        family, table, chain, rule, NULL);
2585         if (err < 0)
2586                 goto err;
2587
2588         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
2589
2590 err:
2591         kfree_skb(skb2);
2592         return err;
2593 }
2594
2595 static void nf_tables_rule_destroy(const struct nft_ctx *ctx,
2596                                    struct nft_rule *rule)
2597 {
2598         struct nft_expr *expr, *next;
2599
2600         /*
2601          * Careful: some expressions might not be initialized in case this
2602          * is called on error from nf_tables_newrule().
2603          */
2604         expr = nft_expr_first(rule);
2605         while (expr != nft_expr_last(rule) && expr->ops) {
2606                 next = nft_expr_next(expr);
2607                 nf_tables_expr_destroy(ctx, expr);
2608                 expr = next;
2609         }
2610         kfree(rule);
2611 }
2612
2613 static void nf_tables_rule_release(const struct nft_ctx *ctx,
2614                                    struct nft_rule *rule)
2615 {
2616         nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_RELEASE);
2617         nf_tables_rule_destroy(ctx, rule);
2618 }
2619
2620 int nft_chain_validate(const struct nft_ctx *ctx, const struct nft_chain *chain)
2621 {
2622         struct nft_expr *expr, *last;
2623         const struct nft_data *data;
2624         struct nft_rule *rule;
2625         int err;
2626
2627         if (ctx->level == NFT_JUMP_STACK_SIZE)
2628                 return -EMLINK;
2629
2630         list_for_each_entry(rule, &chain->rules, list) {
2631                 if (!nft_is_active_next(ctx->net, rule))
2632                         continue;
2633
2634                 nft_rule_for_each_expr(expr, last, rule) {
2635                         if (!expr->ops->validate)
2636                                 continue;
2637
2638                         err = expr->ops->validate(ctx, expr, &data);
2639                         if (err < 0)
2640                                 return err;
2641                 }
2642         }
2643
2644         return 0;
2645 }
2646 EXPORT_SYMBOL_GPL(nft_chain_validate);
2647
2648 static int nft_table_validate(struct net *net, const struct nft_table *table)
2649 {
2650         struct nft_chain *chain;
2651         struct nft_ctx ctx = {
2652                 .net    = net,
2653                 .family = table->family,
2654         };
2655         int err;
2656
2657         list_for_each_entry(chain, &table->chains, list) {
2658                 if (!nft_is_base_chain(chain))
2659                         continue;
2660
2661                 ctx.chain = chain;
2662                 err = nft_chain_validate(&ctx, chain);
2663                 if (err < 0)
2664                         return err;
2665         }
2666
2667         return 0;
2668 }
2669
2670 static struct nft_rule *nft_rule_lookup_byid(const struct net *net,
2671                                              const struct nlattr *nla);
2672
2673 #define NFT_RULE_MAXEXPRS       128
2674
2675 static int nf_tables_newrule(struct net *net, struct sock *nlsk,
2676                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2677                              const struct nlattr * const nla[],
2678                              struct netlink_ext_ack *extack)
2679 {
2680         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2681         u8 genmask = nft_genmask_next(net);
2682         struct nft_expr_info *info = NULL;
2683         int family = nfmsg->nfgen_family;
2684         struct nft_flow_rule *flow;
2685         struct nft_table *table;
2686         struct nft_chain *chain;
2687         struct nft_rule *rule, *old_rule = NULL;
2688         struct nft_userdata *udata;
2689         struct nft_trans *trans = NULL;
2690         struct nft_expr *expr;
2691         struct nft_ctx ctx;
2692         struct nlattr *tmp;
2693         unsigned int size, i, n, ulen = 0, usize = 0;
2694         int err, rem;
2695         u64 handle, pos_handle;
2696
2697         lockdep_assert_held(&net->nft.commit_mutex);
2698
2699         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2700         if (IS_ERR(table)) {
2701                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2702                 return PTR_ERR(table);
2703         }
2704
2705         chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
2706         if (IS_ERR(chain)) {
2707                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2708                 return PTR_ERR(chain);
2709         }
2710
2711         if (nla[NFTA_RULE_HANDLE]) {
2712                 handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_HANDLE]));
2713                 rule = __nft_rule_lookup(chain, handle);
2714                 if (IS_ERR(rule)) {
2715                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2716                         return PTR_ERR(rule);
2717                 }
2718
2719                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
2720                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2721                         return -EEXIST;
2722                 }
2723                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
2724                         old_rule = rule;
2725                 else
2726                         return -EOPNOTSUPP;
2727         } else {
2728                 if (!(nlh->nlmsg_flags & NLM_F_CREATE) ||
2729                     nlh->nlmsg_flags & NLM_F_REPLACE)
2730                         return -EINVAL;
2731                 handle = nf_tables_alloc_handle(table);
2732
2733                 if (chain->use == UINT_MAX)
2734                         return -EOVERFLOW;
2735
2736                 if (nla[NFTA_RULE_POSITION]) {
2737                         pos_handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_POSITION]));
2738                         old_rule = __nft_rule_lookup(chain, pos_handle);
2739                         if (IS_ERR(old_rule)) {
2740                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_POSITION]);
2741                                 return PTR_ERR(old_rule);
2742                         }
2743                 } else if (nla[NFTA_RULE_POSITION_ID]) {
2744                         old_rule = nft_rule_lookup_byid(net, nla[NFTA_RULE_POSITION_ID]);
2745                         if (IS_ERR(old_rule)) {
2746                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_POSITION_ID]);
2747                                 return PTR_ERR(old_rule);
2748                         }
2749                 }
2750         }
2751
2752         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
2753
2754         n = 0;
2755         size = 0;
2756         if (nla[NFTA_RULE_EXPRESSIONS]) {
2757                 info = kvmalloc_array(NFT_RULE_MAXEXPRS,
2758                                       sizeof(struct nft_expr_info),
2759                                       GFP_KERNEL);
2760                 if (!info)
2761                         return -ENOMEM;
2762
2763                 nla_for_each_nested(tmp, nla[NFTA_RULE_EXPRESSIONS], rem) {
2764                         err = -EINVAL;
2765                         if (nla_type(tmp) != NFTA_LIST_ELEM)
2766                                 goto err1;
2767                         if (n == NFT_RULE_MAXEXPRS)
2768                                 goto err1;
2769                         err = nf_tables_expr_parse(&ctx, tmp, &info[n]);
2770                         if (err < 0)
2771                                 goto err1;
2772                         size += info[n].ops->size;
2773                         n++;
2774                 }
2775         }
2776         /* Check for overflow of dlen field */
2777         err = -EFBIG;
2778         if (size >= 1 << 12)
2779                 goto err1;
2780
2781         if (nla[NFTA_RULE_USERDATA]) {
2782                 ulen = nla_len(nla[NFTA_RULE_USERDATA]);
2783                 if (ulen > 0)
2784                         usize = sizeof(struct nft_userdata) + ulen;
2785         }
2786
2787         err = -ENOMEM;
2788         rule = kzalloc(sizeof(*rule) + size + usize, GFP_KERNEL);
2789         if (rule == NULL)
2790                 goto err1;
2791
2792         nft_activate_next(net, rule);
2793
2794         rule->handle = handle;
2795         rule->dlen   = size;
2796         rule->udata  = ulen ? 1 : 0;
2797
2798         if (ulen) {
2799                 udata = nft_userdata(rule);
2800                 udata->len = ulen - 1;
2801                 nla_memcpy(udata->data, nla[NFTA_RULE_USERDATA], ulen);
2802         }
2803
2804         expr = nft_expr_first(rule);
2805         for (i = 0; i < n; i++) {
2806                 err = nf_tables_newexpr(&ctx, &info[i], expr);
2807                 if (err < 0)
2808                         goto err2;
2809
2810                 if (info[i].ops->validate)
2811                         nft_validate_state_update(net, NFT_VALIDATE_NEED);
2812
2813                 info[i].ops = NULL;
2814                 expr = nft_expr_next(expr);
2815         }
2816
2817         if (nlh->nlmsg_flags & NLM_F_REPLACE) {
2818                 trans = nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule);
2819                 if (trans == NULL) {
2820                         err = -ENOMEM;
2821                         goto err2;
2822                 }
2823                 err = nft_delrule(&ctx, old_rule);
2824                 if (err < 0) {
2825                         nft_trans_destroy(trans);
2826                         goto err2;
2827                 }
2828
2829                 list_add_tail_rcu(&rule->list, &old_rule->list);
2830         } else {
2831                 trans = nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule);
2832                 if (!trans) {
2833                         err = -ENOMEM;
2834                         goto err2;
2835                 }
2836
2837                 if (nlh->nlmsg_flags & NLM_F_APPEND) {
2838                         if (old_rule)
2839                                 list_add_rcu(&rule->list, &old_rule->list);
2840                         else
2841                                 list_add_tail_rcu(&rule->list, &chain->rules);
2842                  } else {
2843                         if (old_rule)
2844                                 list_add_tail_rcu(&rule->list, &old_rule->list);
2845                         else
2846                                 list_add_rcu(&rule->list, &chain->rules);
2847                 }
2848         }
2849         kvfree(info);
2850         chain->use++;
2851
2852         if (net->nft.validate_state == NFT_VALIDATE_DO)
2853                 return nft_table_validate(net, table);
2854
2855         if (chain->flags & NFT_CHAIN_HW_OFFLOAD) {
2856                 flow = nft_flow_rule_create(net, rule);
2857                 if (IS_ERR(flow))
2858                         return PTR_ERR(flow);
2859
2860                 nft_trans_flow_rule(trans) = flow;
2861         }
2862
2863         return 0;
2864 err2:
2865         nf_tables_rule_release(&ctx, rule);
2866 err1:
2867         for (i = 0; i < n; i++) {
2868                 if (info[i].ops) {
2869                         module_put(info[i].ops->type->owner);
2870                         if (info[i].ops->type->release_ops)
2871                                 info[i].ops->type->release_ops(info[i].ops);
2872                 }
2873         }
2874         kvfree(info);
2875         return err;
2876 }
2877
2878 static struct nft_rule *nft_rule_lookup_byid(const struct net *net,
2879                                              const struct nlattr *nla)
2880 {
2881         u32 id = ntohl(nla_get_be32(nla));
2882         struct nft_trans *trans;
2883
2884         list_for_each_entry(trans, &net->nft.commit_list, list) {
2885                 struct nft_rule *rule = nft_trans_rule(trans);
2886
2887                 if (trans->msg_type == NFT_MSG_NEWRULE &&
2888                     id == nft_trans_rule_id(trans))
2889                         return rule;
2890         }
2891         return ERR_PTR(-ENOENT);
2892 }
2893
2894 static int nf_tables_delrule(struct net *net, struct sock *nlsk,
2895                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2896                              const struct nlattr * const nla[],
2897                              struct netlink_ext_ack *extack)
2898 {
2899         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2900         u8 genmask = nft_genmask_next(net);
2901         struct nft_table *table;
2902         struct nft_chain *chain = NULL;
2903         struct nft_rule *rule;
2904         int family = nfmsg->nfgen_family, err = 0;
2905         struct nft_ctx ctx;
2906
2907         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2908         if (IS_ERR(table)) {
2909                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2910                 return PTR_ERR(table);
2911         }
2912
2913         if (nla[NFTA_RULE_CHAIN]) {
2914                 chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN],
2915                                          genmask);
2916                 if (IS_ERR(chain)) {
2917                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2918                         return PTR_ERR(chain);
2919                 }
2920         }
2921
2922         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
2923
2924         if (chain) {
2925                 if (nla[NFTA_RULE_HANDLE]) {
2926                         rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
2927                         if (IS_ERR(rule)) {
2928                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2929                                 return PTR_ERR(rule);
2930                         }
2931
2932                         err = nft_delrule(&ctx, rule);
2933                 } else if (nla[NFTA_RULE_ID]) {
2934                         rule = nft_rule_lookup_byid(net, nla[NFTA_RULE_ID]);
2935                         if (IS_ERR(rule)) {
2936                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_ID]);
2937                                 return PTR_ERR(rule);
2938                         }
2939
2940                         err = nft_delrule(&ctx, rule);
2941                 } else {
2942                         err = nft_delrule_by_chain(&ctx);
2943                 }
2944         } else {
2945                 list_for_each_entry(chain, &table->chains, list) {
2946                         if (!nft_is_active_next(net, chain))
2947                                 continue;
2948
2949                         ctx.chain = chain;
2950                         err = nft_delrule_by_chain(&ctx);
2951                         if (err < 0)
2952                                 break;
2953                 }
2954         }
2955
2956         return err;
2957 }
2958
2959 /*
2960  * Sets
2961  */
2962
2963 static LIST_HEAD(nf_tables_set_types);
2964
2965 int nft_register_set(struct nft_set_type *type)
2966 {
2967         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2968         list_add_tail_rcu(&type->list, &nf_tables_set_types);
2969         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2970         return 0;
2971 }
2972 EXPORT_SYMBOL_GPL(nft_register_set);
2973
2974 void nft_unregister_set(struct nft_set_type *type)
2975 {
2976         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2977         list_del_rcu(&type->list);
2978         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2979 }
2980 EXPORT_SYMBOL_GPL(nft_unregister_set);
2981
2982 #define NFT_SET_FEATURES        (NFT_SET_INTERVAL | NFT_SET_MAP | \
2983                                  NFT_SET_TIMEOUT | NFT_SET_OBJECT | \
2984                                  NFT_SET_EVAL)
2985
2986 static bool nft_set_ops_candidate(const struct nft_set_type *type, u32 flags)
2987 {
2988         return (flags & type->features) == (flags & NFT_SET_FEATURES);
2989 }
2990
2991 /*
2992  * Select a set implementation based on the data characteristics and the
2993  * given policy. The total memory use might not be known if no size is
2994  * given, in that case the amount of memory per element is used.
2995  */
2996 static const struct nft_set_ops *
2997 nft_select_set_ops(const struct nft_ctx *ctx,
2998                    const struct nlattr * const nla[],
2999                    const struct nft_set_desc *desc,
3000                    enum nft_set_policies policy)
3001 {
3002         const struct nft_set_ops *ops, *bops;
3003         struct nft_set_estimate est, best;
3004         const struct nft_set_type *type;
3005         u32 flags = 0;
3006
3007         lockdep_assert_held(&ctx->net->nft.commit_mutex);
3008         lockdep_nfnl_nft_mutex_not_held();
3009 #ifdef CONFIG_MODULES
3010         if (list_empty(&nf_tables_set_types)) {
3011                 nft_request_module(ctx->net, "nft-set");
3012                 if (!list_empty(&nf_tables_set_types))
3013                         return ERR_PTR(-EAGAIN);
3014         }
3015 #endif
3016         if (nla[NFTA_SET_FLAGS] != NULL)
3017                 flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
3018
3019         bops        = NULL;
3020         best.size   = ~0;
3021         best.lookup = ~0;
3022         best.space  = ~0;
3023
3024         list_for_each_entry(type, &nf_tables_set_types, list) {
3025                 ops = &type->ops;
3026
3027                 if (!nft_set_ops_candidate(type, flags))
3028                         continue;
3029                 if (!ops->estimate(desc, flags, &est))
3030                         continue;
3031
3032                 switch (policy) {
3033                 case NFT_SET_POL_PERFORMANCE:
3034                         if (est.lookup < best.lookup)
3035                                 break;
3036                         if (est.lookup == best.lookup &&
3037                             est.space < best.space)
3038                                 break;
3039                         continue;
3040                 case NFT_SET_POL_MEMORY:
3041                         if (!desc->size) {
3042                                 if (est.space < best.space)
3043                                         break;
3044                                 if (est.space == best.space &&
3045                                     est.lookup < best.lookup)
3046                                         break;
3047                         } else if (est.size < best.size || !bops) {
3048                                 break;
3049                         }
3050                         continue;
3051                 default:
3052                         break;
3053                 }
3054
3055                 if (!try_module_get(type->owner))
3056                         continue;
3057                 if (bops != NULL)
3058                         module_put(to_set_type(bops)->owner);
3059
3060                 bops = ops;
3061                 best = est;
3062         }
3063
3064         if (bops != NULL)
3065                 return bops;
3066
3067         return ERR_PTR(-EOPNOTSUPP);
3068 }
3069
3070 static const struct nla_policy nft_set_policy[NFTA_SET_MAX + 1] = {
3071         [NFTA_SET_TABLE]                = { .type = NLA_STRING,
3072                                             .len = NFT_TABLE_MAXNAMELEN - 1 },
3073         [NFTA_SET_NAME]                 = { .type = NLA_STRING,
3074                                             .len = NFT_SET_MAXNAMELEN - 1 },
3075         [NFTA_SET_FLAGS]                = { .type = NLA_U32 },
3076         [NFTA_SET_KEY_TYPE]             = { .type = NLA_U32 },
3077         [NFTA_SET_KEY_LEN]              = { .type = NLA_U32 },
3078         [NFTA_SET_DATA_TYPE]            = { .type = NLA_U32 },
3079         [NFTA_SET_DATA_LEN]             = { .type = NLA_U32 },
3080         [NFTA_SET_POLICY]               = { .type = NLA_U32 },
3081         [NFTA_SET_DESC]                 = { .type = NLA_NESTED },
3082         [NFTA_SET_ID]                   = { .type = NLA_U32 },
3083         [NFTA_SET_TIMEOUT]              = { .type = NLA_U64 },
3084         [NFTA_SET_GC_INTERVAL]          = { .type = NLA_U32 },
3085         [NFTA_SET_USERDATA]             = { .type = NLA_BINARY,
3086                                             .len  = NFT_USERDATA_MAXLEN },
3087         [NFTA_SET_OBJ_TYPE]             = { .type = NLA_U32 },
3088         [NFTA_SET_HANDLE]               = { .type = NLA_U64 },
3089 };
3090
3091 static const struct nla_policy nft_set_desc_policy[NFTA_SET_DESC_MAX + 1] = {
3092         [NFTA_SET_DESC_SIZE]            = { .type = NLA_U32 },
3093 };
3094
3095 static int nft_ctx_init_from_setattr(struct nft_ctx *ctx, struct net *net,
3096                                      const struct sk_buff *skb,
3097                                      const struct nlmsghdr *nlh,
3098                                      const struct nlattr * const nla[],
3099                                      struct netlink_ext_ack *extack,
3100                                      u8 genmask)
3101 {
3102         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3103         int family = nfmsg->nfgen_family;
3104         struct nft_table *table = NULL;
3105
3106         if (nla[NFTA_SET_TABLE] != NULL) {
3107                 table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family,
3108                                          genmask);
3109                 if (IS_ERR(table)) {
3110                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
3111                         return PTR_ERR(table);
3112                 }
3113         }
3114
3115         nft_ctx_init(ctx, net, skb, nlh, family, table, NULL, nla);
3116         return 0;
3117 }
3118
3119 static struct nft_set *nft_set_lookup(const struct nft_table *table,
3120                                       const struct nlattr *nla, u8 genmask)
3121 {
3122         struct nft_set *set;
3123
3124         if (nla == NULL)
3125                 return ERR_PTR(-EINVAL);
3126
3127         list_for_each_entry_rcu(set, &table->sets, list) {
3128                 if (!nla_strcmp(nla, set->name) &&
3129                     nft_active_genmask(set, genmask))
3130                         return set;
3131         }
3132         return ERR_PTR(-ENOENT);
3133 }
3134
3135 static struct nft_set *nft_set_lookup_byhandle(const struct nft_table *table,
3136                                                const struct nlattr *nla,
3137                                                u8 genmask)
3138 {
3139         struct nft_set *set;
3140
3141         list_for_each_entry(set, &table->sets, list) {
3142                 if (be64_to_cpu(nla_get_be64(nla)) == set->handle &&
3143                     nft_active_genmask(set, genmask))
3144                         return set;
3145         }
3146         return ERR_PTR(-ENOENT);
3147 }
3148
3149 static struct nft_set *nft_set_lookup_byid(const struct net *net,
3150                                            const struct nlattr *nla, u8 genmask)
3151 {
3152         struct nft_trans *trans;
3153         u32 id = ntohl(nla_get_be32(nla));
3154
3155         list_for_each_entry(trans, &net->nft.commit_list, list) {
3156                 if (trans->msg_type == NFT_MSG_NEWSET) {
3157                         struct nft_set *set = nft_trans_set(trans);
3158
3159                         if (id == nft_trans_set_id(trans) &&
3160                             nft_active_genmask(set, genmask))
3161                                 return set;
3162                 }
3163         }
3164         return ERR_PTR(-ENOENT);
3165 }
3166
3167 struct nft_set *nft_set_lookup_global(const struct net *net,
3168                                       const struct nft_table *table,
3169                                       const struct nlattr *nla_set_name,
3170                                       const struct nlattr *nla_set_id,
3171                                       u8 genmask)
3172 {
3173         struct nft_set *set;
3174
3175         set = nft_set_lookup(table, nla_set_name, genmask);
3176         if (IS_ERR(set)) {
3177                 if (!nla_set_id)
3178                         return set;
3179
3180                 set = nft_set_lookup_byid(net, nla_set_id, genmask);
3181         }
3182         return set;
3183 }
3184 EXPORT_SYMBOL_GPL(nft_set_lookup_global);
3185
3186 static int nf_tables_set_alloc_name(struct nft_ctx *ctx, struct nft_set *set,
3187                                     const char *name)
3188 {
3189         const struct nft_set *i;
3190         const char *p;
3191         unsigned long *inuse;
3192         unsigned int n = 0, min = 0;
3193
3194         p = strchr(name, '%');
3195         if (p != NULL) {
3196                 if (p[1] != 'd' || strchr(p + 2, '%'))
3197                         return -EINVAL;
3198
3199                 inuse = (unsigned long *)get_zeroed_page(GFP_KERNEL);
3200                 if (inuse == NULL)
3201                         return -ENOMEM;
3202 cont:
3203                 list_for_each_entry(i, &ctx->table->sets, list) {
3204                         int tmp;
3205
3206                         if (!nft_is_active_next(ctx->net, set))
3207                                 continue;
3208                         if (!sscanf(i->name, name, &tmp))
3209                                 continue;
3210                         if (tmp < min || tmp >= min + BITS_PER_BYTE * PAGE_SIZE)
3211                                 continue;
3212
3213                         set_bit(tmp - min, inuse);
3214                 }
3215
3216                 n = find_first_zero_bit(inuse, BITS_PER_BYTE * PAGE_SIZE);
3217                 if (n >= BITS_PER_BYTE * PAGE_SIZE) {
3218                         min += BITS_PER_BYTE * PAGE_SIZE;
3219                         memset(inuse, 0, PAGE_SIZE);
3220                         goto cont;
3221                 }
3222                 free_page((unsigned long)inuse);
3223         }
3224
3225         set->name = kasprintf(GFP_KERNEL, name, min + n);
3226         if (!set->name)
3227                 return -ENOMEM;
3228
3229         list_for_each_entry(i, &ctx->table->sets, list) {
3230                 if (!nft_is_active_next(ctx->net, i))
3231                         continue;
3232                 if (!strcmp(set->name, i->name)) {
3233                         kfree(set->name);
3234                         return -ENFILE;
3235                 }
3236         }
3237         return 0;
3238 }
3239
3240 static int nf_msecs_to_jiffies64(const struct nlattr *nla, u64 *result)
3241 {
3242         u64 ms = be64_to_cpu(nla_get_be64(nla));
3243         u64 max = (u64)(~((u64)0));
3244
3245         max = div_u64(max, NSEC_PER_MSEC);
3246         if (ms >= max)
3247                 return -ERANGE;
3248
3249         ms *= NSEC_PER_MSEC;
3250         *result = nsecs_to_jiffies64(ms);
3251         return 0;
3252 }
3253
3254 static __be64 nf_jiffies64_to_msecs(u64 input)
3255 {
3256         return cpu_to_be64(jiffies64_to_msecs(input));
3257 }
3258
3259 static int nf_tables_fill_set(struct sk_buff *skb, const struct nft_ctx *ctx,
3260                               const struct nft_set *set, u16 event, u16 flags)
3261 {
3262         struct nfgenmsg *nfmsg;
3263         struct nlmsghdr *nlh;
3264         struct nlattr *desc;
3265         u32 portid = ctx->portid;
3266         u32 seq = ctx->seq;
3267
3268         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
3269         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
3270                         flags);
3271         if (nlh == NULL)
3272                 goto nla_put_failure;
3273
3274         nfmsg = nlmsg_data(nlh);
3275         nfmsg->nfgen_family     = ctx->family;
3276         nfmsg->version          = NFNETLINK_V0;
3277         nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
3278
3279         if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
3280                 goto nla_put_failure;
3281         if (nla_put_string(skb, NFTA_SET_NAME, set->name))
3282                 goto nla_put_failure;
3283         if (nla_put_be64(skb, NFTA_SET_HANDLE, cpu_to_be64(set->handle),
3284                          NFTA_SET_PAD))
3285                 goto nla_put_failure;
3286         if (set->flags != 0)
3287                 if (nla_put_be32(skb, NFTA_SET_FLAGS, htonl(set->flags)))
3288                         goto nla_put_failure;
3289
3290         if (nla_put_be32(skb, NFTA_SET_KEY_TYPE, htonl(set->ktype)))
3291                 goto nla_put_failure;
3292         if (nla_put_be32(skb, NFTA_SET_KEY_LEN, htonl(set->klen)))
3293                 goto nla_put_failure;
3294         if (set->flags & NFT_SET_MAP) {
3295                 if (nla_put_be32(skb, NFTA_SET_DATA_TYPE, htonl(set->dtype)))
3296                         goto nla_put_failure;
3297                 if (nla_put_be32(skb, NFTA_SET_DATA_LEN, htonl(set->dlen)))
3298                         goto nla_put_failure;
3299         }
3300         if (set->flags & NFT_SET_OBJECT &&
3301             nla_put_be32(skb, NFTA_SET_OBJ_TYPE, htonl(set->objtype)))
3302                 goto nla_put_failure;
3303
3304         if (set->timeout &&
3305             nla_put_be64(skb, NFTA_SET_TIMEOUT,
3306                          nf_jiffies64_to_msecs(set->timeout),
3307                          NFTA_SET_PAD))
3308                 goto nla_put_failure;
3309         if (set->gc_int &&
3310             nla_put_be32(skb, NFTA_SET_GC_INTERVAL, htonl(set->gc_int)))
3311                 goto nla_put_failure;
3312
3313         if (set->policy != NFT_SET_POL_PERFORMANCE) {
3314                 if (nla_put_be32(skb, NFTA_SET_POLICY, htonl(set->policy)))
3315                         goto nla_put_failure;
3316         }
3317
3318         if (nla_put(skb, NFTA_SET_USERDATA, set->udlen, set->udata))
3319                 goto nla_put_failure;
3320
3321         desc = nla_nest_start_noflag(skb, NFTA_SET_DESC);
3322         if (desc == NULL)
3323                 goto nla_put_failure;
3324         if (set->size &&
3325             nla_put_be32(skb, NFTA_SET_DESC_SIZE, htonl(set->size)))
3326                 goto nla_put_failure;
3327         nla_nest_end(skb, desc);
3328
3329         nlmsg_end(skb, nlh);
3330         return 0;
3331
3332 nla_put_failure:
3333         nlmsg_trim(skb, nlh);
3334         return -1;
3335 }
3336
3337 static void nf_tables_set_notify(const struct nft_ctx *ctx,
3338                                  const struct nft_set *set, int event,
3339                                  gfp_t gfp_flags)
3340 {
3341         struct sk_buff *skb;
3342         u32 portid = ctx->portid;
3343         int err;
3344
3345         if (!ctx->report &&
3346             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
3347                 return;
3348
3349         skb = nlmsg_new(NLMSG_GOODSIZE, gfp_flags);
3350         if (skb == NULL)
3351                 goto err;
3352
3353         err = nf_tables_fill_set(skb, ctx, set, event, 0);
3354         if (err < 0) {
3355                 kfree_skb(skb);
3356                 goto err;
3357         }
3358
3359         nfnetlink_send(skb, ctx->net, portid, NFNLGRP_NFTABLES, ctx->report,
3360                        gfp_flags);
3361         return;
3362 err:
3363         nfnetlink_set_err(ctx->net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
3364 }
3365
3366 static int nf_tables_dump_sets(struct sk_buff *skb, struct netlink_callback *cb)
3367 {
3368         const struct nft_set *set;
3369         unsigned int idx, s_idx = cb->args[0];
3370         struct nft_table *table, *cur_table = (struct nft_table *)cb->args[2];
3371         struct net *net = sock_net(skb->sk);
3372         struct nft_ctx *ctx = cb->data, ctx_set;
3373
3374         if (cb->args[1])
3375                 return skb->len;
3376
3377         rcu_read_lock();
3378         cb->seq = net->nft.base_seq;
3379
3380         list_for_each_entry_rcu(table, &net->nft.tables, list) {
3381                 if (ctx->family != NFPROTO_UNSPEC &&
3382                     ctx->family != table->family)
3383                         continue;
3384
3385                 if (ctx->table && ctx->table != table)
3386                         continue;
3387
3388                 if (cur_table) {
3389                         if (cur_table != table)
3390                                 continue;
3391
3392                         cur_table = NULL;
3393                 }
3394                 idx = 0;
3395                 list_for_each_entry_rcu(set, &table->sets, list) {
3396                         if (idx < s_idx)
3397                                 goto cont;
3398                         if (!nft_is_active(net, set))
3399                                 goto cont;
3400
3401                         ctx_set = *ctx;
3402                         ctx_set.table = table;
3403                         ctx_set.family = table->family;
3404
3405                         if (nf_tables_fill_set(skb, &ctx_set, set,
3406                                                NFT_MSG_NEWSET,
3407                                                NLM_F_MULTI) < 0) {
3408                                 cb->args[0] = idx;
3409                                 cb->args[2] = (unsigned long) table;
3410                                 goto done;
3411                         }
3412                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
3413 cont:
3414                         idx++;
3415                 }
3416                 if (s_idx)
3417                         s_idx = 0;
3418         }
3419         cb->args[1] = 1;
3420 done:
3421         rcu_read_unlock();
3422         return skb->len;
3423 }
3424
3425 static int nf_tables_dump_sets_start(struct netlink_callback *cb)
3426 {
3427         struct nft_ctx *ctx_dump = NULL;
3428
3429         ctx_dump = kmemdup(cb->data, sizeof(*ctx_dump), GFP_ATOMIC);
3430         if (ctx_dump == NULL)
3431                 return -ENOMEM;
3432
3433         cb->data = ctx_dump;
3434         return 0;
3435 }
3436
3437 static int nf_tables_dump_sets_done(struct netlink_callback *cb)
3438 {
3439         kfree(cb->data);
3440         return 0;
3441 }
3442
3443 /* called with rcu_read_lock held */
3444 static int nf_tables_getset(struct net *net, struct sock *nlsk,
3445                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3446                             const struct nlattr * const nla[],
3447                             struct netlink_ext_ack *extack)
3448 {
3449         u8 genmask = nft_genmask_cur(net);
3450         const struct nft_set *set;
3451         struct nft_ctx ctx;
3452         struct sk_buff *skb2;
3453         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3454         int err;
3455
3456         /* Verify existence before starting dump */
3457         err = nft_ctx_init_from_setattr(&ctx, net, skb, nlh, nla, extack,
3458                                         genmask);
3459         if (err < 0)
3460                 return err;
3461
3462         if (nlh->nlmsg_flags & NLM_F_DUMP) {
3463                 struct netlink_dump_control c = {
3464                         .start = nf_tables_dump_sets_start,
3465                         .dump = nf_tables_dump_sets,
3466                         .done = nf_tables_dump_sets_done,
3467                         .data = &ctx,
3468                         .module = THIS_MODULE,
3469                 };
3470
3471                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
3472         }
3473
3474         /* Only accept unspec with dump */
3475         if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
3476                 return -EAFNOSUPPORT;
3477         if (!nla[NFTA_SET_TABLE])
3478                 return -EINVAL;
3479
3480         set = nft_set_lookup(ctx.table, nla[NFTA_SET_NAME], genmask);
3481         if (IS_ERR(set))
3482                 return PTR_ERR(set);
3483
3484         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
3485         if (skb2 == NULL)
3486                 return -ENOMEM;
3487
3488         err = nf_tables_fill_set(skb2, &ctx, set, NFT_MSG_NEWSET, 0);
3489         if (err < 0)
3490                 goto err;
3491
3492         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
3493
3494 err:
3495         kfree_skb(skb2);
3496         return err;
3497 }
3498
3499 static int nf_tables_set_desc_parse(struct nft_set_desc *desc,
3500                                     const struct nlattr *nla)
3501 {
3502         struct nlattr *da[NFTA_SET_DESC_MAX + 1];
3503         int err;
3504
3505         err = nla_parse_nested_deprecated(da, NFTA_SET_DESC_MAX, nla,
3506                                           nft_set_desc_policy, NULL);
3507         if (err < 0)
3508                 return err;
3509
3510         if (da[NFTA_SET_DESC_SIZE] != NULL)
3511                 desc->size = ntohl(nla_get_be32(da[NFTA_SET_DESC_SIZE]));
3512
3513         return 0;
3514 }
3515
3516 static int nf_tables_newset(struct net *net, struct sock *nlsk,
3517                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3518                             const struct nlattr * const nla[],
3519                             struct netlink_ext_ack *extack)
3520 {
3521         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3522         u8 genmask = nft_genmask_next(net);
3523         int family = nfmsg->nfgen_family;
3524         const struct nft_set_ops *ops;
3525         struct nft_table *table;
3526         struct nft_set *set;
3527         struct nft_ctx ctx;
3528         char *name;
3529         u64 size;
3530         u64 timeout;
3531         u32 ktype, dtype, flags, policy, gc_int, objtype;
3532         struct nft_set_desc desc;
3533         unsigned char *udata;
3534         u16 udlen;
3535         int err;
3536
3537         if (nla[NFTA_SET_TABLE] == NULL ||
3538             nla[NFTA_SET_NAME] == NULL ||
3539             nla[NFTA_SET_KEY_LEN] == NULL ||
3540             nla[NFTA_SET_ID] == NULL)
3541                 return -EINVAL;
3542
3543         memset(&desc, 0, sizeof(desc));
3544
3545         ktype = NFT_DATA_VALUE;
3546         if (nla[NFTA_SET_KEY_TYPE] != NULL) {
3547                 ktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));
3548                 if ((ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)
3549                         return -EINVAL;
3550         }
3551
3552         desc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));
3553         if (desc.klen == 0 || desc.klen > NFT_DATA_VALUE_MAXLEN)
3554                 return -EINVAL;
3555
3556         flags = 0;
3557         if (nla[NFTA_SET_FLAGS] != NULL) {
3558                 flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
3559                 if (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |
3560                               NFT_SET_INTERVAL | NFT_SET_TIMEOUT |
3561                               NFT_SET_MAP | NFT_SET_EVAL |
3562                               NFT_SET_OBJECT))
3563                         return -EINVAL;
3564                 /* Only one of these operations is supported */
3565                 if ((flags & (NFT_SET_MAP | NFT_SET_EVAL | NFT_SET_OBJECT)) ==
3566                              (NFT_SET_MAP | NFT_SET_EVAL | NFT_SET_OBJECT))
3567                         return -EOPNOTSUPP;
3568         }
3569
3570         dtype = 0;
3571         if (nla[NFTA_SET_DATA_TYPE] != NULL) {
3572                 if (!(flags & NFT_SET_MAP))
3573                         return -EINVAL;
3574
3575                 dtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));
3576                 if ((dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&
3577                     dtype != NFT_DATA_VERDICT)
3578                         return -EINVAL;
3579
3580                 if (dtype != NFT_DATA_VERDICT) {
3581                         if (nla[NFTA_SET_DATA_LEN] == NULL)
3582                                 return -EINVAL;
3583                         desc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));
3584                         if (desc.dlen == 0 || desc.dlen > NFT_DATA_VALUE_MAXLEN)
3585                                 return -EINVAL;
3586                 } else
3587                         desc.dlen = sizeof(struct nft_verdict);
3588         } else if (flags & NFT_SET_MAP)
3589                 return -EINVAL;
3590
3591         if (nla[NFTA_SET_OBJ_TYPE] != NULL) {
3592                 if (!(flags & NFT_SET_OBJECT))
3593                         return -EINVAL;
3594
3595                 objtype = ntohl(nla_get_be32(nla[NFTA_SET_OBJ_TYPE]));
3596                 if (objtype == NFT_OBJECT_UNSPEC ||
3597                     objtype > NFT_OBJECT_MAX)
3598                         return -EINVAL;
3599         } else if (flags & NFT_SET_OBJECT)
3600                 return -EINVAL;
3601         else
3602                 objtype = NFT_OBJECT_UNSPEC;
3603
3604         timeout = 0;
3605         if (nla[NFTA_SET_TIMEOUT] != NULL) {
3606                 if (!(flags & NFT_SET_TIMEOUT))
3607                         return -EINVAL;
3608
3609                 err = nf_msecs_to_jiffies64(nla[NFTA_SET_TIMEOUT], &timeout);
3610                 if (err)
3611                         return err;
3612         }
3613         gc_int = 0;
3614         if (nla[NFTA_SET_GC_INTERVAL] != NULL) {
3615                 if (!(flags & NFT_SET_TIMEOUT))
3616                         return -EINVAL;
3617                 gc_int = ntohl(nla_get_be32(nla[NFTA_SET_GC_INTERVAL]));
3618         }
3619
3620         policy = NFT_SET_POL_PERFORMANCE;
3621         if (nla[NFTA_SET_POLICY] != NULL)
3622                 policy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));
3623
3624         if (nla[NFTA_SET_DESC] != NULL) {
3625                 err = nf_tables_set_desc_parse(&desc, nla[NFTA_SET_DESC]);
3626                 if (err < 0)
3627                         return err;
3628         }
3629
3630         table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family, genmask);
3631         if (IS_ERR(table)) {
3632                 NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
3633                 return PTR_ERR(table);
3634         }
3635
3636         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
3637
3638         set = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);
3639         if (IS_ERR(set)) {
3640                 if (PTR_ERR(set) != -ENOENT) {
3641                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
3642                         return PTR_ERR(set);
3643                 }
3644         } else {
3645                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
3646                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
3647                         return -EEXIST;
3648                 }
3649                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
3650                         return -EOPNOTSUPP;
3651
3652                 return 0;
3653         }
3654
3655         if (!(nlh->nlmsg_flags & NLM_F_CREATE))
3656                 return -ENOENT;
3657
3658         ops = nft_select_set_ops(&ctx, nla, &desc, policy);
3659         if (IS_ERR(ops))
3660                 return PTR_ERR(ops);
3661
3662         udlen = 0;
3663         if (nla[NFTA_SET_USERDATA])
3664                 udlen = nla_len(nla[NFTA_SET_USERDATA]);
3665
3666         size = 0;
3667         if (ops->privsize != NULL)
3668                 size = ops->privsize(nla, &desc);
3669
3670         set = kvzalloc(sizeof(*set) + size + udlen, GFP_KERNEL);
3671         if (!set) {
3672                 err = -ENOMEM;
3673                 goto err1;
3674         }
3675
3676         name = nla_strdup(nla[NFTA_SET_NAME], GFP_KERNEL);
3677         if (!name) {
3678                 err = -ENOMEM;
3679                 goto err2;
3680         }
3681
3682         err = nf_tables_set_alloc_name(&ctx, set, name);
3683         kfree(name);
3684         if (err < 0)
3685                 goto err2;
3686
3687         udata = NULL;
3688         if (udlen) {
3689                 udata = set->data + size;
3690                 nla_memcpy(udata, nla[NFTA_SET_USERDATA], udlen);
3691         }
3692
3693         INIT_LIST_HEAD(&set->bindings);
3694         set->table = table;
3695         write_pnet(&set->net, net);
3696         set->ops   = ops;
3697         set->ktype = ktype;
3698         set->klen  = desc.klen;
3699         set->dtype = dtype;
3700         set->objtype = objtype;
3701         set->dlen  = desc.dlen;
3702         set->flags = flags;
3703         set->size  = desc.size;
3704         set->policy = policy;
3705         set->udlen  = udlen;
3706         set->udata  = udata;
3707         set->timeout = timeout;
3708         set->gc_int = gc_int;
3709         set->handle = nf_tables_alloc_handle(table);
3710
3711         err = ops->init(set, &desc, nla);
3712         if (err < 0)
3713                 goto err3;
3714
3715         err = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);
3716         if (err < 0)
3717                 goto err4;
3718
3719         list_add_tail_rcu(&set->list, &table->sets);
3720         table->use++;
3721         return 0;
3722
3723 err4:
3724         ops->destroy(set);
3725 err3:
3726         kfree(set->name);
3727 err2:
3728         kvfree(set);
3729 err1:
3730         module_put(to_set_type(ops)->owner);
3731         return err;
3732 }
3733
3734 static void nft_set_destroy(struct nft_set *set)
3735 {
3736         if (WARN_ON(set->use > 0))
3737                 return;
3738
3739         set->ops->destroy(set);
3740         module_put(to_set_type(set->ops)->owner);
3741         kfree(set->name);
3742         kvfree(set);
3743 }
3744
3745 static int nf_tables_delset(struct net *net, struct sock *nlsk,
3746                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3747                             const struct nlattr * const nla[],
3748                             struct netlink_ext_ack *extack)
3749 {
3750         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3751         u8 genmask = nft_genmask_next(net);
3752         const struct nlattr *attr;
3753         struct nft_set *set;
3754         struct nft_ctx ctx;
3755         int err;
3756
3757         if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
3758                 return -EAFNOSUPPORT;
3759         if (nla[NFTA_SET_TABLE] == NULL)
3760                 return -EINVAL;
3761
3762         err = nft_ctx_init_from_setattr(&ctx, net, skb, nlh, nla, extack,
3763                                         genmask);
3764         if (err < 0)
3765                 return err;
3766
3767         if (nla[NFTA_SET_HANDLE]) {
3768                 attr = nla[NFTA_SET_HANDLE];
3769                 set = nft_set_lookup_byhandle(ctx.table, attr, genmask);
3770         } else {
3771                 attr = nla[NFTA_SET_NAME];
3772                 set = nft_set_lookup(ctx.table, attr, genmask);
3773         }
3774
3775         if (IS_ERR(set)) {
3776                 NL_SET_BAD_ATTR(extack, attr);
3777                 return PTR_ERR(set);
3778         }
3779         if (set->use ||
3780             (nlh->nlmsg_flags & NLM_F_NONREC && atomic_read(&set->nelems) > 0)) {
3781                 NL_SET_BAD_ATTR(extack, attr);
3782                 return -EBUSY;
3783         }
3784
3785         return nft_delset(&ctx, set);
3786 }
3787
3788 static int nf_tables_bind_check_setelem(const struct nft_ctx *ctx,
3789                                         struct nft_set *set,
3790                                         const struct nft_set_iter *iter,
3791                                         struct nft_set_elem *elem)
3792 {
3793         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
3794         enum nft_registers dreg;
3795
3796         dreg = nft_type_to_reg(set->dtype);
3797         return nft_validate_register_store(ctx, dreg, nft_set_ext_data(ext),
3798                                            set->dtype == NFT_DATA_VERDICT ?
3799                                            NFT_DATA_VERDICT : NFT_DATA_VALUE,
3800                                            set->dlen);
3801 }
3802
3803 int nf_tables_bind_set(const struct nft_ctx *ctx, struct nft_set *set,
3804                        struct nft_set_binding *binding)
3805 {
3806         struct nft_set_binding *i;
3807         struct nft_set_iter iter;
3808
3809         if (set->use == UINT_MAX)
3810                 return -EOVERFLOW;
3811
3812         if (!list_empty(&set->bindings) && nft_set_is_anonymous(set))
3813                 return -EBUSY;
3814
3815         if (binding->flags & NFT_SET_MAP) {
3816                 /* If the set is already bound to the same chain all
3817                  * jumps are already validated for that chain.
3818                  */
3819                 list_for_each_entry(i, &set->bindings, list) {
3820                         if (i->flags & NFT_SET_MAP &&
3821                             i->chain == binding->chain)
3822                                 goto bind;
3823                 }
3824
3825                 iter.genmask    = nft_genmask_next(ctx->net);
3826                 iter.skip       = 0;
3827                 iter.count      = 0;
3828                 iter.err        = 0;
3829                 iter.fn         = nf_tables_bind_check_setelem;
3830
3831                 set->ops->walk(ctx, set, &iter);
3832                 if (iter.err < 0)
3833                         return iter.err;
3834         }
3835 bind:
3836         binding->chain = ctx->chain;
3837         list_add_tail_rcu(&binding->list, &set->bindings);
3838         nft_set_trans_bind(ctx, set);
3839         set->use++;
3840
3841         return 0;
3842 }
3843 EXPORT_SYMBOL_GPL(nf_tables_bind_set);
3844
3845 static void nf_tables_unbind_set(const struct nft_ctx *ctx, struct nft_set *set,
3846                                  struct nft_set_binding *binding, bool event)
3847 {
3848         list_del_rcu(&binding->list);
3849
3850         if (list_empty(&set->bindings) && nft_set_is_anonymous(set)) {
3851                 list_del_rcu(&set->list);
3852                 if (event)
3853                         nf_tables_set_notify(ctx, set, NFT_MSG_DELSET,
3854                                              GFP_KERNEL);
3855         }
3856 }
3857
3858 void nf_tables_deactivate_set(const struct nft_ctx *ctx, struct nft_set *set,
3859                               struct nft_set_binding *binding,
3860                               enum nft_trans_phase phase)
3861 {
3862         switch (phase) {
3863         case NFT_TRANS_PREPARE:
3864                 set->use--;
3865                 return;
3866         case NFT_TRANS_ABORT:
3867         case NFT_TRANS_RELEASE:
3868                 set->use--;
3869                 /* fall through */
3870         default:
3871                 nf_tables_unbind_set(ctx, set, binding,
3872                                      phase == NFT_TRANS_COMMIT);
3873         }
3874 }
3875 EXPORT_SYMBOL_GPL(nf_tables_deactivate_set);
3876
3877 void nf_tables_destroy_set(const struct nft_ctx *ctx, struct nft_set *set)
3878 {
3879         if (list_empty(&set->bindings) && nft_set_is_anonymous(set))
3880                 nft_set_destroy(set);
3881 }
3882 EXPORT_SYMBOL_GPL(nf_tables_destroy_set);
3883
3884 const struct nft_set_ext_type nft_set_ext_types[] = {
3885         [NFT_SET_EXT_KEY]               = {
3886                 .align  = __alignof__(u32),
3887         },
3888         [NFT_SET_EXT_DATA]              = {
3889                 .align  = __alignof__(u32),
3890         },
3891         [NFT_SET_EXT_EXPR]              = {
3892                 .align  = __alignof__(struct nft_expr),
3893         },
3894         [NFT_SET_EXT_OBJREF]            = {
3895                 .len    = sizeof(struct nft_object *),
3896                 .align  = __alignof__(struct nft_object *),
3897         },
3898         [NFT_SET_EXT_FLAGS]             = {
3899                 .len    = sizeof(u8),
3900                 .align  = __alignof__(u8),
3901         },
3902         [NFT_SET_EXT_TIMEOUT]           = {
3903                 .len    = sizeof(u64),
3904                 .align  = __alignof__(u64),
3905         },
3906         [NFT_SET_EXT_EXPIRATION]        = {
3907                 .len    = sizeof(u64),
3908                 .align  = __alignof__(u64),
3909         },
3910         [NFT_SET_EXT_USERDATA]          = {
3911                 .len    = sizeof(struct nft_userdata),
3912                 .align  = __alignof__(struct nft_userdata),
3913         },
3914 };
3915 EXPORT_SYMBOL_GPL(nft_set_ext_types);
3916
3917 /*
3918  * Set elements
3919  */
3920
3921 static const struct nla_policy nft_set_elem_policy[NFTA_SET_ELEM_MAX + 1] = {
3922         [NFTA_SET_ELEM_KEY]             = { .type = NLA_NESTED },
3923         [NFTA_SET_ELEM_DATA]            = { .type = NLA_NESTED },
3924         [NFTA_SET_ELEM_FLAGS]           = { .type = NLA_U32 },
3925         [NFTA_SET_ELEM_TIMEOUT]         = { .type = NLA_U64 },
3926         [NFTA_SET_ELEM_EXPIRATION]      = { .type = NLA_U64 },
3927         [NFTA_SET_ELEM_USERDATA]        = { .type = NLA_BINARY,
3928                                             .len = NFT_USERDATA_MAXLEN },
3929         [NFTA_SET_ELEM_EXPR]            = { .type = NLA_NESTED },
3930         [NFTA_SET_ELEM_OBJREF]          = { .type = NLA_STRING },
3931 };
3932
3933 static const struct nla_policy nft_set_elem_list_policy[NFTA_SET_ELEM_LIST_MAX + 1] = {
3934         [NFTA_SET_ELEM_LIST_TABLE]      = { .type = NLA_STRING,
3935                                             .len = NFT_TABLE_MAXNAMELEN - 1 },
3936         [NFTA_SET_ELEM_LIST_SET]        = { .type = NLA_STRING,
3937                                             .len = NFT_SET_MAXNAMELEN - 1 },
3938         [NFTA_SET_ELEM_LIST_ELEMENTS]   = { .type = NLA_NESTED },
3939         [NFTA_SET_ELEM_LIST_SET_ID]     = { .type = NLA_U32 },
3940 };
3941
3942 static int nft_ctx_init_from_elemattr(struct nft_ctx *ctx, struct net *net,
3943                                       const struct sk_buff *skb,
3944                                       const struct nlmsghdr *nlh,
3945                                       const struct nlattr * const nla[],
3946                                       struct netlink_ext_ack *extack,
3947                                       u8 genmask)
3948 {
3949         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3950         int family = nfmsg->nfgen_family;
3951         struct nft_table *table;
3952
3953         table = nft_table_lookup(net, nla[NFTA_SET_ELEM_LIST_TABLE], family,
3954                                  genmask);
3955         if (IS_ERR(table)) {
3956                 NL_SET_BAD_ATTR(extack, nla[NFTA_SET_ELEM_LIST_TABLE]);
3957                 return PTR_ERR(table);
3958         }
3959
3960         nft_ctx_init(ctx, net, skb, nlh, family, table, NULL, nla);
3961         return 0;
3962 }
3963
3964 static int nf_tables_fill_setelem(struct sk_buff *skb,
3965                                   const struct nft_set *set,
3966                                   const struct nft_set_elem *elem)
3967 {
3968         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
3969         unsigned char *b = skb_tail_pointer(skb);
3970         struct nlattr *nest;
3971
3972         nest = nla_nest_start_noflag(skb, NFTA_LIST_ELEM);
3973         if (nest == NULL)
3974                 goto nla_put_failure;
3975
3976         if (nft_data_dump(skb, NFTA_SET_ELEM_KEY, nft_set_ext_key(ext),
3977                           NFT_DATA_VALUE, set->klen) < 0)
3978                 goto nla_put_failure;
3979
3980         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
3981             nft_data_dump(skb, NFTA_SET_ELEM_DATA, nft_set_ext_data(ext),
3982                           set->dtype == NFT_DATA_VERDICT ? NFT_DATA_VERDICT : NFT_DATA_VALUE,
3983                           set->dlen) < 0)
3984                 goto nla_put_failure;
3985
3986         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPR) &&
3987             nft_expr_dump(skb, NFTA_SET_ELEM_EXPR, nft_set_ext_expr(ext)) < 0)
3988                 goto nla_put_failure;
3989
3990         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
3991             nla_put_string(skb, NFTA_SET_ELEM_OBJREF,
3992                            (*nft_set_ext_obj(ext))->key.name) < 0)
3993                 goto nla_put_failure;
3994
3995         if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
3996             nla_put_be32(skb, NFTA_SET_ELEM_FLAGS,
3997                          htonl(*nft_set_ext_flags(ext))))
3998                 goto nla_put_failure;
3999
4000         if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT) &&
4001             nla_put_be64(skb, NFTA_SET_ELEM_TIMEOUT,
4002                          nf_jiffies64_to_msecs(*nft_set_ext_timeout(ext)),
4003                          NFTA_SET_ELEM_PAD))
4004                 goto nla_put_failure;
4005
4006         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION)) {
4007                 u64 expires, now = get_jiffies_64();
4008
4009                 expires = *nft_set_ext_expiration(ext);
4010                 if (time_before64(now, expires))
4011                         expires -= now;
4012                 else
4013                         expires = 0;
4014
4015                 if (nla_put_be64(skb, NFTA_SET_ELEM_EXPIRATION,
4016                                  nf_jiffies64_to_msecs(expires),
4017                                  NFTA_SET_ELEM_PAD))
4018                         goto nla_put_failure;
4019         }
4020
4021         if (nft_set_ext_exists(ext, NFT_SET_EXT_USERDATA)) {
4022                 struct nft_userdata *udata;
4023
4024                 udata = nft_set_ext_userdata(ext);
4025                 if (nla_put(skb, NFTA_SET_ELEM_USERDATA,
4026                             udata->len + 1, udata->data))
4027                         goto nla_put_failure;
4028         }
4029
4030         nla_nest_end(skb, nest);
4031         return 0;
4032
4033 nla_put_failure:
4034         nlmsg_trim(skb, b);
4035         return -EMSGSIZE;
4036 }
4037
4038 struct nft_set_dump_args {
4039         const struct netlink_callback   *cb;
4040         struct nft_set_iter             iter;
4041         struct sk_buff                  *skb;
4042 };
4043
4044 static int nf_tables_dump_setelem(const struct nft_ctx *ctx,
4045                                   struct nft_set *set,
4046                                   const struct nft_set_iter *iter,
4047                                   struct nft_set_elem *elem)
4048 {
4049         struct nft_set_dump_args *args;
4050
4051         args = container_of(iter, struct nft_set_dump_args, iter);
4052         return nf_tables_fill_setelem(args->skb, set, elem);
4053 }
4054
4055 struct nft_set_dump_ctx {
4056         const struct nft_set    *set;
4057         struct nft_ctx          ctx;
4058 };
4059
4060 static int nf_tables_dump_set(struct sk_buff *skb, struct netlink_callback *cb)
4061 {
4062         struct nft_set_dump_ctx *dump_ctx = cb->data;
4063         struct net *net = sock_net(skb->sk);
4064         struct nft_table *table;
4065         struct nft_set *set;
4066         struct nft_set_dump_args args;
4067         bool set_found = false;
4068         struct nfgenmsg *nfmsg;
4069         struct nlmsghdr *nlh;
4070         struct nlattr *nest;
4071         u32 portid, seq;
4072         int event;
4073
4074         rcu_read_lock();
4075         list_for_each_entry_rcu(table, &net->nft.tables, list) {
4076                 if (dump_ctx->ctx.family != NFPROTO_UNSPEC &&
4077                     dump_ctx->ctx.family != table->family)
4078                         continue;
4079
4080                 if (table != dump_ctx->ctx.table)
4081                         continue;
4082
4083                 list_for_each_entry_rcu(set, &table->sets, list) {
4084                         if (set == dump_ctx->set) {
4085                                 set_found = true;
4086                                 break;
4087                         }
4088                 }
4089                 break;
4090         }
4091
4092         if (!set_found) {
4093                 rcu_read_unlock();
4094                 return -ENOENT;
4095         }
4096
4097         event  = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWSETELEM);
4098         portid = NETLINK_CB(cb->skb).portid;
4099         seq    = cb->nlh->nlmsg_seq;
4100
4101         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
4102                         NLM_F_MULTI);
4103         if (nlh == NULL)
4104                 goto nla_put_failure;
4105
4106         nfmsg = nlmsg_data(nlh);
4107         nfmsg->nfgen_family = table->family;
4108         nfmsg->version      = NFNETLINK_V0;
4109         nfmsg->res_id       = htons(net->nft.base_seq & 0xffff);
4110
4111         if (nla_put_string(skb, NFTA_SET_ELEM_LIST_TABLE, table->name))
4112                 goto nla_put_failure;
4113         if (nla_put_string(skb, NFTA_SET_ELEM_LIST_SET, set->name))
4114                 goto nla_put_failure;
4115
4116         nest = nla_nest_start_noflag(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
4117         if (nest == NULL)
4118                 goto nla_put_failure;
4119
4120         args.cb                 = cb;
4121         args.skb                = skb;
4122         args.iter.genmask       = nft_genmask_cur(net);
4123         args.iter.skip          = cb->args[0];
4124         args.iter.count         = 0;
4125         args.iter.err           = 0;
4126         args.iter.fn            = nf_tables_dump_setelem;
4127         set->ops->walk(&dump_ctx->ctx, set, &args.iter);
4128         rcu_read_unlock();
4129
4130         nla_nest_end(skb, nest);
4131         nlmsg_end(skb, nlh);
4132
4133         if (args.iter.err && args.iter.err != -EMSGSIZE)
4134                 return args.iter.err;
4135         if (args.iter.count == cb->args[0])
4136                 return 0;
4137
4138         cb->args[0] = args.iter.count;
4139         return skb->len;
4140
4141 nla_put_failure:
4142         rcu_read_unlock();
4143         return -ENOSPC;
4144 }
4145
4146 static int nf_tables_dump_set_start(struct netlink_callback *cb)
4147 {
4148         struct nft_set_dump_ctx *dump_ctx = cb->data;
4149
4150         cb->data = kmemdup(dump_ctx, sizeof(*dump_ctx), GFP_ATOMIC);
4151
4152         return cb->data ? 0 : -ENOMEM;
4153 }
4154
4155 static int nf_tables_dump_set_done(struct netlink_callback *cb)
4156 {
4157         kfree(cb->data);
4158         return 0;
4159 }
4160
4161 static int nf_tables_fill_setelem_info(struct sk_buff *skb,
4162                                        const struct nft_ctx *ctx, u32 seq,
4163                                        u32 portid, int event, u16 flags,
4164                                        const struct nft_set *set,
4165                                        const struct nft_set_elem *elem)
4166 {
4167         struct nfgenmsg *nfmsg;
4168         struct nlmsghdr *nlh;
4169         struct nlattr *nest;
4170         int err;
4171
4172         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
4173         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
4174                         flags);
4175         if (nlh == NULL)
4176                 goto nla_put_failure;
4177
4178         nfmsg = nlmsg_data(nlh);
4179         nfmsg->nfgen_family     = ctx->family;
4180         nfmsg->version          = NFNETLINK_V0;
4181         nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
4182
4183         if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
4184                 goto nla_put_failure;
4185         if (nla_put_string(skb, NFTA_SET_NAME, set->name))
4186                 goto nla_put_failure;
4187
4188         nest = nla_nest_start_noflag(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
4189         if (nest == NULL)
4190                 goto nla_put_failure;
4191
4192         err = nf_tables_fill_setelem(skb, set, elem);
4193         if (err < 0)
4194                 goto nla_put_failure;
4195
4196         nla_nest_end(skb, nest);
4197
4198         nlmsg_end(skb, nlh);
4199         return 0;
4200
4201 nla_put_failure:
4202         nlmsg_trim(skb, nlh);
4203         return -1;
4204 }
4205
4206 static int nft_setelem_parse_flags(const struct nft_set *set,
4207                                    const struct nlattr *attr, u32 *flags)
4208 {
4209         if (attr == NULL)
4210                 return 0;
4211
4212         *flags = ntohl(nla_get_be32(attr));
4213         if (*flags & ~NFT_SET_ELEM_INTERVAL_END)
4214                 return -EINVAL;
4215         if (!(set->flags & NFT_SET_INTERVAL) &&
4216             *flags & NFT_SET_ELEM_INTERVAL_END)
4217                 return -EINVAL;
4218
4219         return 0;
4220 }
4221
4222 static int nft_get_set_elem(struct nft_ctx *ctx, struct nft_set *set,
4223                             const struct nlattr *attr)
4224 {
4225         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4226         struct nft_data_desc desc;
4227         struct nft_set_elem elem;
4228         struct sk_buff *skb;
4229         uint32_t flags = 0;
4230         void *priv;
4231         int err;
4232
4233         err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
4234                                           nft_set_elem_policy, NULL);
4235         if (err < 0)
4236                 return err;
4237
4238         if (!nla[NFTA_SET_ELEM_KEY])
4239                 return -EINVAL;
4240
4241         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4242         if (err < 0)
4243                 return err;
4244
4245         err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &desc,
4246                             nla[NFTA_SET_ELEM_KEY]);
4247         if (err < 0)
4248                 return err;
4249
4250         err = -EINVAL;
4251         if (desc.type != NFT_DATA_VALUE || desc.len != set->klen)
4252                 return err;
4253
4254         priv = set->ops->get(ctx->net, set, &elem, flags);
4255         if (IS_ERR(priv))
4256                 return PTR_ERR(priv);
4257
4258         elem.priv = priv;
4259
4260         err = -ENOMEM;
4261         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_ATOMIC);
4262         if (skb == NULL)
4263                 goto err1;
4264
4265         err = nf_tables_fill_setelem_info(skb, ctx, ctx->seq, ctx->portid,
4266                                           NFT_MSG_NEWSETELEM, 0, set, &elem);
4267         if (err < 0)
4268                 goto err2;
4269
4270         err = nfnetlink_unicast(skb, ctx->net, ctx->portid, MSG_DONTWAIT);
4271         /* This avoids a loop in nfnetlink. */
4272         if (err < 0)
4273                 goto err1;
4274
4275         return 0;
4276 err2:
4277         kfree_skb(skb);
4278 err1:
4279         /* this avoids a loop in nfnetlink. */
4280         return err == -EAGAIN ? -ENOBUFS : err;
4281 }
4282
4283 /* called with rcu_read_lock held */
4284 static int nf_tables_getsetelem(struct net *net, struct sock *nlsk,
4285                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
4286                                 const struct nlattr * const nla[],
4287                                 struct netlink_ext_ack *extack)
4288 {
4289         u8 genmask = nft_genmask_cur(net);
4290         struct nft_set *set;
4291         struct nlattr *attr;
4292         struct nft_ctx ctx;
4293         int rem, err = 0;
4294
4295         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4296                                          genmask);
4297         if (err < 0)
4298                 return err;
4299
4300         set = nft_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
4301         if (IS_ERR(set))
4302                 return PTR_ERR(set);
4303
4304         if (nlh->nlmsg_flags & NLM_F_DUMP) {
4305                 struct netlink_dump_control c = {
4306                         .start = nf_tables_dump_set_start,
4307                         .dump = nf_tables_dump_set,
4308                         .done = nf_tables_dump_set_done,
4309                         .module = THIS_MODULE,
4310                 };
4311                 struct nft_set_dump_ctx dump_ctx = {
4312                         .set = set,
4313                         .ctx = ctx,
4314                 };
4315
4316                 c.data = &dump_ctx;
4317                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
4318         }
4319
4320         if (!nla[NFTA_SET_ELEM_LIST_ELEMENTS])
4321                 return -EINVAL;
4322
4323         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4324                 err = nft_get_set_elem(&ctx, set, attr);
4325                 if (err < 0)
4326                         break;
4327         }
4328
4329         return err;
4330 }
4331
4332 static void nf_tables_setelem_notify(const struct nft_ctx *ctx,
4333                                      const struct nft_set *set,
4334                                      const struct nft_set_elem *elem,
4335                                      int event, u16 flags)
4336 {
4337         struct net *net = ctx->net;
4338         u32 portid = ctx->portid;
4339         struct sk_buff *skb;
4340         int err;
4341
4342         if (!ctx->report && !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
4343                 return;
4344
4345         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
4346         if (skb == NULL)
4347                 goto err;
4348
4349         err = nf_tables_fill_setelem_info(skb, ctx, 0, portid, event, flags,
4350                                           set, elem);
4351         if (err < 0) {
4352                 kfree_skb(skb);
4353                 goto err;
4354         }
4355
4356         nfnetlink_send(skb, net, portid, NFNLGRP_NFTABLES, ctx->report,
4357                        GFP_KERNEL);
4358         return;
4359 err:
4360         nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
4361 }
4362
4363 static struct nft_trans *nft_trans_elem_alloc(struct nft_ctx *ctx,
4364                                               int msg_type,
4365                                               struct nft_set *set)
4366 {
4367         struct nft_trans *trans;
4368
4369         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_elem));
4370         if (trans == NULL)
4371                 return NULL;
4372
4373         nft_trans_elem_set(trans) = set;
4374         return trans;
4375 }
4376
4377 void *nft_set_elem_init(const struct nft_set *set,
4378                         const struct nft_set_ext_tmpl *tmpl,
4379                         const u32 *key, const u32 *data,
4380                         u64 timeout, u64 expiration, gfp_t gfp)
4381 {
4382         struct nft_set_ext *ext;
4383         void *elem;
4384
4385         elem = kzalloc(set->ops->elemsize + tmpl->len, gfp);
4386         if (elem == NULL)
4387                 return NULL;
4388
4389         ext = nft_set_elem_ext(set, elem);
4390         nft_set_ext_init(ext, tmpl);
4391
4392         memcpy(nft_set_ext_key(ext), key, set->klen);
4393         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4394                 memcpy(nft_set_ext_data(ext), data, set->dlen);
4395         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION)) {
4396                 *nft_set_ext_expiration(ext) = get_jiffies_64() + expiration;
4397                 if (expiration == 0)
4398                         *nft_set_ext_expiration(ext) += timeout;
4399         }
4400         if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT))
4401                 *nft_set_ext_timeout(ext) = timeout;
4402
4403         return elem;
4404 }
4405
4406 void nft_set_elem_destroy(const struct nft_set *set, void *elem,
4407                           bool destroy_expr)
4408 {
4409         struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
4410         struct nft_ctx ctx = {
4411                 .net    = read_pnet(&set->net),
4412                 .family = set->table->family,
4413         };
4414
4415         nft_data_release(nft_set_ext_key(ext), NFT_DATA_VALUE);
4416         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4417                 nft_data_release(nft_set_ext_data(ext), set->dtype);
4418         if (destroy_expr && nft_set_ext_exists(ext, NFT_SET_EXT_EXPR)) {
4419                 struct nft_expr *expr = nft_set_ext_expr(ext);
4420
4421                 if (expr->ops->destroy_clone) {
4422                         expr->ops->destroy_clone(&ctx, expr);
4423                         module_put(expr->ops->type->owner);
4424                 } else {
4425                         nf_tables_expr_destroy(&ctx, expr);
4426                 }
4427         }
4428         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4429                 (*nft_set_ext_obj(ext))->use--;
4430         kfree(elem);
4431 }
4432 EXPORT_SYMBOL_GPL(nft_set_elem_destroy);
4433
4434 /* Only called from commit path, nft_set_elem_deactivate() already deals with
4435  * the refcounting from the preparation phase.
4436  */
4437 static void nf_tables_set_elem_destroy(const struct nft_ctx *ctx,
4438                                        const struct nft_set *set, void *elem)
4439 {
4440         struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
4441
4442         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPR))
4443                 nf_tables_expr_destroy(ctx, nft_set_ext_expr(ext));
4444         kfree(elem);
4445 }
4446
4447 static int nft_add_set_elem(struct nft_ctx *ctx, struct nft_set *set,
4448                             const struct nlattr *attr, u32 nlmsg_flags)
4449 {
4450         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4451         u8 genmask = nft_genmask_next(ctx->net);
4452         struct nft_data_desc d1, d2;
4453         struct nft_set_ext_tmpl tmpl;
4454         struct nft_set_ext *ext, *ext2;
4455         struct nft_set_elem elem;
4456         struct nft_set_binding *binding;
4457         struct nft_object *obj = NULL;
4458         struct nft_userdata *udata;
4459         struct nft_data data;
4460         enum nft_registers dreg;
4461         struct nft_trans *trans;
4462         u32 flags = 0;
4463         u64 timeout;
4464         u64 expiration;
4465         u8 ulen;
4466         int err;
4467
4468         err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
4469                                           nft_set_elem_policy, NULL);
4470         if (err < 0)
4471                 return err;
4472
4473         if (nla[NFTA_SET_ELEM_KEY] == NULL)
4474                 return -EINVAL;
4475
4476         nft_set_ext_prepare(&tmpl);
4477
4478         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4479         if (err < 0)
4480                 return err;
4481         if (flags != 0)
4482                 nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
4483
4484         if (set->flags & NFT_SET_MAP) {
4485                 if (nla[NFTA_SET_ELEM_DATA] == NULL &&
4486                     !(flags & NFT_SET_ELEM_INTERVAL_END))
4487                         return -EINVAL;
4488                 if (nla[NFTA_SET_ELEM_DATA] != NULL &&
4489                     flags & NFT_SET_ELEM_INTERVAL_END)
4490                         return -EINVAL;
4491         } else {
4492                 if (nla[NFTA_SET_ELEM_DATA] != NULL)
4493                         return -EINVAL;
4494         }
4495
4496         timeout = 0;
4497         if (nla[NFTA_SET_ELEM_TIMEOUT] != NULL) {
4498                 if (!(set->flags & NFT_SET_TIMEOUT))
4499                         return -EINVAL;
4500                 err = nf_msecs_to_jiffies64(nla[NFTA_SET_ELEM_TIMEOUT],
4501                                             &timeout);
4502                 if (err)
4503                         return err;
4504         } else if (set->flags & NFT_SET_TIMEOUT) {
4505                 timeout = set->timeout;
4506         }
4507
4508         expiration = 0;
4509         if (nla[NFTA_SET_ELEM_EXPIRATION] != NULL) {
4510                 if (!(set->flags & NFT_SET_TIMEOUT))
4511                         return -EINVAL;
4512                 err = nf_msecs_to_jiffies64(nla[NFTA_SET_ELEM_EXPIRATION],
4513                                             &expiration);
4514                 if (err)
4515                         return err;
4516         }
4517
4518         err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &d1,
4519                             nla[NFTA_SET_ELEM_KEY]);
4520         if (err < 0)
4521                 goto err1;
4522         err = -EINVAL;
4523         if (d1.type != NFT_DATA_VALUE || d1.len != set->klen)
4524                 goto err2;
4525
4526         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, d1.len);
4527         if (timeout > 0) {
4528                 nft_set_ext_add(&tmpl, NFT_SET_EXT_EXPIRATION);
4529                 if (timeout != set->timeout)
4530                         nft_set_ext_add(&tmpl, NFT_SET_EXT_TIMEOUT);
4531         }
4532
4533         if (nla[NFTA_SET_ELEM_OBJREF] != NULL) {
4534                 if (!(set->flags & NFT_SET_OBJECT)) {
4535                         err = -EINVAL;
4536                         goto err2;
4537                 }
4538                 obj = nft_obj_lookup(ctx->net, ctx->table,
4539                                      nla[NFTA_SET_ELEM_OBJREF],
4540                                      set->objtype, genmask);
4541                 if (IS_ERR(obj)) {
4542                         err = PTR_ERR(obj);
4543                         goto err2;
4544                 }
4545                 nft_set_ext_add(&tmpl, NFT_SET_EXT_OBJREF);
4546         }
4547
4548         if (nla[NFTA_SET_ELEM_DATA] != NULL) {
4549                 err = nft_data_init(ctx, &data, sizeof(data), &d2,
4550                                     nla[NFTA_SET_ELEM_DATA]);
4551                 if (err < 0)
4552                         goto err2;
4553
4554                 err = -EINVAL;
4555                 if (set->dtype != NFT_DATA_VERDICT && d2.len != set->dlen)
4556                         goto err3;
4557
4558                 dreg = nft_type_to_reg(set->dtype);
4559                 list_for_each_entry(binding, &set->bindings, list) {
4560                         struct nft_ctx bind_ctx = {
4561                                 .net    = ctx->net,
4562                                 .family = ctx->family,
4563                                 .table  = ctx->table,
4564                                 .chain  = (struct nft_chain *)binding->chain,
4565                         };
4566
4567                         if (!(binding->flags & NFT_SET_MAP))
4568                                 continue;
4569
4570                         err = nft_validate_register_store(&bind_ctx, dreg,
4571                                                           &data,
4572                                                           d2.type, d2.len);
4573                         if (err < 0)
4574                                 goto err3;
4575
4576                         if (d2.type == NFT_DATA_VERDICT &&
4577                             (data.verdict.code == NFT_GOTO ||
4578                              data.verdict.code == NFT_JUMP))
4579                                 nft_validate_state_update(ctx->net,
4580                                                           NFT_VALIDATE_NEED);
4581                 }
4582
4583                 nft_set_ext_add_length(&tmpl, NFT_SET_EXT_DATA, d2.len);
4584         }
4585
4586         /* The full maximum length of userdata can exceed the maximum
4587          * offset value (U8_MAX) for following extensions, therefor it
4588          * must be the last extension added.
4589          */
4590         ulen = 0;
4591         if (nla[NFTA_SET_ELEM_USERDATA] != NULL) {
4592                 ulen = nla_len(nla[NFTA_SET_ELEM_USERDATA]);
4593                 if (ulen > 0)
4594                         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_USERDATA,
4595                                                ulen);
4596         }
4597
4598         err = -ENOMEM;
4599         elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, data.data,
4600                                       timeout, expiration, GFP_KERNEL);
4601         if (elem.priv == NULL)
4602                 goto err3;
4603
4604         ext = nft_set_elem_ext(set, elem.priv);
4605         if (flags)
4606                 *nft_set_ext_flags(ext) = flags;
4607         if (ulen > 0) {
4608                 udata = nft_set_ext_userdata(ext);
4609                 udata->len = ulen - 1;
4610                 nla_memcpy(&udata->data, nla[NFTA_SET_ELEM_USERDATA], ulen);
4611         }
4612         if (obj) {
4613                 *nft_set_ext_obj(ext) = obj;
4614                 obj->use++;
4615         }
4616
4617         trans = nft_trans_elem_alloc(ctx, NFT_MSG_NEWSETELEM, set);
4618         if (trans == NULL)
4619                 goto err4;
4620
4621         ext->genmask = nft_genmask_cur(ctx->net) | NFT_SET_ELEM_BUSY_MASK;
4622         err = set->ops->insert(ctx->net, set, &elem, &ext2);
4623         if (err) {
4624                 if (err == -EEXIST) {
4625                         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) ^
4626                             nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) ||
4627                             nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) ^
4628                             nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF)) {
4629                                 err = -EBUSY;
4630                                 goto err5;
4631                         }
4632                         if ((nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
4633                              nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) &&
4634                              memcmp(nft_set_ext_data(ext),
4635                                     nft_set_ext_data(ext2), set->dlen) != 0) ||
4636                             (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
4637                              nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF) &&
4638                              *nft_set_ext_obj(ext) != *nft_set_ext_obj(ext2)))
4639                                 err = -EBUSY;
4640                         else if (!(nlmsg_flags & NLM_F_EXCL))
4641                                 err = 0;
4642                 }
4643                 goto err5;
4644         }
4645
4646         if (set->size &&
4647             !atomic_add_unless(&set->nelems, 1, set->size + set->ndeact)) {
4648                 err = -ENFILE;
4649                 goto err6;
4650         }
4651
4652         nft_trans_elem(trans) = elem;
4653         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4654         return 0;
4655
4656 err6:
4657         set->ops->remove(ctx->net, set, &elem);
4658 err5:
4659         kfree(trans);
4660 err4:
4661         if (obj)
4662                 obj->use--;
4663         kfree(elem.priv);
4664 err3:
4665         if (nla[NFTA_SET_ELEM_DATA] != NULL)
4666                 nft_data_release(&data, d2.type);
4667 err2:
4668         nft_data_release(&elem.key.val, d1.type);
4669 err1:
4670         return err;
4671 }
4672
4673 static int nf_tables_newsetelem(struct net *net, struct sock *nlsk,
4674                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
4675                                 const struct nlattr * const nla[],
4676                                 struct netlink_ext_ack *extack)
4677 {
4678         u8 genmask = nft_genmask_next(net);
4679         const struct nlattr *attr;
4680         struct nft_set *set;
4681         struct nft_ctx ctx;
4682         int rem, err;
4683
4684         if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL)
4685                 return -EINVAL;
4686
4687         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4688                                          genmask);
4689         if (err < 0)
4690                 return err;
4691
4692         set = nft_set_lookup_global(net, ctx.table, nla[NFTA_SET_ELEM_LIST_SET],
4693                                     nla[NFTA_SET_ELEM_LIST_SET_ID], genmask);
4694         if (IS_ERR(set))
4695                 return PTR_ERR(set);
4696
4697         if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
4698                 return -EBUSY;
4699
4700         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4701                 err = nft_add_set_elem(&ctx, set, attr, nlh->nlmsg_flags);
4702                 if (err < 0)
4703                         return err;
4704         }
4705
4706         if (net->nft.validate_state == NFT_VALIDATE_DO)
4707                 return nft_table_validate(net, ctx.table);
4708
4709         return 0;
4710 }
4711
4712 /**
4713  *      nft_data_hold - hold a nft_data item
4714  *
4715  *      @data: struct nft_data to release
4716  *      @type: type of data
4717  *
4718  *      Hold a nft_data item. NFT_DATA_VALUE types can be silently discarded,
4719  *      NFT_DATA_VERDICT bumps the reference to chains in case of NFT_JUMP and
4720  *      NFT_GOTO verdicts. This function must be called on active data objects
4721  *      from the second phase of the commit protocol.
4722  */
4723 void nft_data_hold(const struct nft_data *data, enum nft_data_types type)
4724 {
4725         if (type == NFT_DATA_VERDICT) {
4726                 switch (data->verdict.code) {
4727                 case NFT_JUMP:
4728                 case NFT_GOTO:
4729                         data->verdict.chain->use++;
4730                         break;
4731                 }
4732         }
4733 }
4734
4735 static void nft_set_elem_activate(const struct net *net,
4736                                   const struct nft_set *set,
4737                                   struct nft_set_elem *elem)
4738 {
4739         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
4740
4741         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4742                 nft_data_hold(nft_set_ext_data(ext), set->dtype);
4743         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4744                 (*nft_set_ext_obj(ext))->use++;
4745 }
4746
4747 static void nft_set_elem_deactivate(const struct net *net,
4748                                     const struct nft_set *set,
4749                                     struct nft_set_elem *elem)
4750 {
4751         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
4752
4753         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4754                 nft_data_release(nft_set_ext_data(ext), set->dtype);
4755         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4756                 (*nft_set_ext_obj(ext))->use--;
4757 }
4758
4759 static int nft_del_setelem(struct nft_ctx *ctx, struct nft_set *set,
4760                            const struct nlattr *attr)
4761 {
4762         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4763         struct nft_set_ext_tmpl tmpl;
4764         struct nft_data_desc desc;
4765         struct nft_set_elem elem;
4766         struct nft_set_ext *ext;
4767         struct nft_trans *trans;
4768         u32 flags = 0;
4769         void *priv;
4770         int err;
4771
4772         err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
4773                                           nft_set_elem_policy, NULL);
4774         if (err < 0)
4775                 goto err1;
4776
4777         err = -EINVAL;
4778         if (nla[NFTA_SET_ELEM_KEY] == NULL)
4779                 goto err1;
4780
4781         nft_set_ext_prepare(&tmpl);
4782
4783         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4784         if (err < 0)
4785                 return err;
4786         if (flags != 0)
4787                 nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
4788
4789         err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &desc,
4790                             nla[NFTA_SET_ELEM_KEY]);
4791         if (err < 0)
4792                 goto err1;
4793
4794         err = -EINVAL;
4795         if (desc.type != NFT_DATA_VALUE || desc.len != set->klen)
4796                 goto err2;
4797
4798         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, desc.len);
4799
4800         err = -ENOMEM;
4801         elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, NULL, 0,
4802                                       0, GFP_KERNEL);
4803         if (elem.priv == NULL)
4804                 goto err2;
4805
4806         ext = nft_set_elem_ext(set, elem.priv);
4807         if (flags)
4808                 *nft_set_ext_flags(ext) = flags;
4809
4810         trans = nft_trans_elem_alloc(ctx, NFT_MSG_DELSETELEM, set);
4811         if (trans == NULL) {
4812                 err = -ENOMEM;
4813                 goto err3;
4814         }
4815
4816         priv = set->ops->deactivate(ctx->net, set, &elem);
4817         if (priv == NULL) {
4818                 err = -ENOENT;
4819                 goto err4;
4820         }
4821         kfree(elem.priv);
4822         elem.priv = priv;
4823
4824         nft_set_elem_deactivate(ctx->net, set, &elem);
4825
4826         nft_trans_elem(trans) = elem;
4827         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4828         return 0;
4829
4830 err4:
4831         kfree(trans);
4832 err3:
4833         kfree(elem.priv);
4834 err2:
4835         nft_data_release(&elem.key.val, desc.type);
4836 err1:
4837         return err;
4838 }
4839
4840 static int nft_flush_set(const struct nft_ctx *ctx,
4841                          struct nft_set *set,
4842                          const struct nft_set_iter *iter,
4843                          struct nft_set_elem *elem)
4844 {
4845         struct nft_trans *trans;
4846         int err;
4847
4848         trans = nft_trans_alloc_gfp(ctx, NFT_MSG_DELSETELEM,
4849                                     sizeof(struct nft_trans_elem), GFP_ATOMIC);
4850         if (!trans)
4851                 return -ENOMEM;
4852
4853         if (!set->ops->flush(ctx->net, set, elem->priv)) {
4854                 err = -ENOENT;
4855                 goto err1;
4856         }
4857         set->ndeact++;
4858
4859         nft_set_elem_deactivate(ctx->net, set, elem);
4860         nft_trans_elem_set(trans) = set;
4861         nft_trans_elem(trans) = *elem;
4862         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4863
4864         return 0;
4865 err1:
4866         kfree(trans);
4867         return err;
4868 }
4869
4870 static int nf_tables_delsetelem(struct net *net, struct sock *nlsk,
4871                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
4872                                 const struct nlattr * const nla[],
4873                                 struct netlink_ext_ack *extack)
4874 {
4875         u8 genmask = nft_genmask_next(net);
4876         const struct nlattr *attr;
4877         struct nft_set *set;
4878         struct nft_ctx ctx;
4879         int rem, err = 0;
4880
4881         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4882                                          genmask);
4883         if (err < 0)
4884                 return err;
4885
4886         set = nft_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
4887         if (IS_ERR(set))
4888                 return PTR_ERR(set);
4889         if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
4890                 return -EBUSY;
4891
4892         if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL) {
4893                 struct nft_set_iter iter = {
4894                         .genmask        = genmask,
4895                         .fn             = nft_flush_set,
4896                 };
4897                 set->ops->walk(&ctx, set, &iter);
4898
4899                 return iter.err;
4900         }
4901
4902         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4903                 err = nft_del_setelem(&ctx, set, attr);
4904                 if (err < 0)
4905                         break;
4906
4907                 set->ndeact++;
4908         }
4909         return err;
4910 }
4911
4912 void nft_set_gc_batch_release(struct rcu_head *rcu)
4913 {
4914         struct nft_set_gc_batch *gcb;
4915         unsigned int i;
4916
4917         gcb = container_of(rcu, struct nft_set_gc_batch, head.rcu);
4918         for (i = 0; i < gcb->head.cnt; i++)
4919                 nft_set_elem_destroy(gcb->head.set, gcb->elems[i], true);
4920         kfree(gcb);
4921 }
4922 EXPORT_SYMBOL_GPL(nft_set_gc_batch_release);
4923
4924 struct nft_set_gc_batch *nft_set_gc_batch_alloc(const struct nft_set *set,
4925                                                 gfp_t gfp)
4926 {
4927         struct nft_set_gc_batch *gcb;
4928
4929         gcb = kzalloc(sizeof(*gcb), gfp);
4930         if (gcb == NULL)
4931                 return gcb;
4932         gcb->head.set = set;
4933         return gcb;
4934 }
4935 EXPORT_SYMBOL_GPL(nft_set_gc_batch_alloc);
4936
4937 /*
4938  * Stateful objects
4939  */
4940
4941 /**
4942  *      nft_register_obj- register nf_tables stateful object type
4943  *      @obj: object type
4944  *
4945  *      Registers the object type for use with nf_tables. Returns zero on
4946  *      success or a negative errno code otherwise.
4947  */
4948 int nft_register_obj(struct nft_object_type *obj_type)
4949 {
4950         if (obj_type->type == NFT_OBJECT_UNSPEC)
4951                 return -EINVAL;
4952
4953         nfnl_lock(NFNL_SUBSYS_NFTABLES);
4954         list_add_rcu(&obj_type->list, &nf_tables_objects);
4955         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
4956         return 0;
4957 }
4958 EXPORT_SYMBOL_GPL(nft_register_obj);
4959
4960 /**
4961  *      nft_unregister_obj - unregister nf_tables object type
4962  *      @obj: object type
4963  *
4964  *      Unregisters the object type for use with nf_tables.
4965  */
4966 void nft_unregister_obj(struct nft_object_type *obj_type)
4967 {
4968         nfnl_lock(NFNL_SUBSYS_NFTABLES);
4969         list_del_rcu(&obj_type->list);
4970         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
4971 }
4972 EXPORT_SYMBOL_GPL(nft_unregister_obj);
4973
4974 struct nft_object *nft_obj_lookup(const struct net *net,
4975                                   const struct nft_table *table,
4976                                   const struct nlattr *nla, u32 objtype,
4977                                   u8 genmask)
4978 {
4979         struct nft_object_hash_key k = { .table = table };
4980         char search[NFT_OBJ_MAXNAMELEN];
4981         struct rhlist_head *tmp, *list;
4982         struct nft_object *obj;
4983
4984         nla_strlcpy(search, nla, sizeof(search));
4985         k.name = search;
4986
4987         WARN_ON_ONCE(!rcu_read_lock_held() &&
4988                      !lockdep_commit_lock_is_held(net));
4989
4990         rcu_read_lock();
4991         list = rhltable_lookup(&nft_objname_ht, &k, nft_objname_ht_params);
4992         if (!list)
4993                 goto out;
4994
4995         rhl_for_each_entry_rcu(obj, tmp, list, rhlhead) {
4996                 if (objtype == obj->ops->type->type &&
4997                     nft_active_genmask(obj, genmask)) {
4998                         rcu_read_unlock();
4999                         return obj;
5000                 }
5001         }
5002 out:
5003         rcu_read_unlock();
5004         return ERR_PTR(-ENOENT);
5005 }
5006 EXPORT_SYMBOL_GPL(nft_obj_lookup);
5007
5008 static struct nft_object *nft_obj_lookup_byhandle(const struct nft_table *table,
5009                                                   const struct nlattr *nla,
5010                                                   u32 objtype, u8 genmask)
5011 {
5012         struct nft_object *obj;
5013
5014         list_for_each_entry(obj, &table->objects, list) {
5015                 if (be64_to_cpu(nla_get_be64(nla)) == obj->handle &&
5016                     objtype == obj->ops->type->type &&
5017                     nft_active_genmask(obj, genmask))
5018                         return obj;
5019         }
5020         return ERR_PTR(-ENOENT);
5021 }
5022
5023 static const struct nla_policy nft_obj_policy[NFTA_OBJ_MAX + 1] = {
5024         [NFTA_OBJ_TABLE]        = { .type = NLA_STRING,
5025                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
5026         [NFTA_OBJ_NAME]         = { .type = NLA_STRING,
5027                                     .len = NFT_OBJ_MAXNAMELEN - 1 },
5028         [NFTA_OBJ_TYPE]         = { .type = NLA_U32 },
5029         [NFTA_OBJ_DATA]         = { .type = NLA_NESTED },
5030         [NFTA_OBJ_HANDLE]       = { .type = NLA_U64},
5031 };
5032
5033 static struct nft_object *nft_obj_init(const struct nft_ctx *ctx,
5034                                        const struct nft_object_type *type,
5035                                        const struct nlattr *attr)
5036 {
5037         struct nlattr **tb;
5038         const struct nft_object_ops *ops;
5039         struct nft_object *obj;
5040         int err = -ENOMEM;
5041
5042         tb = kmalloc_array(type->maxattr + 1, sizeof(*tb), GFP_KERNEL);
5043         if (!tb)
5044                 goto err1;
5045
5046         if (attr) {
5047                 err = nla_parse_nested_deprecated(tb, type->maxattr, attr,
5048                                                   type->policy, NULL);
5049                 if (err < 0)
5050                         goto err2;
5051         } else {
5052                 memset(tb, 0, sizeof(tb[0]) * (type->maxattr + 1));
5053         }
5054
5055         if (type->select_ops) {
5056                 ops = type->select_ops(ctx, (const struct nlattr * const *)tb);
5057                 if (IS_ERR(ops)) {
5058                         err = PTR_ERR(ops);
5059                         goto err2;
5060                 }
5061         } else {
5062                 ops = type->ops;
5063         }
5064
5065         err = -ENOMEM;
5066         obj = kzalloc(sizeof(*obj) + ops->size, GFP_KERNEL);
5067         if (!obj)
5068                 goto err2;
5069
5070         err = ops->init(ctx, (const struct nlattr * const *)tb, obj);
5071         if (err < 0)
5072                 goto err3;
5073
5074         obj->ops = ops;
5075
5076         kfree(tb);
5077         return obj;
5078 err3:
5079         kfree(obj);
5080 err2:
5081         kfree(tb);
5082 err1:
5083         return ERR_PTR(err);
5084 }
5085
5086 static int nft_object_dump(struct sk_buff *skb, unsigned int attr,
5087                            struct nft_object *obj, bool reset)
5088 {
5089         struct nlattr *nest;
5090
5091         nest = nla_nest_start_noflag(skb, attr);
5092         if (!nest)
5093                 goto nla_put_failure;
5094         if (obj->ops->dump(skb, obj, reset) < 0)
5095                 goto nla_put_failure;
5096         nla_nest_end(skb, nest);
5097         return 0;
5098
5099 nla_put_failure:
5100         return -1;
5101 }
5102
5103 static const struct nft_object_type *__nft_obj_type_get(u32 objtype)
5104 {
5105         const struct nft_object_type *type;
5106
5107         list_for_each_entry(type, &nf_tables_objects, list) {
5108                 if (objtype == type->type)
5109                         return type;
5110         }
5111         return NULL;
5112 }
5113
5114 static const struct nft_object_type *
5115 nft_obj_type_get(struct net *net, u32 objtype)
5116 {
5117         const struct nft_object_type *type;
5118
5119         type = __nft_obj_type_get(objtype);
5120         if (type != NULL && try_module_get(type->owner))
5121                 return type;
5122
5123         lockdep_nfnl_nft_mutex_not_held();
5124 #ifdef CONFIG_MODULES
5125         if (type == NULL) {
5126                 nft_request_module(net, "nft-obj-%u", objtype);
5127                 if (__nft_obj_type_get(objtype))
5128                         return ERR_PTR(-EAGAIN);
5129         }
5130 #endif
5131         return ERR_PTR(-ENOENT);
5132 }
5133
5134 static int nf_tables_updobj(const struct nft_ctx *ctx,
5135                             const struct nft_object_type *type,
5136                             const struct nlattr *attr,
5137                             struct nft_object *obj)
5138 {
5139         struct nft_object *newobj;
5140         struct nft_trans *trans;
5141         int err;
5142
5143         if (!obj->ops->update)
5144                 return -EOPNOTSUPP;
5145
5146         trans = nft_trans_alloc(ctx, NFT_MSG_NEWOBJ,
5147                                 sizeof(struct nft_trans_obj));
5148         if (!trans)
5149                 return -ENOMEM;
5150
5151         newobj = nft_obj_init(ctx, type, attr);
5152         if (IS_ERR(newobj)) {
5153                 err = PTR_ERR(newobj);
5154                 goto err_free_trans;
5155         }
5156
5157         nft_trans_obj(trans) = obj;
5158         nft_trans_obj_update(trans) = true;
5159         nft_trans_obj_newobj(trans) = newobj;
5160         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
5161
5162         return 0;
5163
5164 err_free_trans:
5165         kfree(trans);
5166         return err;
5167 }
5168
5169 static int nf_tables_newobj(struct net *net, struct sock *nlsk,
5170                             struct sk_buff *skb, const struct nlmsghdr *nlh,
5171                             const struct nlattr * const nla[],
5172                             struct netlink_ext_ack *extack)
5173 {
5174         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5175         const struct nft_object_type *type;
5176         u8 genmask = nft_genmask_next(net);
5177         int family = nfmsg->nfgen_family;
5178         struct nft_table *table;
5179         struct nft_object *obj;
5180         struct nft_ctx ctx;
5181         u32 objtype;
5182         int err;
5183
5184         if (!nla[NFTA_OBJ_TYPE] ||
5185             !nla[NFTA_OBJ_NAME] ||
5186             !nla[NFTA_OBJ_DATA])
5187                 return -EINVAL;
5188
5189         table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
5190         if (IS_ERR(table)) {
5191                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
5192                 return PTR_ERR(table);
5193         }
5194
5195         objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5196         obj = nft_obj_lookup(net, table, nla[NFTA_OBJ_NAME], objtype, genmask);
5197         if (IS_ERR(obj)) {
5198                 err = PTR_ERR(obj);
5199                 if (err != -ENOENT) {
5200                         NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
5201                         return err;
5202                 }
5203         } else {
5204                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
5205                         NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
5206                         return -EEXIST;
5207                 }
5208                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
5209                         return -EOPNOTSUPP;
5210
5211                 type = nft_obj_type_get(net, objtype);
5212                 nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5213
5214                 return nf_tables_updobj(&ctx, type, nla[NFTA_OBJ_DATA], obj);
5215         }
5216
5217         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5218
5219         type = nft_obj_type_get(net, objtype);
5220         if (IS_ERR(type))
5221                 return PTR_ERR(type);
5222
5223         obj = nft_obj_init(&ctx, type, nla[NFTA_OBJ_DATA]);
5224         if (IS_ERR(obj)) {
5225                 err = PTR_ERR(obj);
5226                 goto err1;
5227         }
5228         obj->key.table = table;
5229         obj->handle = nf_tables_alloc_handle(table);
5230
5231         obj->key.name = nla_strdup(nla[NFTA_OBJ_NAME], GFP_KERNEL);
5232         if (!obj->key.name) {
5233                 err = -ENOMEM;
5234                 goto err2;
5235         }
5236
5237         err = nft_trans_obj_add(&ctx, NFT_MSG_NEWOBJ, obj);
5238         if (err < 0)
5239                 goto err3;
5240
5241         err = rhltable_insert(&nft_objname_ht, &obj->rhlhead,
5242                               nft_objname_ht_params);
5243         if (err < 0)
5244                 goto err4;
5245
5246         list_add_tail_rcu(&obj->list, &table->objects);
5247         table->use++;
5248         return 0;
5249 err4:
5250         /* queued in transaction log */
5251         INIT_LIST_HEAD(&obj->list);
5252         return err;
5253 err3:
5254         kfree(obj->key.name);
5255 err2:
5256         if (obj->ops->destroy)
5257                 obj->ops->destroy(&ctx, obj);
5258         kfree(obj);
5259 err1:
5260         module_put(type->owner);
5261         return err;
5262 }
5263
5264 static int nf_tables_fill_obj_info(struct sk_buff *skb, struct net *net,
5265                                    u32 portid, u32 seq, int event, u32 flags,
5266                                    int family, const struct nft_table *table,
5267                                    struct nft_object *obj, bool reset)
5268 {
5269         struct nfgenmsg *nfmsg;
5270         struct nlmsghdr *nlh;
5271
5272         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
5273         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
5274         if (nlh == NULL)
5275                 goto nla_put_failure;
5276
5277         nfmsg = nlmsg_data(nlh);
5278         nfmsg->nfgen_family     = family;
5279         nfmsg->version          = NFNETLINK_V0;
5280         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
5281
5282         if (nla_put_string(skb, NFTA_OBJ_TABLE, table->name) ||
5283             nla_put_string(skb, NFTA_OBJ_NAME, obj->key.name) ||
5284             nla_put_be32(skb, NFTA_OBJ_TYPE, htonl(obj->ops->type->type)) ||
5285             nla_put_be32(skb, NFTA_OBJ_USE, htonl(obj->use)) ||
5286             nft_object_dump(skb, NFTA_OBJ_DATA, obj, reset) ||
5287             nla_put_be64(skb, NFTA_OBJ_HANDLE, cpu_to_be64(obj->handle),
5288                          NFTA_OBJ_PAD))
5289                 goto nla_put_failure;
5290
5291         nlmsg_end(skb, nlh);
5292         return 0;
5293
5294 nla_put_failure:
5295         nlmsg_trim(skb, nlh);
5296         return -1;
5297 }
5298
5299 struct nft_obj_filter {
5300         char            *table;
5301         u32             type;
5302 };
5303
5304 static int nf_tables_dump_obj(struct sk_buff *skb, struct netlink_callback *cb)
5305 {
5306         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
5307         const struct nft_table *table;
5308         unsigned int idx = 0, s_idx = cb->args[0];
5309         struct nft_obj_filter *filter = cb->data;
5310         struct net *net = sock_net(skb->sk);
5311         int family = nfmsg->nfgen_family;
5312         struct nft_object *obj;
5313         bool reset = false;
5314
5315         if (NFNL_MSG_TYPE(cb->nlh->nlmsg_type) == NFT_MSG_GETOBJ_RESET)
5316                 reset = true;
5317
5318         rcu_read_lock();
5319         cb->seq = net->nft.base_seq;
5320
5321         list_for_each_entry_rcu(table, &net->nft.tables, list) {
5322                 if (family != NFPROTO_UNSPEC && family != table->family)
5323                         continue;
5324
5325                 list_for_each_entry_rcu(obj, &table->objects, list) {
5326                         if (!nft_is_active(net, obj))
5327                                 goto cont;
5328                         if (idx < s_idx)
5329                                 goto cont;
5330                         if (idx > s_idx)
5331                                 memset(&cb->args[1], 0,
5332                                        sizeof(cb->args) - sizeof(cb->args[0]));
5333                         if (filter && filter->table &&
5334                             strcmp(filter->table, table->name))
5335                                 goto cont;
5336                         if (filter &&
5337                             filter->type != NFT_OBJECT_UNSPEC &&
5338                             obj->ops->type->type != filter->type)
5339                                 goto cont;
5340
5341                         if (nf_tables_fill_obj_info(skb, net, NETLINK_CB(cb->skb).portid,
5342                                                     cb->nlh->nlmsg_seq,
5343                                                     NFT_MSG_NEWOBJ,
5344                                                     NLM_F_MULTI | NLM_F_APPEND,
5345                                                     table->family, table,
5346                                                     obj, reset) < 0)
5347                                 goto done;
5348
5349                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
5350 cont:
5351                         idx++;
5352                 }
5353         }
5354 done:
5355         rcu_read_unlock();
5356
5357         cb->args[0] = idx;
5358         return skb->len;
5359 }
5360
5361 static int nf_tables_dump_obj_start(struct netlink_callback *cb)
5362 {
5363         const struct nlattr * const *nla = cb->data;
5364         struct nft_obj_filter *filter = NULL;
5365
5366         if (nla[NFTA_OBJ_TABLE] || nla[NFTA_OBJ_TYPE]) {
5367                 filter = kzalloc(sizeof(*filter), GFP_ATOMIC);
5368                 if (!filter)
5369                         return -ENOMEM;
5370
5371                 if (nla[NFTA_OBJ_TABLE]) {
5372                         filter->table = nla_strdup(nla[NFTA_OBJ_TABLE], GFP_ATOMIC);
5373                         if (!filter->table) {
5374                                 kfree(filter);
5375                                 return -ENOMEM;
5376                         }
5377                 }
5378
5379                 if (nla[NFTA_OBJ_TYPE])
5380                         filter->type = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5381         }
5382
5383         cb->data = filter;
5384         return 0;
5385 }
5386
5387 static int nf_tables_dump_obj_done(struct netlink_callback *cb)
5388 {
5389         struct nft_obj_filter *filter = cb->data;
5390
5391         if (filter) {
5392                 kfree(filter->table);
5393                 kfree(filter);
5394         }
5395
5396         return 0;
5397 }
5398
5399 /* called with rcu_read_lock held */
5400 static int nf_tables_getobj(struct net *net, struct sock *nlsk,
5401                             struct sk_buff *skb, const struct nlmsghdr *nlh,
5402                             const struct nlattr * const nla[],
5403                             struct netlink_ext_ack *extack)
5404 {
5405         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5406         u8 genmask = nft_genmask_cur(net);
5407         int family = nfmsg->nfgen_family;
5408         const struct nft_table *table;
5409         struct nft_object *obj;
5410         struct sk_buff *skb2;
5411         bool reset = false;
5412         u32 objtype;
5413         int err;
5414
5415         if (nlh->nlmsg_flags & NLM_F_DUMP) {
5416                 struct netlink_dump_control c = {
5417                         .start = nf_tables_dump_obj_start,
5418                         .dump = nf_tables_dump_obj,
5419                         .done = nf_tables_dump_obj_done,
5420                         .module = THIS_MODULE,
5421                         .data = (void *)nla,
5422                 };
5423
5424                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
5425         }
5426
5427         if (!nla[NFTA_OBJ_NAME] ||
5428             !nla[NFTA_OBJ_TYPE])
5429                 return -EINVAL;
5430
5431         table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
5432         if (IS_ERR(table)) {
5433                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
5434                 return PTR_ERR(table);
5435         }
5436
5437         objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5438         obj = nft_obj_lookup(net, table, nla[NFTA_OBJ_NAME], objtype, genmask);
5439         if (IS_ERR(obj)) {
5440                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
5441                 return PTR_ERR(obj);
5442         }
5443
5444         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
5445         if (!skb2)
5446                 return -ENOMEM;
5447
5448         if (NFNL_MSG_TYPE(nlh->nlmsg_type) == NFT_MSG_GETOBJ_RESET)
5449                 reset = true;
5450
5451         err = nf_tables_fill_obj_info(skb2, net, NETLINK_CB(skb).portid,
5452                                       nlh->nlmsg_seq, NFT_MSG_NEWOBJ, 0,
5453                                       family, table, obj, reset);
5454         if (err < 0)
5455                 goto err;
5456
5457         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
5458 err:
5459         kfree_skb(skb2);
5460         return err;
5461 }
5462
5463 static void nft_obj_destroy(const struct nft_ctx *ctx, struct nft_object *obj)
5464 {
5465         if (obj->ops->destroy)
5466                 obj->ops->destroy(ctx, obj);
5467
5468         module_put(obj->ops->type->owner);
5469         kfree(obj->key.name);
5470         kfree(obj);
5471 }
5472
5473 static int nf_tables_delobj(struct net *net, struct sock *nlsk,
5474                             struct sk_buff *skb, const struct nlmsghdr *nlh,
5475                             const struct nlattr * const nla[],
5476                             struct netlink_ext_ack *extack)
5477 {
5478         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5479         u8 genmask = nft_genmask_next(net);
5480         int family = nfmsg->nfgen_family;
5481         const struct nlattr *attr;
5482         struct nft_table *table;
5483         struct nft_object *obj;
5484         struct nft_ctx ctx;
5485         u32 objtype;
5486
5487         if (!nla[NFTA_OBJ_TYPE] ||
5488             (!nla[NFTA_OBJ_NAME] && !nla[NFTA_OBJ_HANDLE]))
5489                 return -EINVAL;
5490
5491         table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
5492         if (IS_ERR(table)) {
5493                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
5494                 return PTR_ERR(table);
5495         }
5496
5497         objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5498         if (nla[NFTA_OBJ_HANDLE]) {
5499                 attr = nla[NFTA_OBJ_HANDLE];
5500                 obj = nft_obj_lookup_byhandle(table, attr, objtype, genmask);
5501         } else {
5502                 attr = nla[NFTA_OBJ_NAME];
5503                 obj = nft_obj_lookup(net, table, attr, objtype, genmask);
5504         }
5505
5506         if (IS_ERR(obj)) {
5507                 NL_SET_BAD_ATTR(extack, attr);
5508                 return PTR_ERR(obj);
5509         }
5510         if (obj->use > 0) {
5511                 NL_SET_BAD_ATTR(extack, attr);
5512                 return -EBUSY;
5513         }
5514
5515         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5516
5517         return nft_delobj(&ctx, obj);
5518 }
5519
5520 void nft_obj_notify(struct net *net, const struct nft_table *table,
5521                     struct nft_object *obj, u32 portid, u32 seq, int event,
5522                     int family, int report, gfp_t gfp)
5523 {
5524         struct sk_buff *skb;
5525         int err;
5526
5527         if (!report &&
5528             !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
5529                 return;
5530
5531         skb = nlmsg_new(NLMSG_GOODSIZE, gfp);
5532         if (skb == NULL)
5533                 goto err;
5534
5535         err = nf_tables_fill_obj_info(skb, net, portid, seq, event, 0, family,
5536                                       table, obj, false);
5537         if (err < 0) {
5538                 kfree_skb(skb);
5539                 goto err;
5540         }
5541
5542         nfnetlink_send(skb, net, portid, NFNLGRP_NFTABLES, report, gfp);
5543         return;
5544 err:
5545         nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
5546 }
5547 EXPORT_SYMBOL_GPL(nft_obj_notify);
5548
5549 static void nf_tables_obj_notify(const struct nft_ctx *ctx,
5550                                  struct nft_object *obj, int event)
5551 {
5552         nft_obj_notify(ctx->net, ctx->table, obj, ctx->portid, ctx->seq, event,
5553                        ctx->family, ctx->report, GFP_KERNEL);
5554 }
5555
5556 /*
5557  * Flow tables
5558  */
5559 void nft_register_flowtable_type(struct nf_flowtable_type *type)
5560 {
5561         nfnl_lock(NFNL_SUBSYS_NFTABLES);
5562         list_add_tail_rcu(&type->list, &nf_tables_flowtables);
5563         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
5564 }
5565 EXPORT_SYMBOL_GPL(nft_register_flowtable_type);
5566
5567 void nft_unregister_flowtable_type(struct nf_flowtable_type *type)
5568 {
5569         nfnl_lock(NFNL_SUBSYS_NFTABLES);
5570         list_del_rcu(&type->list);
5571         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
5572 }
5573 EXPORT_SYMBOL_GPL(nft_unregister_flowtable_type);
5574
5575 static const struct nla_policy nft_flowtable_policy[NFTA_FLOWTABLE_MAX + 1] = {
5576         [NFTA_FLOWTABLE_TABLE]          = { .type = NLA_STRING,
5577                                             .len = NFT_NAME_MAXLEN - 1 },
5578         [NFTA_FLOWTABLE_NAME]           = { .type = NLA_STRING,
5579                                             .len = NFT_NAME_MAXLEN - 1 },
5580         [NFTA_FLOWTABLE_HOOK]           = { .type = NLA_NESTED },
5581         [NFTA_FLOWTABLE_HANDLE]         = { .type = NLA_U64 },
5582 };
5583
5584 struct nft_flowtable *nft_flowtable_lookup(const struct nft_table *table,
5585                                            const struct nlattr *nla, u8 genmask)
5586 {
5587         struct nft_flowtable *flowtable;
5588
5589         list_for_each_entry_rcu(flowtable, &table->flowtables, list) {
5590                 if (!nla_strcmp(nla, flowtable->name) &&
5591                     nft_active_genmask(flowtable, genmask))
5592                         return flowtable;
5593         }
5594         return ERR_PTR(-ENOENT);
5595 }
5596 EXPORT_SYMBOL_GPL(nft_flowtable_lookup);
5597
5598 static struct nft_flowtable *
5599 nft_flowtable_lookup_byhandle(const struct nft_table *table,
5600                               const struct nlattr *nla, u8 genmask)
5601 {
5602        struct nft_flowtable *flowtable;
5603
5604        list_for_each_entry(flowtable, &table->flowtables, list) {
5605                if (be64_to_cpu(nla_get_be64(nla)) == flowtable->handle &&
5606                    nft_active_genmask(flowtable, genmask))
5607                        return flowtable;
5608        }
5609        return ERR_PTR(-ENOENT);
5610 }
5611
5612 static int nf_tables_parse_devices(const struct nft_ctx *ctx,
5613                                    const struct nlattr *attr,
5614                                    struct net_device *dev_array[], int *len)
5615 {
5616         const struct nlattr *tmp;
5617         struct net_device *dev;
5618         char ifname[IFNAMSIZ];
5619         int rem, n = 0, err;
5620
5621         nla_for_each_nested(tmp, attr, rem) {
5622                 if (nla_type(tmp) != NFTA_DEVICE_NAME) {
5623                         err = -EINVAL;
5624                         goto err1;
5625                 }
5626
5627                 nla_strlcpy(ifname, tmp, IFNAMSIZ);
5628                 dev = __dev_get_by_name(ctx->net, ifname);
5629                 if (!dev) {
5630                         err = -ENOENT;
5631                         goto err1;
5632                 }
5633
5634                 dev_array[n++] = dev;
5635                 if (n == NFT_FLOWTABLE_DEVICE_MAX) {
5636                         err = -EFBIG;
5637                         goto err1;
5638                 }
5639         }
5640         if (!len)
5641                 return -EINVAL;
5642
5643         err = 0;
5644 err1:
5645         *len = n;
5646         return err;
5647 }
5648
5649 static const struct nla_policy nft_flowtable_hook_policy[NFTA_FLOWTABLE_HOOK_MAX + 1] = {
5650         [NFTA_FLOWTABLE_HOOK_NUM]       = { .type = NLA_U32 },
5651         [NFTA_FLOWTABLE_HOOK_PRIORITY]  = { .type = NLA_U32 },
5652         [NFTA_FLOWTABLE_HOOK_DEVS]      = { .type = NLA_NESTED },
5653 };
5654
5655 static int nf_tables_flowtable_parse_hook(const struct nft_ctx *ctx,
5656                                           const struct nlattr *attr,
5657                                           struct nft_flowtable *flowtable)
5658 {
5659         struct net_device *dev_array[NFT_FLOWTABLE_DEVICE_MAX];
5660         struct nlattr *tb[NFTA_FLOWTABLE_HOOK_MAX + 1];
5661         struct nf_hook_ops *ops;
5662         int hooknum, priority;
5663         int err, n = 0, i;
5664
5665         err = nla_parse_nested_deprecated(tb, NFTA_FLOWTABLE_HOOK_MAX, attr,
5666                                           nft_flowtable_hook_policy, NULL);
5667         if (err < 0)
5668                 return err;
5669
5670         if (!tb[NFTA_FLOWTABLE_HOOK_NUM] ||
5671             !tb[NFTA_FLOWTABLE_HOOK_PRIORITY] ||
5672             !tb[NFTA_FLOWTABLE_HOOK_DEVS])
5673                 return -EINVAL;
5674
5675         hooknum = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_NUM]));
5676         if (hooknum != NF_NETDEV_INGRESS)
5677                 return -EINVAL;
5678
5679         priority = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_PRIORITY]));
5680
5681         err = nf_tables_parse_devices(ctx, tb[NFTA_FLOWTABLE_HOOK_DEVS],
5682                                       dev_array, &n);
5683         if (err < 0)
5684                 return err;
5685
5686         ops = kcalloc(n, sizeof(struct nf_hook_ops), GFP_KERNEL);
5687         if (!ops)
5688                 return -ENOMEM;
5689
5690         flowtable->hooknum      = hooknum;
5691         flowtable->priority     = priority;
5692         flowtable->ops          = ops;
5693         flowtable->ops_len      = n;
5694
5695         for (i = 0; i < n; i++) {
5696                 flowtable->ops[i].pf            = NFPROTO_NETDEV;
5697                 flowtable->ops[i].hooknum       = hooknum;
5698                 flowtable->ops[i].priority      = priority;
5699                 flowtable->ops[i].priv          = &flowtable->data;
5700                 flowtable->ops[i].hook          = flowtable->data.type->hook;
5701                 flowtable->ops[i].dev           = dev_array[i];
5702         }
5703
5704         return err;
5705 }
5706
5707 static const struct nf_flowtable_type *__nft_flowtable_type_get(u8 family)
5708 {
5709         const struct nf_flowtable_type *type;
5710
5711         list_for_each_entry(type, &nf_tables_flowtables, list) {
5712                 if (family == type->family)
5713                         return type;
5714         }
5715         return NULL;
5716 }
5717
5718 static const struct nf_flowtable_type *
5719 nft_flowtable_type_get(struct net *net, u8 family)
5720 {
5721         const struct nf_flowtable_type *type;
5722
5723         type = __nft_flowtable_type_get(family);
5724         if (type != NULL && try_module_get(type->owner))
5725                 return type;
5726
5727         lockdep_nfnl_nft_mutex_not_held();
5728 #ifdef CONFIG_MODULES
5729         if (type == NULL) {
5730                 nft_request_module(net, "nf-flowtable-%u", family);
5731                 if (__nft_flowtable_type_get(family))
5732                         return ERR_PTR(-EAGAIN);
5733         }
5734 #endif
5735         return ERR_PTR(-ENOENT);
5736 }
5737
5738 static void nft_unregister_flowtable_net_hooks(struct net *net,
5739                                                struct nft_flowtable *flowtable)
5740 {
5741         int i;
5742
5743         for (i = 0; i < flowtable->ops_len; i++) {
5744                 if (!flowtable->ops[i].dev)
5745                         continue;
5746
5747                 nf_unregister_net_hook(net, &flowtable->ops[i]);
5748         }
5749 }
5750
5751 static int nf_tables_newflowtable(struct net *net, struct sock *nlsk,
5752                                   struct sk_buff *skb,
5753                                   const struct nlmsghdr *nlh,
5754                                   const struct nlattr * const nla[],
5755                                   struct netlink_ext_ack *extack)
5756 {
5757         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5758         const struct nf_flowtable_type *type;
5759         struct nft_flowtable *flowtable, *ft;
5760         u8 genmask = nft_genmask_next(net);
5761         int family = nfmsg->nfgen_family;
5762         struct nft_table *table;
5763         struct nft_ctx ctx;
5764         int err, i, k;
5765
5766         if (!nla[NFTA_FLOWTABLE_TABLE] ||
5767             !nla[NFTA_FLOWTABLE_NAME] ||
5768             !nla[NFTA_FLOWTABLE_HOOK])
5769                 return -EINVAL;
5770
5771         table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
5772                                  genmask);
5773         if (IS_ERR(table)) {
5774                 NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_TABLE]);
5775                 return PTR_ERR(table);
5776         }
5777
5778         flowtable = nft_flowtable_lookup(table, nla[NFTA_FLOWTABLE_NAME],
5779                                          genmask);
5780         if (IS_ERR(flowtable)) {
5781                 err = PTR_ERR(flowtable);
5782                 if (err != -ENOENT) {
5783                         NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
5784                         return err;
5785                 }
5786         } else {
5787                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
5788                         NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
5789                         return -EEXIST;
5790                 }
5791
5792                 return 0;
5793         }
5794
5795         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5796
5797         flowtable = kzalloc(sizeof(*flowtable), GFP_KERNEL);
5798         if (!flowtable)
5799                 return -ENOMEM;
5800
5801         flowtable->table = table;
5802         flowtable->handle = nf_tables_alloc_handle(table);
5803
5804         flowtable->name = nla_strdup(nla[NFTA_FLOWTABLE_NAME], GFP_KERNEL);
5805         if (!flowtable->name) {
5806                 err = -ENOMEM;
5807                 goto err1;
5808         }
5809
5810         type = nft_flowtable_type_get(net, family);
5811         if (IS_ERR(type)) {
5812                 err = PTR_ERR(type);
5813                 goto err2;
5814         }
5815
5816         flowtable->data.type = type;
5817         err = type->init(&flowtable->data);
5818         if (err < 0)
5819                 goto err3;
5820
5821         err = nf_tables_flowtable_parse_hook(&ctx, nla[NFTA_FLOWTABLE_HOOK],
5822                                              flowtable);
5823         if (err < 0)
5824                 goto err4;
5825
5826         for (i = 0; i < flowtable->ops_len; i++) {
5827                 if (!flowtable->ops[i].dev)
5828                         continue;
5829
5830                 list_for_each_entry(ft, &table->flowtables, list) {
5831                         for (k = 0; k < ft->ops_len; k++) {
5832                                 if (!ft->ops[k].dev)
5833                                         continue;
5834
5835                                 if (flowtable->ops[i].dev == ft->ops[k].dev &&
5836                                     flowtable->ops[i].pf == ft->ops[k].pf) {
5837                                         err = -EBUSY;
5838                                         goto err5;
5839                                 }
5840                         }
5841                 }
5842
5843                 err = nf_register_net_hook(net, &flowtable->ops[i]);
5844                 if (err < 0)
5845                         goto err5;
5846         }
5847
5848         err = nft_trans_flowtable_add(&ctx, NFT_MSG_NEWFLOWTABLE, flowtable);
5849         if (err < 0)
5850                 goto err6;
5851
5852         list_add_tail_rcu(&flowtable->list, &table->flowtables);
5853         table->use++;
5854
5855         return 0;
5856 err6:
5857         i = flowtable->ops_len;
5858 err5:
5859         for (k = i - 1; k >= 0; k--)
5860                 nf_unregister_net_hook(net, &flowtable->ops[k]);
5861
5862         kfree(flowtable->ops);
5863 err4:
5864         flowtable->data.type->free(&flowtable->data);
5865 err3:
5866         module_put(type->owner);
5867 err2:
5868         kfree(flowtable->name);
5869 err1:
5870         kfree(flowtable);
5871         return err;
5872 }
5873
5874 static int nf_tables_delflowtable(struct net *net, struct sock *nlsk,
5875                                   struct sk_buff *skb,
5876                                   const struct nlmsghdr *nlh,
5877                                   const struct nlattr * const nla[],
5878                                   struct netlink_ext_ack *extack)
5879 {
5880         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5881         u8 genmask = nft_genmask_next(net);
5882         int family = nfmsg->nfgen_family;
5883         struct nft_flowtable *flowtable;
5884         const struct nlattr *attr;
5885         struct nft_table *table;
5886         struct nft_ctx ctx;
5887
5888         if (!nla[NFTA_FLOWTABLE_TABLE] ||
5889             (!nla[NFTA_FLOWTABLE_NAME] &&
5890              !nla[NFTA_FLOWTABLE_HANDLE]))
5891                 return -EINVAL;
5892
5893         table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
5894                                  genmask);
5895         if (IS_ERR(table)) {
5896                 NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_TABLE]);
5897                 return PTR_ERR(table);
5898         }
5899
5900         if (nla[NFTA_FLOWTABLE_HANDLE]) {
5901                 attr = nla[NFTA_FLOWTABLE_HANDLE];
5902                 flowtable = nft_flowtable_lookup_byhandle(table, attr, genmask);
5903         } else {
5904                 attr = nla[NFTA_FLOWTABLE_NAME];
5905                 flowtable = nft_flowtable_lookup(table, attr, genmask);
5906         }
5907
5908         if (IS_ERR(flowtable)) {
5909                 NL_SET_BAD_ATTR(extack, attr);
5910                 return PTR_ERR(flowtable);
5911         }
5912         if (flowtable->use > 0) {
5913                 NL_SET_BAD_ATTR(extack, attr);
5914                 return -EBUSY;
5915         }
5916
5917         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5918
5919         return nft_delflowtable(&ctx, flowtable);
5920 }
5921
5922 static int nf_tables_fill_flowtable_info(struct sk_buff *skb, struct net *net,
5923                                          u32 portid, u32 seq, int event,
5924                                          u32 flags, int family,
5925                                          struct nft_flowtable *flowtable)
5926 {
5927         struct nlattr *nest, *nest_devs;
5928         struct nfgenmsg *nfmsg;
5929         struct nlmsghdr *nlh;
5930         int i;
5931
5932         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
5933         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
5934         if (nlh == NULL)
5935                 goto nla_put_failure;
5936
5937         nfmsg = nlmsg_data(nlh);
5938         nfmsg->nfgen_family     = family;
5939         nfmsg->version          = NFNETLINK_V0;
5940         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
5941
5942         if (nla_put_string(skb, NFTA_FLOWTABLE_TABLE, flowtable->table->name) ||
5943             nla_put_string(skb, NFTA_FLOWTABLE_NAME, flowtable->name) ||
5944             nla_put_be32(skb, NFTA_FLOWTABLE_USE, htonl(flowtable->use)) ||
5945             nla_put_be64(skb, NFTA_FLOWTABLE_HANDLE, cpu_to_be64(flowtable->handle),
5946                          NFTA_FLOWTABLE_PAD))
5947                 goto nla_put_failure;
5948
5949         nest = nla_nest_start_noflag(skb, NFTA_FLOWTABLE_HOOK);
5950         if (!nest)
5951                 goto nla_put_failure;
5952         if (nla_put_be32(skb, NFTA_FLOWTABLE_HOOK_NUM, htonl(flowtable->hooknum)) ||
5953             nla_put_be32(skb, NFTA_FLOWTABLE_HOOK_PRIORITY, htonl(flowtable->priority)))
5954                 goto nla_put_failure;
5955
5956         nest_devs = nla_nest_start_noflag(skb, NFTA_FLOWTABLE_HOOK_DEVS);
5957         if (!nest_devs)
5958                 goto nla_put_failure;
5959
5960         for (i = 0; i < flowtable->ops_len; i++) {
5961                 const struct net_device *dev = READ_ONCE(flowtable->ops[i].dev);
5962
5963                 if (dev &&
5964                     nla_put_string(skb, NFTA_DEVICE_NAME, dev->name))
5965                         goto nla_put_failure;
5966         }
5967         nla_nest_end(skb, nest_devs);
5968         nla_nest_end(skb, nest);
5969
5970         nlmsg_end(skb, nlh);
5971         return 0;
5972
5973 nla_put_failure:
5974         nlmsg_trim(skb, nlh);
5975         return -1;
5976 }
5977
5978 struct nft_flowtable_filter {
5979         char            *table;
5980 };
5981
5982 static int nf_tables_dump_flowtable(struct sk_buff *skb,
5983                                     struct netlink_callback *cb)
5984 {
5985         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
5986         struct nft_flowtable_filter *filter = cb->data;
5987         unsigned int idx = 0, s_idx = cb->args[0];
5988         struct net *net = sock_net(skb->sk);
5989         int family = nfmsg->nfgen_family;
5990         struct nft_flowtable *flowtable;
5991         const struct nft_table *table;
5992
5993         rcu_read_lock();
5994         cb->seq = net->nft.base_seq;
5995
5996         list_for_each_entry_rcu(table, &net->nft.tables, list) {
5997                 if (family != NFPROTO_UNSPEC && family != table->family)
5998                         continue;
5999
6000                 list_for_each_entry_rcu(flowtable, &table->flowtables, list) {
6001                         if (!nft_is_active(net, flowtable))
6002                                 goto cont;
6003                         if (idx < s_idx)
6004                                 goto cont;
6005                         if (idx > s_idx)
6006                                 memset(&cb->args[1], 0,
6007                                        sizeof(cb->args) - sizeof(cb->args[0]));
6008                         if (filter && filter->table &&
6009                             strcmp(filter->table, table->name))
6010                                 goto cont;
6011
6012                         if (nf_tables_fill_flowtable_info(skb, net, NETLINK_CB(cb->skb).portid,
6013                                                           cb->nlh->nlmsg_seq,
6014                                                           NFT_MSG_NEWFLOWTABLE,
6015                                                           NLM_F_MULTI | NLM_F_APPEND,
6016                                                           table->family, flowtable) < 0)
6017                                 goto done;
6018
6019                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
6020 cont:
6021                         idx++;
6022                 }
6023         }
6024 done:
6025         rcu_read_unlock();
6026
6027         cb->args[0] = idx;
6028         return skb->len;
6029 }
6030
6031 static int nf_tables_dump_flowtable_start(struct netlink_callback *cb)
6032 {
6033         const struct nlattr * const *nla = cb->data;
6034         struct nft_flowtable_filter *filter = NULL;
6035
6036         if (nla[NFTA_FLOWTABLE_TABLE]) {
6037                 filter = kzalloc(sizeof(*filter), GFP_ATOMIC);
6038                 if (!filter)
6039                         return -ENOMEM;
6040
6041                 filter->table = nla_strdup(nla[NFTA_FLOWTABLE_TABLE],
6042                                            GFP_ATOMIC);
6043                 if (!filter->table) {
6044                         kfree(filter);
6045                         return -ENOMEM;
6046                 }
6047         }
6048
6049         cb->data = filter;
6050         return 0;
6051 }
6052
6053 static int nf_tables_dump_flowtable_done(struct netlink_callback *cb)
6054 {
6055         struct nft_flowtable_filter *filter = cb->data;
6056
6057         if (!filter)
6058                 return 0;
6059
6060         kfree(filter->table);
6061         kfree(filter);
6062
6063         return 0;
6064 }
6065
6066 /* called with rcu_read_lock held */
6067 static int nf_tables_getflowtable(struct net *net, struct sock *nlsk,
6068                                   struct sk_buff *skb,
6069                                   const struct nlmsghdr *nlh,
6070                                   const struct nlattr * const nla[],
6071                                   struct netlink_ext_ack *extack)
6072 {
6073         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
6074         u8 genmask = nft_genmask_cur(net);
6075         int family = nfmsg->nfgen_family;
6076         struct nft_flowtable *flowtable;
6077         const struct nft_table *table;
6078         struct sk_buff *skb2;
6079         int err;
6080
6081         if (nlh->nlmsg_flags & NLM_F_DUMP) {
6082                 struct netlink_dump_control c = {
6083                         .start = nf_tables_dump_flowtable_start,
6084                         .dump = nf_tables_dump_flowtable,
6085                         .done = nf_tables_dump_flowtable_done,
6086                         .module = THIS_MODULE,
6087                         .data = (void *)nla,
6088                 };
6089
6090                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
6091         }
6092
6093         if (!nla[NFTA_FLOWTABLE_NAME])
6094                 return -EINVAL;
6095
6096         table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
6097                                  genmask);
6098         if (IS_ERR(table))
6099                 return PTR_ERR(table);
6100
6101         flowtable = nft_flowtable_lookup(table, nla[NFTA_FLOWTABLE_NAME],
6102                                          genmask);
6103         if (IS_ERR(flowtable))
6104                 return PTR_ERR(flowtable);
6105
6106         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
6107         if (!skb2)
6108                 return -ENOMEM;
6109
6110         err = nf_tables_fill_flowtable_info(skb2, net, NETLINK_CB(skb).portid,
6111                                             nlh->nlmsg_seq,
6112                                             NFT_MSG_NEWFLOWTABLE, 0, family,
6113                                             flowtable);
6114         if (err < 0)
6115                 goto err;
6116
6117         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
6118 err:
6119         kfree_skb(skb2);
6120         return err;
6121 }
6122
6123 static void nf_tables_flowtable_notify(struct nft_ctx *ctx,
6124                                        struct nft_flowtable *flowtable,
6125                                        int event)
6126 {
6127         struct sk_buff *skb;
6128         int err;
6129
6130         if (ctx->report &&
6131             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
6132                 return;
6133
6134         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
6135         if (skb == NULL)
6136                 goto err;
6137
6138         err = nf_tables_fill_flowtable_info(skb, ctx->net, ctx->portid,
6139                                             ctx->seq, event, 0,
6140                                             ctx->family, flowtable);
6141         if (err < 0) {
6142                 kfree_skb(skb);
6143                 goto err;
6144         }
6145
6146         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
6147                        ctx->report, GFP_KERNEL);
6148         return;
6149 err:
6150         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
6151 }
6152
6153 static void nf_tables_flowtable_destroy(struct nft_flowtable *flowtable)
6154 {
6155         kfree(flowtable->ops);
6156         kfree(flowtable->name);
6157         flowtable->data.type->free(&flowtable->data);
6158         module_put(flowtable->data.type->owner);
6159         kfree(flowtable);
6160 }
6161
6162 static int nf_tables_fill_gen_info(struct sk_buff *skb, struct net *net,
6163                                    u32 portid, u32 seq)
6164 {
6165         struct nlmsghdr *nlh;
6166         struct nfgenmsg *nfmsg;
6167         char buf[TASK_COMM_LEN];
6168         int event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWGEN);
6169
6170         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), 0);
6171         if (nlh == NULL)
6172                 goto nla_put_failure;
6173
6174         nfmsg = nlmsg_data(nlh);
6175         nfmsg->nfgen_family     = AF_UNSPEC;
6176         nfmsg->version          = NFNETLINK_V0;
6177         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
6178
6179         if (nla_put_be32(skb, NFTA_GEN_ID, htonl(net->nft.base_seq)) ||
6180             nla_put_be32(skb, NFTA_GEN_PROC_PID, htonl(task_pid_nr(current))) ||
6181             nla_put_string(skb, NFTA_GEN_PROC_NAME, get_task_comm(buf, current)))
6182                 goto nla_put_failure;
6183
6184         nlmsg_end(skb, nlh);
6185         return 0;
6186
6187 nla_put_failure:
6188         nlmsg_trim(skb, nlh);
6189         return -EMSGSIZE;
6190 }
6191
6192 static void nft_flowtable_event(unsigned long event, struct net_device *dev,
6193                                 struct nft_flowtable *flowtable)
6194 {
6195         int i;
6196
6197         for (i = 0; i < flowtable->ops_len; i++) {
6198                 if (flowtable->ops[i].dev != dev)
6199                         continue;
6200
6201                 nf_unregister_net_hook(dev_net(dev), &flowtable->ops[i]);
6202                 flowtable->ops[i].dev = NULL;
6203                 break;
6204         }
6205 }
6206
6207 static int nf_tables_flowtable_event(struct notifier_block *this,
6208                                      unsigned long event, void *ptr)
6209 {
6210         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
6211         struct nft_flowtable *flowtable;
6212         struct nft_table *table;
6213         struct net *net;
6214
6215         if (event != NETDEV_UNREGISTER)
6216                 return 0;
6217
6218         net = dev_net(dev);
6219         mutex_lock(&net->nft.commit_mutex);
6220         list_for_each_entry(table, &net->nft.tables, list) {
6221                 list_for_each_entry(flowtable, &table->flowtables, list) {
6222                         nft_flowtable_event(event, dev, flowtable);
6223                 }
6224         }
6225         mutex_unlock(&net->nft.commit_mutex);
6226
6227         return NOTIFY_DONE;
6228 }
6229
6230 static struct notifier_block nf_tables_flowtable_notifier = {
6231         .notifier_call  = nf_tables_flowtable_event,
6232 };
6233
6234 static void nf_tables_gen_notify(struct net *net, struct sk_buff *skb,
6235                                  int event)
6236 {
6237         struct nlmsghdr *nlh = nlmsg_hdr(skb);
6238         struct sk_buff *skb2;
6239         int err;
6240
6241         if (nlmsg_report(nlh) &&
6242             !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
6243                 return;
6244
6245         skb2 = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
6246         if (skb2 == NULL)
6247                 goto err;
6248
6249         err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
6250                                       nlh->nlmsg_seq);
6251         if (err < 0) {
6252                 kfree_skb(skb2);
6253                 goto err;
6254         }
6255
6256         nfnetlink_send(skb2, net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
6257                        nlmsg_report(nlh), GFP_KERNEL);
6258         return;
6259 err:
6260         nfnetlink_set_err(net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
6261                           -ENOBUFS);
6262 }
6263
6264 static int nf_tables_getgen(struct net *net, struct sock *nlsk,
6265                             struct sk_buff *skb, const struct nlmsghdr *nlh,
6266                             const struct nlattr * const nla[],
6267                             struct netlink_ext_ack *extack)
6268 {
6269         struct sk_buff *skb2;
6270         int err;
6271
6272         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
6273         if (skb2 == NULL)
6274                 return -ENOMEM;
6275
6276         err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
6277                                       nlh->nlmsg_seq);
6278         if (err < 0)
6279                 goto err;
6280
6281         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
6282 err:
6283         kfree_skb(skb2);
6284         return err;
6285 }
6286
6287 static const struct nfnl_callback nf_tables_cb[NFT_MSG_MAX] = {
6288         [NFT_MSG_NEWTABLE] = {
6289                 .call_batch     = nf_tables_newtable,
6290                 .attr_count     = NFTA_TABLE_MAX,
6291                 .policy         = nft_table_policy,
6292         },
6293         [NFT_MSG_GETTABLE] = {
6294                 .call_rcu       = nf_tables_gettable,
6295                 .attr_count     = NFTA_TABLE_MAX,
6296                 .policy         = nft_table_policy,
6297         },
6298         [NFT_MSG_DELTABLE] = {
6299                 .call_batch     = nf_tables_deltable,
6300                 .attr_count     = NFTA_TABLE_MAX,
6301                 .policy         = nft_table_policy,
6302         },
6303         [NFT_MSG_NEWCHAIN] = {
6304                 .call_batch     = nf_tables_newchain,
6305                 .attr_count     = NFTA_CHAIN_MAX,
6306                 .policy         = nft_chain_policy,
6307         },
6308         [NFT_MSG_GETCHAIN] = {
6309                 .call_rcu       = nf_tables_getchain,
6310                 .attr_count     = NFTA_CHAIN_MAX,
6311                 .policy         = nft_chain_policy,
6312         },
6313         [NFT_MSG_DELCHAIN] = {
6314                 .call_batch     = nf_tables_delchain,
6315                 .attr_count     = NFTA_CHAIN_MAX,
6316                 .policy         = nft_chain_policy,
6317         },
6318         [NFT_MSG_NEWRULE] = {
6319                 .call_batch     = nf_tables_newrule,
6320                 .attr_count     = NFTA_RULE_MAX,
6321                 .policy         = nft_rule_policy,
6322         },
6323         [NFT_MSG_GETRULE] = {
6324                 .call_rcu       = nf_tables_getrule,
6325                 .attr_count     = NFTA_RULE_MAX,
6326                 .policy         = nft_rule_policy,
6327         },
6328         [NFT_MSG_DELRULE] = {
6329                 .call_batch     = nf_tables_delrule,
6330                 .attr_count     = NFTA_RULE_MAX,
6331                 .policy         = nft_rule_policy,
6332         },
6333         [NFT_MSG_NEWSET] = {
6334                 .call_batch     = nf_tables_newset,
6335                 .attr_count     = NFTA_SET_MAX,
6336                 .policy         = nft_set_policy,
6337         },
6338         [NFT_MSG_GETSET] = {
6339                 .call_rcu       = nf_tables_getset,
6340                 .attr_count     = NFTA_SET_MAX,
6341                 .policy         = nft_set_policy,
6342         },
6343         [NFT_MSG_DELSET] = {
6344                 .call_batch     = nf_tables_delset,
6345                 .attr_count     = NFTA_SET_MAX,
6346                 .policy         = nft_set_policy,
6347         },
6348         [NFT_MSG_NEWSETELEM] = {
6349                 .call_batch     = nf_tables_newsetelem,
6350                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6351                 .policy         = nft_set_elem_list_policy,
6352         },
6353         [NFT_MSG_GETSETELEM] = {
6354                 .call_rcu       = nf_tables_getsetelem,
6355                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6356                 .policy         = nft_set_elem_list_policy,
6357         },
6358         [NFT_MSG_DELSETELEM] = {
6359                 .call_batch     = nf_tables_delsetelem,
6360                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6361                 .policy         = nft_set_elem_list_policy,
6362         },
6363         [NFT_MSG_GETGEN] = {
6364                 .call_rcu       = nf_tables_getgen,
6365         },
6366         [NFT_MSG_NEWOBJ] = {
6367                 .call_batch     = nf_tables_newobj,
6368                 .attr_count     = NFTA_OBJ_MAX,
6369                 .policy         = nft_obj_policy,
6370         },
6371         [NFT_MSG_GETOBJ] = {
6372                 .call_rcu       = nf_tables_getobj,
6373                 .attr_count     = NFTA_OBJ_MAX,
6374                 .policy         = nft_obj_policy,
6375         },
6376         [NFT_MSG_DELOBJ] = {
6377                 .call_batch     = nf_tables_delobj,
6378                 .attr_count     = NFTA_OBJ_MAX,
6379                 .policy         = nft_obj_policy,
6380         },
6381         [NFT_MSG_GETOBJ_RESET] = {
6382                 .call_rcu       = nf_tables_getobj,
6383                 .attr_count     = NFTA_OBJ_MAX,
6384                 .policy         = nft_obj_policy,
6385         },
6386         [NFT_MSG_NEWFLOWTABLE] = {
6387                 .call_batch     = nf_tables_newflowtable,
6388                 .attr_count     = NFTA_FLOWTABLE_MAX,
6389                 .policy         = nft_flowtable_policy,
6390         },
6391         [NFT_MSG_GETFLOWTABLE] = {
6392                 .call_rcu       = nf_tables_getflowtable,
6393                 .attr_count     = NFTA_FLOWTABLE_MAX,
6394                 .policy         = nft_flowtable_policy,
6395         },
6396         [NFT_MSG_DELFLOWTABLE] = {
6397                 .call_batch     = nf_tables_delflowtable,
6398                 .attr_count     = NFTA_FLOWTABLE_MAX,
6399                 .policy         = nft_flowtable_policy,
6400         },
6401 };
6402
6403 static int nf_tables_validate(struct net *net)
6404 {
6405         struct nft_table *table;
6406
6407         switch (net->nft.validate_state) {
6408         case NFT_VALIDATE_SKIP:
6409                 break;
6410         case NFT_VALIDATE_NEED:
6411                 nft_validate_state_update(net, NFT_VALIDATE_DO);
6412                 /* fall through */
6413         case NFT_VALIDATE_DO:
6414                 list_for_each_entry(table, &net->nft.tables, list) {
6415                         if (nft_table_validate(net, table) < 0)
6416                                 return -EAGAIN;
6417                 }
6418                 break;
6419         }
6420
6421         return 0;
6422 }
6423
6424 /* a drop policy has to be deferred until all rules have been activated,
6425  * otherwise a large ruleset that contains a drop-policy base chain will
6426  * cause all packets to get dropped until the full transaction has been
6427  * processed.
6428  *
6429  * We defer the drop policy until the transaction has been finalized.
6430  */
6431 static void nft_chain_commit_drop_policy(struct nft_trans *trans)
6432 {
6433         struct nft_base_chain *basechain;
6434
6435         if (nft_trans_chain_policy(trans) != NF_DROP)
6436                 return;
6437
6438         if (!nft_is_base_chain(trans->ctx.chain))
6439                 return;
6440
6441         basechain = nft_base_chain(trans->ctx.chain);
6442         basechain->policy = NF_DROP;
6443 }
6444
6445 static void nft_chain_commit_update(struct nft_trans *trans)
6446 {
6447         struct nft_base_chain *basechain;
6448
6449         if (nft_trans_chain_name(trans)) {
6450                 rhltable_remove(&trans->ctx.table->chains_ht,
6451                                 &trans->ctx.chain->rhlhead,
6452                                 nft_chain_ht_params);
6453                 swap(trans->ctx.chain->name, nft_trans_chain_name(trans));
6454                 rhltable_insert_key(&trans->ctx.table->chains_ht,
6455                                     trans->ctx.chain->name,
6456                                     &trans->ctx.chain->rhlhead,
6457                                     nft_chain_ht_params);
6458         }
6459
6460         if (!nft_is_base_chain(trans->ctx.chain))
6461                 return;
6462
6463         nft_chain_stats_replace(trans);
6464
6465         basechain = nft_base_chain(trans->ctx.chain);
6466
6467         switch (nft_trans_chain_policy(trans)) {
6468         case NF_DROP:
6469         case NF_ACCEPT:
6470                 basechain->policy = nft_trans_chain_policy(trans);
6471                 break;
6472         }
6473 }
6474
6475 static void nft_obj_commit_update(struct nft_trans *trans)
6476 {
6477         struct nft_object *newobj;
6478         struct nft_object *obj;
6479
6480         obj = nft_trans_obj(trans);
6481         newobj = nft_trans_obj_newobj(trans);
6482
6483         obj->ops->update(obj, newobj);
6484
6485         kfree(newobj);
6486 }
6487
6488 static void nft_commit_release(struct nft_trans *trans)
6489 {
6490         switch (trans->msg_type) {
6491         case NFT_MSG_DELTABLE:
6492                 nf_tables_table_destroy(&trans->ctx);
6493                 break;
6494         case NFT_MSG_NEWCHAIN:
6495                 free_percpu(nft_trans_chain_stats(trans));
6496                 kfree(nft_trans_chain_name(trans));
6497                 break;
6498         case NFT_MSG_DELCHAIN:
6499                 nf_tables_chain_destroy(&trans->ctx);
6500                 break;
6501         case NFT_MSG_DELRULE:
6502                 nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
6503                 break;
6504         case NFT_MSG_DELSET:
6505                 nft_set_destroy(nft_trans_set(trans));
6506                 break;
6507         case NFT_MSG_DELSETELEM:
6508                 nf_tables_set_elem_destroy(&trans->ctx,
6509                                            nft_trans_elem_set(trans),
6510                                            nft_trans_elem(trans).priv);
6511                 break;
6512         case NFT_MSG_DELOBJ:
6513                 nft_obj_destroy(&trans->ctx, nft_trans_obj(trans));
6514                 break;
6515         case NFT_MSG_DELFLOWTABLE:
6516                 nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
6517                 break;
6518         }
6519
6520         if (trans->put_net)
6521                 put_net(trans->ctx.net);
6522
6523         kfree(trans);
6524 }
6525
6526 static void nf_tables_trans_destroy_work(struct work_struct *w)
6527 {
6528         struct nft_trans *trans, *next;
6529         LIST_HEAD(head);
6530
6531         spin_lock(&nf_tables_destroy_list_lock);
6532         list_splice_init(&nf_tables_destroy_list, &head);
6533         spin_unlock(&nf_tables_destroy_list_lock);
6534
6535         if (list_empty(&head))
6536                 return;
6537
6538         synchronize_rcu();
6539
6540         list_for_each_entry_safe(trans, next, &head, list) {
6541                 list_del(&trans->list);
6542                 nft_commit_release(trans);
6543         }
6544 }
6545
6546 static int nf_tables_commit_chain_prepare(struct net *net, struct nft_chain *chain)
6547 {
6548         struct nft_rule *rule;
6549         unsigned int alloc = 0;
6550         int i;
6551
6552         /* already handled or inactive chain? */
6553         if (chain->rules_next || !nft_is_active_next(net, chain))
6554                 return 0;
6555
6556         rule = list_entry(&chain->rules, struct nft_rule, list);
6557         i = 0;
6558
6559         list_for_each_entry_continue(rule, &chain->rules, list) {
6560                 if (nft_is_active_next(net, rule))
6561                         alloc++;
6562         }
6563
6564         chain->rules_next = nf_tables_chain_alloc_rules(chain, alloc);
6565         if (!chain->rules_next)
6566                 return -ENOMEM;
6567
6568         list_for_each_entry_continue(rule, &chain->rules, list) {
6569                 if (nft_is_active_next(net, rule))
6570                         chain->rules_next[i++] = rule;
6571         }
6572
6573         chain->rules_next[i] = NULL;
6574         return 0;
6575 }
6576
6577 static void nf_tables_commit_chain_prepare_cancel(struct net *net)
6578 {
6579         struct nft_trans *trans, *next;
6580
6581         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6582                 struct nft_chain *chain = trans->ctx.chain;
6583
6584                 if (trans->msg_type == NFT_MSG_NEWRULE ||
6585                     trans->msg_type == NFT_MSG_DELRULE) {
6586                         kvfree(chain->rules_next);
6587                         chain->rules_next = NULL;
6588                 }
6589         }
6590 }
6591
6592 static void __nf_tables_commit_chain_free_rules_old(struct rcu_head *h)
6593 {
6594         struct nft_rules_old *o = container_of(h, struct nft_rules_old, h);
6595
6596         kvfree(o->start);
6597 }
6598
6599 static void nf_tables_commit_chain_free_rules_old(struct nft_rule **rules)
6600 {
6601         struct nft_rule **r = rules;
6602         struct nft_rules_old *old;
6603
6604         while (*r)
6605                 r++;
6606
6607         r++;    /* rcu_head is after end marker */
6608         old = (void *) r;
6609         old->start = rules;
6610
6611         call_rcu(&old->h, __nf_tables_commit_chain_free_rules_old);
6612 }
6613
6614 static void nf_tables_commit_chain(struct net *net, struct nft_chain *chain)
6615 {
6616         struct nft_rule **g0, **g1;
6617         bool next_genbit;
6618
6619         next_genbit = nft_gencursor_next(net);
6620
6621         g0 = rcu_dereference_protected(chain->rules_gen_0,
6622                                        lockdep_commit_lock_is_held(net));
6623         g1 = rcu_dereference_protected(chain->rules_gen_1,
6624                                        lockdep_commit_lock_is_held(net));
6625
6626         /* No changes to this chain? */
6627         if (chain->rules_next == NULL) {
6628                 /* chain had no change in last or next generation */
6629                 if (g0 == g1)
6630                         return;
6631                 /*
6632                  * chain had no change in this generation; make sure next
6633                  * one uses same rules as current generation.
6634                  */
6635                 if (next_genbit) {
6636                         rcu_assign_pointer(chain->rules_gen_1, g0);
6637                         nf_tables_commit_chain_free_rules_old(g1);
6638                 } else {
6639                         rcu_assign_pointer(chain->rules_gen_0, g1);
6640                         nf_tables_commit_chain_free_rules_old(g0);
6641                 }
6642
6643                 return;
6644         }
6645
6646         if (next_genbit)
6647                 rcu_assign_pointer(chain->rules_gen_1, chain->rules_next);
6648         else
6649                 rcu_assign_pointer(chain->rules_gen_0, chain->rules_next);
6650
6651         chain->rules_next = NULL;
6652
6653         if (g0 == g1)
6654                 return;
6655
6656         if (next_genbit)
6657                 nf_tables_commit_chain_free_rules_old(g1);
6658         else
6659                 nf_tables_commit_chain_free_rules_old(g0);
6660 }
6661
6662 static void nft_obj_del(struct nft_object *obj)
6663 {
6664         rhltable_remove(&nft_objname_ht, &obj->rhlhead, nft_objname_ht_params);
6665         list_del_rcu(&obj->list);
6666 }
6667
6668 static void nft_chain_del(struct nft_chain *chain)
6669 {
6670         struct nft_table *table = chain->table;
6671
6672         WARN_ON_ONCE(rhltable_remove(&table->chains_ht, &chain->rhlhead,
6673                                      nft_chain_ht_params));
6674         list_del_rcu(&chain->list);
6675 }
6676
6677 static void nf_tables_commit_release(struct net *net)
6678 {
6679         struct nft_trans *trans;
6680
6681         /* all side effects have to be made visible.
6682          * For example, if a chain named 'foo' has been deleted, a
6683          * new transaction must not find it anymore.
6684          *
6685          * Memory reclaim happens asynchronously from work queue
6686          * to prevent expensive synchronize_rcu() in commit phase.
6687          */
6688         if (list_empty(&net->nft.commit_list)) {
6689                 mutex_unlock(&net->nft.commit_mutex);
6690                 return;
6691         }
6692
6693         trans = list_last_entry(&net->nft.commit_list,
6694                                 struct nft_trans, list);
6695         get_net(trans->ctx.net);
6696         WARN_ON_ONCE(trans->put_net);
6697
6698         trans->put_net = true;
6699         spin_lock(&nf_tables_destroy_list_lock);
6700         list_splice_tail_init(&net->nft.commit_list, &nf_tables_destroy_list);
6701         spin_unlock(&nf_tables_destroy_list_lock);
6702
6703         mutex_unlock(&net->nft.commit_mutex);
6704
6705         schedule_work(&trans_destroy_work);
6706 }
6707
6708 static int nf_tables_commit(struct net *net, struct sk_buff *skb)
6709 {
6710         struct nft_trans *trans, *next;
6711         struct nft_trans_elem *te;
6712         struct nft_chain *chain;
6713         struct nft_table *table;
6714         int err;
6715
6716         if (list_empty(&net->nft.commit_list)) {
6717                 mutex_unlock(&net->nft.commit_mutex);
6718                 return 0;
6719         }
6720
6721         /* 0. Validate ruleset, otherwise roll back for error reporting. */
6722         if (nf_tables_validate(net) < 0)
6723                 return -EAGAIN;
6724
6725         err = nft_flow_rule_offload_commit(net);
6726         if (err < 0)
6727                 return err;
6728
6729         /* 1.  Allocate space for next generation rules_gen_X[] */
6730         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6731                 int ret;
6732
6733                 if (trans->msg_type == NFT_MSG_NEWRULE ||
6734                     trans->msg_type == NFT_MSG_DELRULE) {
6735                         chain = trans->ctx.chain;
6736
6737                         ret = nf_tables_commit_chain_prepare(net, chain);
6738                         if (ret < 0) {
6739                                 nf_tables_commit_chain_prepare_cancel(net);
6740                                 return ret;
6741                         }
6742                 }
6743         }
6744
6745         /* step 2.  Make rules_gen_X visible to packet path */
6746         list_for_each_entry(table, &net->nft.tables, list) {
6747                 list_for_each_entry(chain, &table->chains, list)
6748                         nf_tables_commit_chain(net, chain);
6749         }
6750
6751         /*
6752          * Bump generation counter, invalidate any dump in progress.
6753          * Cannot fail after this point.
6754          */
6755         while (++net->nft.base_seq == 0);
6756
6757         /* step 3. Start new generation, rules_gen_X now in use. */
6758         net->nft.gencursor = nft_gencursor_next(net);
6759
6760         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6761                 switch (trans->msg_type) {
6762                 case NFT_MSG_NEWTABLE:
6763                         if (nft_trans_table_update(trans)) {
6764                                 if (!nft_trans_table_enable(trans)) {
6765                                         nf_tables_table_disable(net,
6766                                                                 trans->ctx.table);
6767                                         trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
6768                                 }
6769                         } else {
6770                                 nft_clear(net, trans->ctx.table);
6771                         }
6772                         nf_tables_table_notify(&trans->ctx, NFT_MSG_NEWTABLE);
6773                         nft_trans_destroy(trans);
6774                         break;
6775                 case NFT_MSG_DELTABLE:
6776                         list_del_rcu(&trans->ctx.table->list);
6777                         nf_tables_table_notify(&trans->ctx, NFT_MSG_DELTABLE);
6778                         break;
6779                 case NFT_MSG_NEWCHAIN:
6780                         if (nft_trans_chain_update(trans)) {
6781                                 nft_chain_commit_update(trans);
6782                                 nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN);
6783                                 /* trans destroyed after rcu grace period */
6784                         } else {
6785                                 nft_chain_commit_drop_policy(trans);
6786                                 nft_clear(net, trans->ctx.chain);
6787                                 nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN);
6788                                 nft_trans_destroy(trans);
6789                         }
6790                         break;
6791                 case NFT_MSG_DELCHAIN:
6792                         nft_chain_del(trans->ctx.chain);
6793                         nf_tables_chain_notify(&trans->ctx, NFT_MSG_DELCHAIN);
6794                         nf_tables_unregister_hook(trans->ctx.net,
6795                                                   trans->ctx.table,
6796                                                   trans->ctx.chain);
6797                         break;
6798                 case NFT_MSG_NEWRULE:
6799                         nft_clear(trans->ctx.net, nft_trans_rule(trans));
6800                         nf_tables_rule_notify(&trans->ctx,
6801                                               nft_trans_rule(trans),
6802                                               NFT_MSG_NEWRULE);
6803                         nft_trans_destroy(trans);
6804                         break;
6805                 case NFT_MSG_DELRULE:
6806                         list_del_rcu(&nft_trans_rule(trans)->list);
6807                         nf_tables_rule_notify(&trans->ctx,
6808                                               nft_trans_rule(trans),
6809                                               NFT_MSG_DELRULE);
6810                         nft_rule_expr_deactivate(&trans->ctx,
6811                                                  nft_trans_rule(trans),
6812                                                  NFT_TRANS_COMMIT);
6813                         break;
6814                 case NFT_MSG_NEWSET:
6815                         nft_clear(net, nft_trans_set(trans));
6816                         /* This avoids hitting -EBUSY when deleting the table
6817                          * from the transaction.
6818                          */
6819                         if (nft_set_is_anonymous(nft_trans_set(trans)) &&
6820                             !list_empty(&nft_trans_set(trans)->bindings))
6821                                 trans->ctx.table->use--;
6822
6823                         nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
6824                                              NFT_MSG_NEWSET, GFP_KERNEL);
6825                         nft_trans_destroy(trans);
6826                         break;
6827                 case NFT_MSG_DELSET:
6828                         list_del_rcu(&nft_trans_set(trans)->list);
6829                         nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
6830                                              NFT_MSG_DELSET, GFP_KERNEL);
6831                         break;
6832                 case NFT_MSG_NEWSETELEM:
6833                         te = (struct nft_trans_elem *)trans->data;
6834
6835                         te->set->ops->activate(net, te->set, &te->elem);
6836                         nf_tables_setelem_notify(&trans->ctx, te->set,
6837                                                  &te->elem,
6838                                                  NFT_MSG_NEWSETELEM, 0);
6839                         nft_trans_destroy(trans);
6840                         break;
6841                 case NFT_MSG_DELSETELEM:
6842                         te = (struct nft_trans_elem *)trans->data;
6843
6844                         nf_tables_setelem_notify(&trans->ctx, te->set,
6845                                                  &te->elem,
6846                                                  NFT_MSG_DELSETELEM, 0);
6847                         te->set->ops->remove(net, te->set, &te->elem);
6848                         atomic_dec(&te->set->nelems);
6849                         te->set->ndeact--;
6850                         break;
6851                 case NFT_MSG_NEWOBJ:
6852                         if (nft_trans_obj_update(trans)) {
6853                                 nft_obj_commit_update(trans);
6854                                 nf_tables_obj_notify(&trans->ctx,
6855                                                      nft_trans_obj(trans),
6856                                                      NFT_MSG_NEWOBJ);
6857                         } else {
6858                                 nft_clear(net, nft_trans_obj(trans));
6859                                 nf_tables_obj_notify(&trans->ctx,
6860                                                      nft_trans_obj(trans),
6861                                                      NFT_MSG_NEWOBJ);
6862                                 nft_trans_destroy(trans);
6863                         }
6864                         break;
6865                 case NFT_MSG_DELOBJ:
6866                         nft_obj_del(nft_trans_obj(trans));
6867                         nf_tables_obj_notify(&trans->ctx, nft_trans_obj(trans),
6868                                              NFT_MSG_DELOBJ);
6869                         break;
6870                 case NFT_MSG_NEWFLOWTABLE:
6871                         nft_clear(net, nft_trans_flowtable(trans));
6872                         nf_tables_flowtable_notify(&trans->ctx,
6873                                                    nft_trans_flowtable(trans),
6874                                                    NFT_MSG_NEWFLOWTABLE);
6875                         nft_trans_destroy(trans);
6876                         break;
6877                 case NFT_MSG_DELFLOWTABLE:
6878                         list_del_rcu(&nft_trans_flowtable(trans)->list);
6879                         nf_tables_flowtable_notify(&trans->ctx,
6880                                                    nft_trans_flowtable(trans),
6881                                                    NFT_MSG_DELFLOWTABLE);
6882                         nft_unregister_flowtable_net_hooks(net,
6883                                         nft_trans_flowtable(trans));
6884                         break;
6885                 }
6886         }
6887
6888         nf_tables_gen_notify(net, skb, NFT_MSG_NEWGEN);
6889         nf_tables_commit_release(net);
6890
6891         return 0;
6892 }
6893
6894 static void nf_tables_abort_release(struct nft_trans *trans)
6895 {
6896         switch (trans->msg_type) {
6897         case NFT_MSG_NEWTABLE:
6898                 nf_tables_table_destroy(&trans->ctx);
6899                 break;
6900         case NFT_MSG_NEWCHAIN:
6901                 nf_tables_chain_destroy(&trans->ctx);
6902                 break;
6903         case NFT_MSG_NEWRULE:
6904                 nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
6905                 break;
6906         case NFT_MSG_NEWSET:
6907                 nft_set_destroy(nft_trans_set(trans));
6908                 break;
6909         case NFT_MSG_NEWSETELEM:
6910                 nft_set_elem_destroy(nft_trans_elem_set(trans),
6911                                      nft_trans_elem(trans).priv, true);
6912                 break;
6913         case NFT_MSG_NEWOBJ:
6914                 nft_obj_destroy(&trans->ctx, nft_trans_obj(trans));
6915                 break;
6916         case NFT_MSG_NEWFLOWTABLE:
6917                 nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
6918                 break;
6919         }
6920         kfree(trans);
6921 }
6922
6923 static int __nf_tables_abort(struct net *net)
6924 {
6925         struct nft_trans *trans, *next;
6926         struct nft_trans_elem *te;
6927
6928         list_for_each_entry_safe_reverse(trans, next, &net->nft.commit_list,
6929                                          list) {
6930                 switch (trans->msg_type) {
6931                 case NFT_MSG_NEWTABLE:
6932                         if (nft_trans_table_update(trans)) {
6933                                 if (nft_trans_table_enable(trans)) {
6934                                         nf_tables_table_disable(net,
6935                                                                 trans->ctx.table);
6936                                         trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
6937                                 }
6938                                 nft_trans_destroy(trans);
6939                         } else {
6940                                 list_del_rcu(&trans->ctx.table->list);
6941                         }
6942                         break;
6943                 case NFT_MSG_DELTABLE:
6944                         nft_clear(trans->ctx.net, trans->ctx.table);
6945                         nft_trans_destroy(trans);
6946                         break;
6947                 case NFT_MSG_NEWCHAIN:
6948                         if (nft_trans_chain_update(trans)) {
6949                                 free_percpu(nft_trans_chain_stats(trans));
6950                                 kfree(nft_trans_chain_name(trans));
6951                                 nft_trans_destroy(trans);
6952                         } else {
6953                                 trans->ctx.table->use--;
6954                                 nft_chain_del(trans->ctx.chain);
6955                                 nf_tables_unregister_hook(trans->ctx.net,
6956                                                           trans->ctx.table,
6957                                                           trans->ctx.chain);
6958                         }
6959                         break;
6960                 case NFT_MSG_DELCHAIN:
6961                         trans->ctx.table->use++;
6962                         nft_clear(trans->ctx.net, trans->ctx.chain);
6963                         nft_trans_destroy(trans);
6964                         break;
6965                 case NFT_MSG_NEWRULE:
6966                         trans->ctx.chain->use--;
6967                         list_del_rcu(&nft_trans_rule(trans)->list);
6968                         nft_rule_expr_deactivate(&trans->ctx,
6969                                                  nft_trans_rule(trans),
6970                                                  NFT_TRANS_ABORT);
6971                         break;
6972                 case NFT_MSG_DELRULE:
6973                         trans->ctx.chain->use++;
6974                         nft_clear(trans->ctx.net, nft_trans_rule(trans));
6975                         nft_rule_expr_activate(&trans->ctx, nft_trans_rule(trans));
6976                         nft_trans_destroy(trans);
6977                         break;
6978                 case NFT_MSG_NEWSET:
6979                         trans->ctx.table->use--;
6980                         if (nft_trans_set_bound(trans)) {
6981                                 nft_trans_destroy(trans);
6982                                 break;
6983                         }
6984                         list_del_rcu(&nft_trans_set(trans)->list);
6985                         break;
6986                 case NFT_MSG_DELSET:
6987                         trans->ctx.table->use++;
6988                         nft_clear(trans->ctx.net, nft_trans_set(trans));
6989                         nft_trans_destroy(trans);
6990                         break;
6991                 case NFT_MSG_NEWSETELEM:
6992                         if (nft_trans_elem_set_bound(trans)) {
6993                                 nft_trans_destroy(trans);
6994                                 break;
6995                         }
6996                         te = (struct nft_trans_elem *)trans->data;
6997                         te->set->ops->remove(net, te->set, &te->elem);
6998                         atomic_dec(&te->set->nelems);
6999                         break;
7000                 case NFT_MSG_DELSETELEM:
7001                         te = (struct nft_trans_elem *)trans->data;
7002
7003                         nft_set_elem_activate(net, te->set, &te->elem);
7004                         te->set->ops->activate(net, te->set, &te->elem);
7005                         te->set->ndeact--;
7006
7007                         nft_trans_destroy(trans);
7008                         break;
7009                 case NFT_MSG_NEWOBJ:
7010                         if (nft_trans_obj_update(trans)) {
7011                                 kfree(nft_trans_obj_newobj(trans));
7012                                 nft_trans_destroy(trans);
7013                         } else {
7014                                 trans->ctx.table->use--;
7015                                 nft_obj_del(nft_trans_obj(trans));
7016                         }
7017                         break;
7018                 case NFT_MSG_DELOBJ:
7019                         trans->ctx.table->use++;
7020                         nft_clear(trans->ctx.net, nft_trans_obj(trans));
7021                         nft_trans_destroy(trans);
7022                         break;
7023                 case NFT_MSG_NEWFLOWTABLE:
7024                         trans->ctx.table->use--;
7025                         list_del_rcu(&nft_trans_flowtable(trans)->list);
7026                         nft_unregister_flowtable_net_hooks(net,
7027                                         nft_trans_flowtable(trans));
7028                         break;
7029                 case NFT_MSG_DELFLOWTABLE:
7030                         trans->ctx.table->use++;
7031                         nft_clear(trans->ctx.net, nft_trans_flowtable(trans));
7032                         nft_trans_destroy(trans);
7033                         break;
7034                 }
7035         }
7036
7037         synchronize_rcu();
7038
7039         list_for_each_entry_safe_reverse(trans, next,
7040                                          &net->nft.commit_list, list) {
7041                 list_del(&trans->list);
7042                 nf_tables_abort_release(trans);
7043         }
7044
7045         return 0;
7046 }
7047
7048 static void nf_tables_cleanup(struct net *net)
7049 {
7050         nft_validate_state_update(net, NFT_VALIDATE_SKIP);
7051 }
7052
7053 static int nf_tables_abort(struct net *net, struct sk_buff *skb)
7054 {
7055         int ret = __nf_tables_abort(net);
7056
7057         mutex_unlock(&net->nft.commit_mutex);
7058
7059         return ret;
7060 }
7061
7062 static bool nf_tables_valid_genid(struct net *net, u32 genid)
7063 {
7064         bool genid_ok;
7065
7066         mutex_lock(&net->nft.commit_mutex);
7067
7068         genid_ok = genid == 0 || net->nft.base_seq == genid;
7069         if (!genid_ok)
7070                 mutex_unlock(&net->nft.commit_mutex);
7071
7072         /* else, commit mutex has to be released by commit or abort function */
7073         return genid_ok;
7074 }
7075
7076 static const struct nfnetlink_subsystem nf_tables_subsys = {
7077         .name           = "nf_tables",
7078         .subsys_id      = NFNL_SUBSYS_NFTABLES,
7079         .cb_count       = NFT_MSG_MAX,
7080         .cb             = nf_tables_cb,
7081         .commit         = nf_tables_commit,
7082         .abort          = nf_tables_abort,
7083         .cleanup        = nf_tables_cleanup,
7084         .valid_genid    = nf_tables_valid_genid,
7085         .owner          = THIS_MODULE,
7086 };
7087
7088 int nft_chain_validate_dependency(const struct nft_chain *chain,
7089                                   enum nft_chain_types type)
7090 {
7091         const struct nft_base_chain *basechain;
7092
7093         if (nft_is_base_chain(chain)) {
7094                 basechain = nft_base_chain(chain);
7095                 if (basechain->type->type != type)
7096                         return -EOPNOTSUPP;
7097         }
7098         return 0;
7099 }
7100 EXPORT_SYMBOL_GPL(nft_chain_validate_dependency);
7101
7102 int nft_chain_validate_hooks(const struct nft_chain *chain,
7103                              unsigned int hook_flags)
7104 {
7105         struct nft_base_chain *basechain;
7106
7107         if (nft_is_base_chain(chain)) {
7108                 basechain = nft_base_chain(chain);
7109
7110                 if ((1 << basechain->ops.hooknum) & hook_flags)
7111                         return 0;
7112
7113                 return -EOPNOTSUPP;
7114         }
7115
7116         return 0;
7117 }
7118 EXPORT_SYMBOL_GPL(nft_chain_validate_hooks);
7119
7120 /*
7121  * Loop detection - walk through the ruleset beginning at the destination chain
7122  * of a new jump until either the source chain is reached (loop) or all
7123  * reachable chains have been traversed.
7124  *
7125  * The loop check is performed whenever a new jump verdict is added to an
7126  * expression or verdict map or a verdict map is bound to a new chain.
7127  */
7128
7129 static int nf_tables_check_loops(const struct nft_ctx *ctx,
7130                                  const struct nft_chain *chain);
7131
7132 static int nf_tables_loop_check_setelem(const struct nft_ctx *ctx,
7133                                         struct nft_set *set,
7134                                         const struct nft_set_iter *iter,
7135                                         struct nft_set_elem *elem)
7136 {
7137         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
7138         const struct nft_data *data;
7139
7140         if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
7141             *nft_set_ext_flags(ext) & NFT_SET_ELEM_INTERVAL_END)
7142                 return 0;
7143
7144         data = nft_set_ext_data(ext);
7145         switch (data->verdict.code) {
7146         case NFT_JUMP:
7147         case NFT_GOTO:
7148                 return nf_tables_check_loops(ctx, data->verdict.chain);
7149         default:
7150                 return 0;
7151         }
7152 }
7153
7154 static int nf_tables_check_loops(const struct nft_ctx *ctx,
7155                                  const struct nft_chain *chain)
7156 {
7157         const struct nft_rule *rule;
7158         const struct nft_expr *expr, *last;
7159         struct nft_set *set;
7160         struct nft_set_binding *binding;
7161         struct nft_set_iter iter;
7162
7163         if (ctx->chain == chain)
7164                 return -ELOOP;
7165
7166         list_for_each_entry(rule, &chain->rules, list) {
7167                 nft_rule_for_each_expr(expr, last, rule) {
7168                         struct nft_immediate_expr *priv;
7169                         const struct nft_data *data;
7170                         int err;
7171
7172                         if (strcmp(expr->ops->type->name, "immediate"))
7173                                 continue;
7174
7175                         priv = nft_expr_priv(expr);
7176                         if (priv->dreg != NFT_REG_VERDICT)
7177                                 continue;
7178
7179                         data = &priv->data;
7180                         switch (data->verdict.code) {
7181                         case NFT_JUMP:
7182                         case NFT_GOTO:
7183                                 err = nf_tables_check_loops(ctx,
7184                                                         data->verdict.chain);
7185                                 if (err < 0)
7186                                         return err;
7187                         default:
7188                                 break;
7189                         }
7190                 }
7191         }
7192
7193         list_for_each_entry(set, &ctx->table->sets, list) {
7194                 if (!nft_is_active_next(ctx->net, set))
7195                         continue;
7196                 if (!(set->flags & NFT_SET_MAP) ||
7197                     set->dtype != NFT_DATA_VERDICT)
7198                         continue;
7199
7200                 list_for_each_entry(binding, &set->bindings, list) {
7201                         if (!(binding->flags & NFT_SET_MAP) ||
7202                             binding->chain != chain)
7203                                 continue;
7204
7205                         iter.genmask    = nft_genmask_next(ctx->net);
7206                         iter.skip       = 0;
7207                         iter.count      = 0;
7208                         iter.err        = 0;
7209                         iter.fn         = nf_tables_loop_check_setelem;
7210
7211                         set->ops->walk(ctx, set, &iter);
7212                         if (iter.err < 0)
7213                                 return iter.err;
7214                 }
7215         }
7216
7217         return 0;
7218 }
7219
7220 /**
7221  *      nft_parse_u32_check - fetch u32 attribute and check for maximum value
7222  *
7223  *      @attr: netlink attribute to fetch value from
7224  *      @max: maximum value to be stored in dest
7225  *      @dest: pointer to the variable
7226  *
7227  *      Parse, check and store a given u32 netlink attribute into variable.
7228  *      This function returns -ERANGE if the value goes over maximum value.
7229  *      Otherwise a 0 is returned and the attribute value is stored in the
7230  *      destination variable.
7231  */
7232 int nft_parse_u32_check(const struct nlattr *attr, int max, u32 *dest)
7233 {
7234         u32 val;
7235
7236         val = ntohl(nla_get_be32(attr));
7237         if (val > max)
7238                 return -ERANGE;
7239
7240         *dest = val;
7241         return 0;
7242 }
7243 EXPORT_SYMBOL_GPL(nft_parse_u32_check);
7244
7245 /**
7246  *      nft_parse_register - parse a register value from a netlink attribute
7247  *
7248  *      @attr: netlink attribute
7249  *
7250  *      Parse and translate a register value from a netlink attribute.
7251  *      Registers used to be 128 bit wide, these register numbers will be
7252  *      mapped to the corresponding 32 bit register numbers.
7253  */
7254 unsigned int nft_parse_register(const struct nlattr *attr)
7255 {
7256         unsigned int reg;
7257
7258         reg = ntohl(nla_get_be32(attr));
7259         switch (reg) {
7260         case NFT_REG_VERDICT...NFT_REG_4:
7261                 return reg * NFT_REG_SIZE / NFT_REG32_SIZE;
7262         default:
7263                 return reg + NFT_REG_SIZE / NFT_REG32_SIZE - NFT_REG32_00;
7264         }
7265 }
7266 EXPORT_SYMBOL_GPL(nft_parse_register);
7267
7268 /**
7269  *      nft_dump_register - dump a register value to a netlink attribute
7270  *
7271  *      @skb: socket buffer
7272  *      @attr: attribute number
7273  *      @reg: register number
7274  *
7275  *      Construct a netlink attribute containing the register number. For
7276  *      compatibility reasons, register numbers being a multiple of 4 are
7277  *      translated to the corresponding 128 bit register numbers.
7278  */
7279 int nft_dump_register(struct sk_buff *skb, unsigned int attr, unsigned int reg)
7280 {
7281         if (reg % (NFT_REG_SIZE / NFT_REG32_SIZE) == 0)
7282                 reg = reg / (NFT_REG_SIZE / NFT_REG32_SIZE);
7283         else
7284                 reg = reg - NFT_REG_SIZE / NFT_REG32_SIZE + NFT_REG32_00;
7285
7286         return nla_put_be32(skb, attr, htonl(reg));
7287 }
7288 EXPORT_SYMBOL_GPL(nft_dump_register);
7289
7290 /**
7291  *      nft_validate_register_load - validate a load from a register
7292  *
7293  *      @reg: the register number
7294  *      @len: the length of the data
7295  *
7296  *      Validate that the input register is one of the general purpose
7297  *      registers and that the length of the load is within the bounds.
7298  */
7299 int nft_validate_register_load(enum nft_registers reg, unsigned int len)
7300 {
7301         if (reg < NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE)
7302                 return -EINVAL;
7303         if (len == 0)
7304                 return -EINVAL;
7305         if (reg * NFT_REG32_SIZE + len > FIELD_SIZEOF(struct nft_regs, data))
7306                 return -ERANGE;
7307
7308         return 0;
7309 }
7310 EXPORT_SYMBOL_GPL(nft_validate_register_load);
7311
7312 /**
7313  *      nft_validate_register_store - validate an expressions' register store
7314  *
7315  *      @ctx: context of the expression performing the load
7316  *      @reg: the destination register number
7317  *      @data: the data to load
7318  *      @type: the data type
7319  *      @len: the length of the data
7320  *
7321  *      Validate that a data load uses the appropriate data type for
7322  *      the destination register and the length is within the bounds.
7323  *      A value of NULL for the data means that its runtime gathered
7324  *      data.
7325  */
7326 int nft_validate_register_store(const struct nft_ctx *ctx,
7327                                 enum nft_registers reg,
7328                                 const struct nft_data *data,
7329                                 enum nft_data_types type, unsigned int len)
7330 {
7331         int err;
7332
7333         switch (reg) {
7334         case NFT_REG_VERDICT:
7335                 if (type != NFT_DATA_VERDICT)
7336                         return -EINVAL;
7337
7338                 if (data != NULL &&
7339                     (data->verdict.code == NFT_GOTO ||
7340                      data->verdict.code == NFT_JUMP)) {
7341                         err = nf_tables_check_loops(ctx, data->verdict.chain);
7342                         if (err < 0)
7343                                 return err;
7344                 }
7345
7346                 return 0;
7347         default:
7348                 if (reg < NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE)
7349                         return -EINVAL;
7350                 if (len == 0)
7351                         return -EINVAL;
7352                 if (reg * NFT_REG32_SIZE + len >
7353                     FIELD_SIZEOF(struct nft_regs, data))
7354                         return -ERANGE;
7355
7356                 if (data != NULL && type != NFT_DATA_VALUE)
7357                         return -EINVAL;
7358                 return 0;
7359         }
7360 }
7361 EXPORT_SYMBOL_GPL(nft_validate_register_store);
7362
7363 static const struct nla_policy nft_verdict_policy[NFTA_VERDICT_MAX + 1] = {
7364         [NFTA_VERDICT_CODE]     = { .type = NLA_U32 },
7365         [NFTA_VERDICT_CHAIN]    = { .type = NLA_STRING,
7366                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
7367 };
7368
7369 static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,
7370                             struct nft_data_desc *desc, const struct nlattr *nla)
7371 {
7372         u8 genmask = nft_genmask_next(ctx->net);
7373         struct nlattr *tb[NFTA_VERDICT_MAX + 1];
7374         struct nft_chain *chain;
7375         int err;
7376
7377         err = nla_parse_nested_deprecated(tb, NFTA_VERDICT_MAX, nla,
7378                                           nft_verdict_policy, NULL);
7379         if (err < 0)
7380                 return err;
7381
7382         if (!tb[NFTA_VERDICT_CODE])
7383                 return -EINVAL;
7384         data->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));
7385
7386         switch (data->verdict.code) {
7387         default:
7388                 switch (data->verdict.code & NF_VERDICT_MASK) {
7389                 case NF_ACCEPT:
7390                 case NF_DROP:
7391                 case NF_QUEUE:
7392                         break;
7393                 default:
7394                         return -EINVAL;
7395                 }
7396                 /* fall through */
7397         case NFT_CONTINUE:
7398         case NFT_BREAK:
7399         case NFT_RETURN:
7400                 break;
7401         case NFT_JUMP:
7402         case NFT_GOTO:
7403                 if (!tb[NFTA_VERDICT_CHAIN])
7404                         return -EINVAL;
7405                 chain = nft_chain_lookup(ctx->net, ctx->table,
7406                                          tb[NFTA_VERDICT_CHAIN], genmask);
7407                 if (IS_ERR(chain))
7408                         return PTR_ERR(chain);
7409                 if (nft_is_base_chain(chain))
7410                         return -EOPNOTSUPP;
7411
7412                 chain->use++;
7413                 data->verdict.chain = chain;
7414                 break;
7415         }
7416
7417         desc->len = sizeof(data->verdict);
7418         desc->type = NFT_DATA_VERDICT;
7419         return 0;
7420 }
7421
7422 static void nft_verdict_uninit(const struct nft_data *data)
7423 {
7424         switch (data->verdict.code) {
7425         case NFT_JUMP:
7426         case NFT_GOTO:
7427                 data->verdict.chain->use--;
7428                 break;
7429         }
7430 }
7431
7432 int nft_verdict_dump(struct sk_buff *skb, int type, const struct nft_verdict *v)
7433 {
7434         struct nlattr *nest;
7435
7436         nest = nla_nest_start_noflag(skb, type);
7437         if (!nest)
7438                 goto nla_put_failure;
7439
7440         if (nla_put_be32(skb, NFTA_VERDICT_CODE, htonl(v->code)))
7441                 goto nla_put_failure;
7442
7443         switch (v->code) {
7444         case NFT_JUMP:
7445         case NFT_GOTO:
7446                 if (nla_put_string(skb, NFTA_VERDICT_CHAIN,
7447                                    v->chain->name))
7448                         goto nla_put_failure;
7449         }
7450         nla_nest_end(skb, nest);
7451         return 0;
7452
7453 nla_put_failure:
7454         return -1;
7455 }
7456
7457 static int nft_value_init(const struct nft_ctx *ctx,
7458                           struct nft_data *data, unsigned int size,
7459                           struct nft_data_desc *desc, const struct nlattr *nla)
7460 {
7461         unsigned int len;
7462
7463         len = nla_len(nla);
7464         if (len == 0)
7465                 return -EINVAL;
7466         if (len > size)
7467                 return -EOVERFLOW;
7468
7469         nla_memcpy(data->data, nla, len);
7470         desc->type = NFT_DATA_VALUE;
7471         desc->len  = len;
7472         return 0;
7473 }
7474
7475 static int nft_value_dump(struct sk_buff *skb, const struct nft_data *data,
7476                           unsigned int len)
7477 {
7478         return nla_put(skb, NFTA_DATA_VALUE, len, data->data);
7479 }
7480
7481 static const struct nla_policy nft_data_policy[NFTA_DATA_MAX + 1] = {
7482         [NFTA_DATA_VALUE]       = { .type = NLA_BINARY },
7483         [NFTA_DATA_VERDICT]     = { .type = NLA_NESTED },
7484 };
7485
7486 /**
7487  *      nft_data_init - parse nf_tables data netlink attributes
7488  *
7489  *      @ctx: context of the expression using the data
7490  *      @data: destination struct nft_data
7491  *      @size: maximum data length
7492  *      @desc: data description
7493  *      @nla: netlink attribute containing data
7494  *
7495  *      Parse the netlink data attributes and initialize a struct nft_data.
7496  *      The type and length of data are returned in the data description.
7497  *
7498  *      The caller can indicate that it only wants to accept data of type
7499  *      NFT_DATA_VALUE by passing NULL for the ctx argument.
7500  */
7501 int nft_data_init(const struct nft_ctx *ctx,
7502                   struct nft_data *data, unsigned int size,
7503                   struct nft_data_desc *desc, const struct nlattr *nla)
7504 {
7505         struct nlattr *tb[NFTA_DATA_MAX + 1];
7506         int err;
7507
7508         err = nla_parse_nested_deprecated(tb, NFTA_DATA_MAX, nla,
7509                                           nft_data_policy, NULL);
7510         if (err < 0)
7511                 return err;
7512
7513         if (tb[NFTA_DATA_VALUE])
7514                 return nft_value_init(ctx, data, size, desc,
7515                                       tb[NFTA_DATA_VALUE]);
7516         if (tb[NFTA_DATA_VERDICT] && ctx != NULL)
7517                 return nft_verdict_init(ctx, data, desc, tb[NFTA_DATA_VERDICT]);
7518         return -EINVAL;
7519 }
7520 EXPORT_SYMBOL_GPL(nft_data_init);
7521
7522 /**
7523  *      nft_data_release - release a nft_data item
7524  *
7525  *      @data: struct nft_data to release
7526  *      @type: type of data
7527  *
7528  *      Release a nft_data item. NFT_DATA_VALUE types can be silently discarded,
7529  *      all others need to be released by calling this function.
7530  */
7531 void nft_data_release(const struct nft_data *data, enum nft_data_types type)
7532 {
7533         if (type < NFT_DATA_VERDICT)
7534                 return;
7535         switch (type) {
7536         case NFT_DATA_VERDICT:
7537                 return nft_verdict_uninit(data);
7538         default:
7539                 WARN_ON(1);
7540         }
7541 }
7542 EXPORT_SYMBOL_GPL(nft_data_release);
7543
7544 int nft_data_dump(struct sk_buff *skb, int attr, const struct nft_data *data,
7545                   enum nft_data_types type, unsigned int len)
7546 {
7547         struct nlattr *nest;
7548         int err;
7549
7550         nest = nla_nest_start_noflag(skb, attr);
7551         if (nest == NULL)
7552                 return -1;
7553
7554         switch (type) {
7555         case NFT_DATA_VALUE:
7556                 err = nft_value_dump(skb, data, len);
7557                 break;
7558         case NFT_DATA_VERDICT:
7559                 err = nft_verdict_dump(skb, NFTA_DATA_VERDICT, &data->verdict);
7560                 break;
7561         default:
7562                 err = -EINVAL;
7563                 WARN_ON(1);
7564         }
7565
7566         nla_nest_end(skb, nest);
7567         return err;
7568 }
7569 EXPORT_SYMBOL_GPL(nft_data_dump);
7570
7571 int __nft_release_basechain(struct nft_ctx *ctx)
7572 {
7573         struct nft_rule *rule, *nr;
7574
7575         if (WARN_ON(!nft_is_base_chain(ctx->chain)))
7576                 return 0;
7577
7578         nf_tables_unregister_hook(ctx->net, ctx->chain->table, ctx->chain);
7579         list_for_each_entry_safe(rule, nr, &ctx->chain->rules, list) {
7580                 list_del(&rule->list);
7581                 ctx->chain->use--;
7582                 nf_tables_rule_release(ctx, rule);
7583         }
7584         nft_chain_del(ctx->chain);
7585         ctx->table->use--;
7586         nf_tables_chain_destroy(ctx);
7587
7588         return 0;
7589 }
7590 EXPORT_SYMBOL_GPL(__nft_release_basechain);
7591
7592 static void __nft_release_tables(struct net *net)
7593 {
7594         struct nft_flowtable *flowtable, *nf;
7595         struct nft_table *table, *nt;
7596         struct nft_chain *chain, *nc;
7597         struct nft_object *obj, *ne;
7598         struct nft_rule *rule, *nr;
7599         struct nft_set *set, *ns;
7600         struct nft_ctx ctx = {
7601                 .net    = net,
7602                 .family = NFPROTO_NETDEV,
7603         };
7604
7605         list_for_each_entry_safe(table, nt, &net->nft.tables, list) {
7606                 ctx.family = table->family;
7607
7608                 list_for_each_entry(chain, &table->chains, list)
7609                         nf_tables_unregister_hook(net, table, chain);
7610                 /* No packets are walking on these chains anymore. */
7611                 ctx.table = table;
7612                 list_for_each_entry(chain, &table->chains, list) {
7613                         ctx.chain = chain;
7614                         list_for_each_entry_safe(rule, nr, &chain->rules, list) {
7615                                 list_del(&rule->list);
7616                                 chain->use--;
7617                                 nf_tables_rule_release(&ctx, rule);
7618                         }
7619                 }
7620                 list_for_each_entry_safe(flowtable, nf, &table->flowtables, list) {
7621                         list_del(&flowtable->list);
7622                         table->use--;
7623                         nf_tables_flowtable_destroy(flowtable);
7624                 }
7625                 list_for_each_entry_safe(set, ns, &table->sets, list) {
7626                         list_del(&set->list);
7627                         table->use--;
7628                         nft_set_destroy(set);
7629                 }
7630                 list_for_each_entry_safe(obj, ne, &table->objects, list) {
7631                         nft_obj_del(obj);
7632                         table->use--;
7633                         nft_obj_destroy(&ctx, obj);
7634                 }
7635                 list_for_each_entry_safe(chain, nc, &table->chains, list) {
7636                         ctx.chain = chain;
7637                         nft_chain_del(chain);
7638                         table->use--;
7639                         nf_tables_chain_destroy(&ctx);
7640                 }
7641                 list_del(&table->list);
7642                 nf_tables_table_destroy(&ctx);
7643         }
7644 }
7645
7646 static int __net_init nf_tables_init_net(struct net *net)
7647 {
7648         INIT_LIST_HEAD(&net->nft.tables);
7649         INIT_LIST_HEAD(&net->nft.commit_list);
7650         mutex_init(&net->nft.commit_mutex);
7651         net->nft.base_seq = 1;
7652         net->nft.validate_state = NFT_VALIDATE_SKIP;
7653
7654         return 0;
7655 }
7656
7657 static void __net_exit nf_tables_exit_net(struct net *net)
7658 {
7659         mutex_lock(&net->nft.commit_mutex);
7660         if (!list_empty(&net->nft.commit_list))
7661                 __nf_tables_abort(net);
7662         __nft_release_tables(net);
7663         mutex_unlock(&net->nft.commit_mutex);
7664         WARN_ON_ONCE(!list_empty(&net->nft.tables));
7665 }
7666
7667 static struct pernet_operations nf_tables_net_ops = {
7668         .init   = nf_tables_init_net,
7669         .exit   = nf_tables_exit_net,
7670 };
7671
7672 static int __init nf_tables_module_init(void)
7673 {
7674         int err;
7675
7676         spin_lock_init(&nf_tables_destroy_list_lock);
7677         err = register_pernet_subsys(&nf_tables_net_ops);
7678         if (err < 0)
7679                 return err;
7680
7681         err = nft_chain_filter_init();
7682         if (err < 0)
7683                 goto err1;
7684
7685         err = nf_tables_core_module_init();
7686         if (err < 0)
7687                 goto err2;
7688
7689         err = register_netdevice_notifier(&nf_tables_flowtable_notifier);
7690         if (err < 0)
7691                 goto err3;
7692
7693         err = rhltable_init(&nft_objname_ht, &nft_objname_ht_params);
7694         if (err < 0)
7695                 goto err4;
7696
7697         err = nft_offload_init();
7698         if (err < 0)
7699                 goto err5;
7700
7701         /* must be last */
7702         err = nfnetlink_subsys_register(&nf_tables_subsys);
7703         if (err < 0)
7704                 goto err6;
7705
7706         nft_chain_route_init();
7707
7708         return err;
7709 err6:
7710         nft_offload_exit();
7711 err5:
7712         rhltable_destroy(&nft_objname_ht);
7713 err4:
7714         unregister_netdevice_notifier(&nf_tables_flowtable_notifier);
7715 err3:
7716         nf_tables_core_module_exit();
7717 err2:
7718         nft_chain_filter_fini();
7719 err1:
7720         unregister_pernet_subsys(&nf_tables_net_ops);
7721         return err;
7722 }
7723
7724 static void __exit nf_tables_module_exit(void)
7725 {
7726         nfnetlink_subsys_unregister(&nf_tables_subsys);
7727         nft_offload_exit();
7728         unregister_netdevice_notifier(&nf_tables_flowtable_notifier);
7729         nft_chain_filter_fini();
7730         nft_chain_route_fini();
7731         unregister_pernet_subsys(&nf_tables_net_ops);
7732         cancel_work_sync(&trans_destroy_work);
7733         rcu_barrier();
7734         rhltable_destroy(&nft_objname_ht);
7735         nf_tables_core_module_exit();
7736 }
7737
7738 module_init(nf_tables_module_init);
7739 module_exit(nf_tables_module_exit);
7740
7741 MODULE_LICENSE("GPL");
7742 MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
7743 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_NFTABLES);