~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/net/netfilter/nf_tables_api.c

Version: ~ [ linux-6.1-rc7 ] ~ [ linux-6.0.10 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.80 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.156 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.225 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.267 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.300 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.334 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.302 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  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 #define NFT_MODULE_AUTOLOAD_LIMIT (MODULE_NAME_LEN - sizeof("nft-expr-255-"))
 26 
 27 static LIST_HEAD(nf_tables_expressions);
 28 static LIST_HEAD(nf_tables_objects);
 29 static LIST_HEAD(nf_tables_flowtables);
 30 static LIST_HEAD(nf_tables_destroy_list);
 31 static DEFINE_SPINLOCK(nf_tables_destroy_list_lock);
 32 static u64 table_handle;
 33 
 34 enum {
 35         NFT_VALIDATE_SKIP       = 0,
 36         NFT_VALIDATE_NEED,
 37         NFT_VALIDATE_DO,
 38 };
 39 
 40 static struct rhltable nft_objname_ht;
 41 
 42 static u32 nft_chain_hash(const void *data, u32 len, u32 seed);
 43 static u32 nft_chain_hash_obj(const void *data, u32 len, u32 seed);
 44 static int nft_chain_hash_cmp(struct rhashtable_compare_arg *, const void *);
 45 
 46 static u32 nft_objname_hash(const void *data, u32 len, u32 seed);
 47 static u32 nft_objname_hash_obj(const void *data, u32 len, u32 seed);
 48 static int nft_objname_hash_cmp(struct rhashtable_compare_arg *, const void *);
 49 
 50 static const struct rhashtable_params nft_chain_ht_params = {
 51         .head_offset            = offsetof(struct nft_chain, rhlhead),
 52         .key_offset             = offsetof(struct nft_chain, name),
 53         .hashfn                 = nft_chain_hash,
 54         .obj_hashfn             = nft_chain_hash_obj,
 55         .obj_cmpfn              = nft_chain_hash_cmp,
 56         .automatic_shrinking    = true,
 57 };
 58 
 59 static const struct rhashtable_params nft_objname_ht_params = {
 60         .head_offset            = offsetof(struct nft_object, rhlhead),
 61         .key_offset             = offsetof(struct nft_object, key),
 62         .hashfn                 = nft_objname_hash,
 63         .obj_hashfn             = nft_objname_hash_obj,
 64         .obj_cmpfn              = nft_objname_hash_cmp,
 65         .automatic_shrinking    = true,
 66 };
 67 
 68 static void nft_validate_state_update(struct net *net, u8 new_validate_state)
 69 {
 70         switch (net->nft.validate_state) {
 71         case NFT_VALIDATE_SKIP:
 72                 WARN_ON_ONCE(new_validate_state == NFT_VALIDATE_DO);
 73                 break;
 74         case NFT_VALIDATE_NEED:
 75                 break;
 76         case NFT_VALIDATE_DO:
 77                 if (new_validate_state == NFT_VALIDATE_NEED)
 78                         return;
 79         }
 80 
 81         net->nft.validate_state = new_validate_state;
 82 }
 83 static void nf_tables_trans_destroy_work(struct work_struct *w);
 84 static DECLARE_WORK(trans_destroy_work, nf_tables_trans_destroy_work);
 85 
 86 static void nft_ctx_init(struct nft_ctx *ctx,
 87                          struct net *net,
 88                          const struct sk_buff *skb,
 89                          const struct nlmsghdr *nlh,
 90                          u8 family,
 91                          struct nft_table *table,
 92                          struct nft_chain *chain,
 93                          const struct nlattr * const *nla)
 94 {
 95         ctx->net        = net;
 96         ctx->family     = family;
 97         ctx->level      = 0;
 98         ctx->table      = table;
 99         ctx->chain      = chain;
100         ctx->nla        = nla;
101         ctx->portid     = NETLINK_CB(skb).portid;
102         ctx->report     = nlmsg_report(nlh);
103         ctx->flags      = nlh->nlmsg_flags;
104         ctx->seq        = nlh->nlmsg_seq;
105 }
106 
107 static struct nft_trans *nft_trans_alloc_gfp(const struct nft_ctx *ctx,
108                                              int msg_type, u32 size, gfp_t gfp)
109 {
110         struct nft_trans *trans;
111 
112         trans = kzalloc(sizeof(struct nft_trans) + size, gfp);
113         if (trans == NULL)
114                 return NULL;
115 
116         trans->msg_type = msg_type;
117         trans->ctx      = *ctx;
118 
119         return trans;
120 }
121 
122 static struct nft_trans *nft_trans_alloc(const struct nft_ctx *ctx,
123                                          int msg_type, u32 size)
124 {
125         return nft_trans_alloc_gfp(ctx, msg_type, size, GFP_KERNEL);
126 }
127 
128 static void nft_trans_destroy(struct nft_trans *trans)
129 {
130         list_del(&trans->list);
131         kfree(trans);
132 }
133 
134 static void nft_set_trans_bind(const struct nft_ctx *ctx, struct nft_set *set)
135 {
136         struct net *net = ctx->net;
137         struct nft_trans *trans;
138 
139         if (!nft_set_is_anonymous(set))
140                 return;
141 
142         list_for_each_entry_reverse(trans, &net->nft.commit_list, list) {
143                 switch (trans->msg_type) {
144                 case NFT_MSG_NEWSET:
145                         if (nft_trans_set(trans) == set)
146                                 nft_trans_set_bound(trans) = true;
147                         break;
148                 case NFT_MSG_NEWSETELEM:
149                         if (nft_trans_elem_set(trans) == set)
150                                 nft_trans_elem_set_bound(trans) = true;
151                         break;
152                 }
153         }
154 }
155 
156 static int nft_netdev_register_hooks(struct net *net,
157                                      struct list_head *hook_list)
158 {
159         struct nft_hook *hook;
160         int err, j;
161 
162         j = 0;
163         list_for_each_entry(hook, hook_list, list) {
164                 err = nf_register_net_hook(net, &hook->ops);
165                 if (err < 0)
166                         goto err_register;
167 
168                 j++;
169         }
170         return 0;
171 
172 err_register:
173         list_for_each_entry(hook, hook_list, list) {
174                 if (j-- <= 0)
175                         break;
176 
177                 nf_unregister_net_hook(net, &hook->ops);
178         }
179         return err;
180 }
181 
182 static void nft_netdev_unregister_hooks(struct net *net,
183                                         struct list_head *hook_list)
184 {
185         struct nft_hook *hook;
186 
187         list_for_each_entry(hook, hook_list, list)
188                 nf_unregister_net_hook(net, &hook->ops);
189 }
190 
191 static int nft_register_basechain_hooks(struct net *net, int family,
192                                         struct nft_base_chain *basechain)
193 {
194         if (family == NFPROTO_NETDEV)
195                 return nft_netdev_register_hooks(net, &basechain->hook_list);
196 
197         return nf_register_net_hook(net, &basechain->ops);
198 }
199 
200 static void nft_unregister_basechain_hooks(struct net *net, int family,
201                                            struct nft_base_chain *basechain)
202 {
203         if (family == NFPROTO_NETDEV)
204                 nft_netdev_unregister_hooks(net, &basechain->hook_list);
205         else
206                 nf_unregister_net_hook(net, &basechain->ops);
207 }
208 
209 static int nf_tables_register_hook(struct net *net,
210                                    const struct nft_table *table,
211                                    struct nft_chain *chain)
212 {
213         struct nft_base_chain *basechain;
214         const struct nf_hook_ops *ops;
215 
216         if (table->flags & NFT_TABLE_F_DORMANT ||
217             !nft_is_base_chain(chain))
218                 return 0;
219 
220         basechain = nft_base_chain(chain);
221         ops = &basechain->ops;
222 
223         if (basechain->type->ops_register)
224                 return basechain->type->ops_register(net, ops);
225 
226         return nft_register_basechain_hooks(net, table->family, basechain);
227 }
228 
229 static void nf_tables_unregister_hook(struct net *net,
230                                       const struct nft_table *table,
231                                       struct nft_chain *chain)
232 {
233         struct nft_base_chain *basechain;
234         const struct nf_hook_ops *ops;
235 
236         if (table->flags & NFT_TABLE_F_DORMANT ||
237             !nft_is_base_chain(chain))
238                 return;
239         basechain = nft_base_chain(chain);
240         ops = &basechain->ops;
241 
242         if (basechain->type->ops_unregister)
243                 return basechain->type->ops_unregister(net, ops);
244 
245         nft_unregister_basechain_hooks(net, table->family, basechain);
246 }
247 
248 static int nft_trans_table_add(struct nft_ctx *ctx, int msg_type)
249 {
250         struct nft_trans *trans;
251 
252         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_table));
253         if (trans == NULL)
254                 return -ENOMEM;
255 
256         if (msg_type == NFT_MSG_NEWTABLE)
257                 nft_activate_next(ctx->net, ctx->table);
258 
259         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
260         return 0;
261 }
262 
263 static int nft_deltable(struct nft_ctx *ctx)
264 {
265         int err;
266 
267         err = nft_trans_table_add(ctx, NFT_MSG_DELTABLE);
268         if (err < 0)
269                 return err;
270 
271         nft_deactivate_next(ctx->net, ctx->table);
272         return err;
273 }
274 
275 static struct nft_trans *nft_trans_chain_add(struct nft_ctx *ctx, int msg_type)
276 {
277         struct nft_trans *trans;
278 
279         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_chain));
280         if (trans == NULL)
281                 return ERR_PTR(-ENOMEM);
282 
283         if (msg_type == NFT_MSG_NEWCHAIN)
284                 nft_activate_next(ctx->net, ctx->chain);
285 
286         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
287         return trans;
288 }
289 
290 static int nft_delchain(struct nft_ctx *ctx)
291 {
292         struct nft_trans *trans;
293 
294         trans = nft_trans_chain_add(ctx, NFT_MSG_DELCHAIN);
295         if (IS_ERR(trans))
296                 return PTR_ERR(trans);
297 
298         ctx->table->use--;
299         nft_deactivate_next(ctx->net, ctx->chain);
300 
301         return 0;
302 }
303 
304 static void nft_rule_expr_activate(const struct nft_ctx *ctx,
305                                    struct nft_rule *rule)
306 {
307         struct nft_expr *expr;
308 
309         expr = nft_expr_first(rule);
310         while (expr != nft_expr_last(rule) && expr->ops) {
311                 if (expr->ops->activate)
312                         expr->ops->activate(ctx, expr);
313 
314                 expr = nft_expr_next(expr);
315         }
316 }
317 
318 static void nft_rule_expr_deactivate(const struct nft_ctx *ctx,
319                                      struct nft_rule *rule,
320                                      enum nft_trans_phase phase)
321 {
322         struct nft_expr *expr;
323 
324         expr = nft_expr_first(rule);
325         while (expr != nft_expr_last(rule) && expr->ops) {
326                 if (expr->ops->deactivate)
327                         expr->ops->deactivate(ctx, expr, phase);
328 
329                 expr = nft_expr_next(expr);
330         }
331 }
332 
333 static int
334 nf_tables_delrule_deactivate(struct nft_ctx *ctx, struct nft_rule *rule)
335 {
336         /* You cannot delete the same rule twice */
337         if (nft_is_active_next(ctx->net, rule)) {
338                 nft_deactivate_next(ctx->net, rule);
339                 ctx->chain->use--;
340                 return 0;
341         }
342         return -ENOENT;
343 }
344 
345 static struct nft_trans *nft_trans_rule_add(struct nft_ctx *ctx, int msg_type,
346                                             struct nft_rule *rule)
347 {
348         struct nft_trans *trans;
349 
350         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_rule));
351         if (trans == NULL)
352                 return NULL;
353 
354         if (msg_type == NFT_MSG_NEWRULE && ctx->nla[NFTA_RULE_ID] != NULL) {
355                 nft_trans_rule_id(trans) =
356                         ntohl(nla_get_be32(ctx->nla[NFTA_RULE_ID]));
357         }
358         nft_trans_rule(trans) = rule;
359         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
360 
361         return trans;
362 }
363 
364 static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule)
365 {
366         struct nft_flow_rule *flow;
367         struct nft_trans *trans;
368         int err;
369 
370         trans = nft_trans_rule_add(ctx, NFT_MSG_DELRULE, rule);
371         if (trans == NULL)
372                 return -ENOMEM;
373 
374         if (ctx->chain->flags & NFT_CHAIN_HW_OFFLOAD) {
375                 flow = nft_flow_rule_create(ctx->net, rule);
376                 if (IS_ERR(flow)) {
377                         nft_trans_destroy(trans);
378                         return PTR_ERR(flow);
379                 }
380 
381                 nft_trans_flow_rule(trans) = flow;
382         }
383 
384         err = nf_tables_delrule_deactivate(ctx, rule);
385         if (err < 0) {
386                 nft_trans_destroy(trans);
387                 return err;
388         }
389         nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_PREPARE);
390 
391         return 0;
392 }
393 
394 static int nft_delrule_by_chain(struct nft_ctx *ctx)
395 {
396         struct nft_rule *rule;
397         int err;
398 
399         list_for_each_entry(rule, &ctx->chain->rules, list) {
400                 if (!nft_is_active_next(ctx->net, rule))
401                         continue;
402 
403                 err = nft_delrule(ctx, rule);
404                 if (err < 0)
405                         return err;
406         }
407         return 0;
408 }
409 
410 static int nft_trans_set_add(const struct nft_ctx *ctx, int msg_type,
411                              struct nft_set *set)
412 {
413         struct nft_trans *trans;
414 
415         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_set));
416         if (trans == NULL)
417                 return -ENOMEM;
418 
419         if (msg_type == NFT_MSG_NEWSET && ctx->nla[NFTA_SET_ID] != NULL) {
420                 nft_trans_set_id(trans) =
421                         ntohl(nla_get_be32(ctx->nla[NFTA_SET_ID]));
422                 nft_activate_next(ctx->net, set);
423         }
424         nft_trans_set(trans) = set;
425         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
426 
427         return 0;
428 }
429 
430 static int nft_delset(const struct nft_ctx *ctx, struct nft_set *set)
431 {
432         int err;
433 
434         err = nft_trans_set_add(ctx, NFT_MSG_DELSET, set);
435         if (err < 0)
436                 return err;
437 
438         nft_deactivate_next(ctx->net, set);
439         ctx->table->use--;
440 
441         return err;
442 }
443 
444 static int nft_trans_obj_add(struct nft_ctx *ctx, int msg_type,
445                              struct nft_object *obj)
446 {
447         struct nft_trans *trans;
448 
449         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_obj));
450         if (trans == NULL)
451                 return -ENOMEM;
452 
453         if (msg_type == NFT_MSG_NEWOBJ)
454                 nft_activate_next(ctx->net, obj);
455 
456         nft_trans_obj(trans) = obj;
457         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
458 
459         return 0;
460 }
461 
462 static int nft_delobj(struct nft_ctx *ctx, struct nft_object *obj)
463 {
464         int err;
465 
466         err = nft_trans_obj_add(ctx, NFT_MSG_DELOBJ, obj);
467         if (err < 0)
468                 return err;
469 
470         nft_deactivate_next(ctx->net, obj);
471         ctx->table->use--;
472 
473         return err;
474 }
475 
476 static int nft_trans_flowtable_add(struct nft_ctx *ctx, int msg_type,
477                                    struct nft_flowtable *flowtable)
478 {
479         struct nft_trans *trans;
480 
481         trans = nft_trans_alloc(ctx, msg_type,
482                                 sizeof(struct nft_trans_flowtable));
483         if (trans == NULL)
484                 return -ENOMEM;
485 
486         if (msg_type == NFT_MSG_NEWFLOWTABLE)
487                 nft_activate_next(ctx->net, flowtable);
488 
489         nft_trans_flowtable(trans) = flowtable;
490         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
491 
492         return 0;
493 }
494 
495 static int nft_delflowtable(struct nft_ctx *ctx,
496                             struct nft_flowtable *flowtable)
497 {
498         int err;
499 
500         err = nft_trans_flowtable_add(ctx, NFT_MSG_DELFLOWTABLE, flowtable);
501         if (err < 0)
502                 return err;
503 
504         nft_deactivate_next(ctx->net, flowtable);
505         ctx->table->use--;
506 
507         return err;
508 }
509 
510 /*
511  * Tables
512  */
513 
514 static struct nft_table *nft_table_lookup(const struct net *net,
515                                           const struct nlattr *nla,
516                                           u8 family, u8 genmask)
517 {
518         struct nft_table *table;
519 
520         if (nla == NULL)
521                 return ERR_PTR(-EINVAL);
522 
523         list_for_each_entry_rcu(table, &net->nft.tables, list) {
524                 if (!nla_strcmp(nla, table->name) &&
525                     table->family == family &&
526                     nft_active_genmask(table, genmask))
527                         return table;
528         }
529 
530         return ERR_PTR(-ENOENT);
531 }
532 
533 static struct nft_table *nft_table_lookup_byhandle(const struct net *net,
534                                                    const struct nlattr *nla,
535                                                    u8 genmask)
536 {
537         struct nft_table *table;
538 
539         list_for_each_entry(table, &net->nft.tables, list) {
540                 if (be64_to_cpu(nla_get_be64(nla)) == table->handle &&
541                     nft_active_genmask(table, genmask))
542                         return table;
543         }
544 
545         return ERR_PTR(-ENOENT);
546 }
547 
548 static inline u64 nf_tables_alloc_handle(struct nft_table *table)
549 {
550         return ++table->hgenerator;
551 }
552 
553 static const struct nft_chain_type *chain_type[NFPROTO_NUMPROTO][NFT_CHAIN_T_MAX];
554 
555 static const struct nft_chain_type *
556 __nft_chain_type_get(u8 family, enum nft_chain_types type)
557 {
558         if (family >= NFPROTO_NUMPROTO ||
559             type >= NFT_CHAIN_T_MAX)
560                 return NULL;
561 
562         return chain_type[family][type];
563 }
564 
565 static const struct nft_chain_type *
566 __nf_tables_chain_type_lookup(const struct nlattr *nla, u8 family)
567 {
568         const struct nft_chain_type *type;
569         int i;
570 
571         for (i = 0; i < NFT_CHAIN_T_MAX; i++) {
572                 type = __nft_chain_type_get(family, i);
573                 if (!type)
574                         continue;
575                 if (!nla_strcmp(nla, type->name))
576                         return type;
577         }
578         return NULL;
579 }
580 
581 struct nft_module_request {
582         struct list_head        list;
583         char                    module[MODULE_NAME_LEN];
584         bool                    done;
585 };
586 
587 #ifdef CONFIG_MODULES
588 static int nft_request_module(struct net *net, const char *fmt, ...)
589 {
590         char module_name[MODULE_NAME_LEN];
591         struct nft_module_request *req;
592         va_list args;
593         int ret;
594 
595         va_start(args, fmt);
596         ret = vsnprintf(module_name, MODULE_NAME_LEN, fmt, args);
597         va_end(args);
598         if (ret >= MODULE_NAME_LEN)
599                 return 0;
600 
601         list_for_each_entry(req, &net->nft.module_list, list) {
602                 if (!strcmp(req->module, module_name)) {
603                         if (req->done)
604                                 return 0;
605 
606                         /* A request to load this module already exists. */
607                         return -EAGAIN;
608                 }
609         }
610 
611         req = kmalloc(sizeof(*req), GFP_KERNEL);
612         if (!req)
613                 return -ENOMEM;
614 
615         req->done = false;
616         strlcpy(req->module, module_name, MODULE_NAME_LEN);
617         list_add_tail(&req->list, &net->nft.module_list);
618 
619         return -EAGAIN;
620 }
621 #endif
622 
623 static void lockdep_nfnl_nft_mutex_not_held(void)
624 {
625 #ifdef CONFIG_PROVE_LOCKING
626         WARN_ON_ONCE(lockdep_nfnl_is_held(NFNL_SUBSYS_NFTABLES));
627 #endif
628 }
629 
630 static const struct nft_chain_type *
631 nf_tables_chain_type_lookup(struct net *net, const struct nlattr *nla,
632                             u8 family, bool autoload)
633 {
634         const struct nft_chain_type *type;
635 
636         type = __nf_tables_chain_type_lookup(nla, family);
637         if (type != NULL)
638                 return type;
639 
640         lockdep_nfnl_nft_mutex_not_held();
641 #ifdef CONFIG_MODULES
642         if (autoload) {
643                 if (nft_request_module(net, "nft-chain-%u-%.*s", family,
644                                        nla_len(nla),
645                                        (const char *)nla_data(nla)) == -EAGAIN)
646                         return ERR_PTR(-EAGAIN);
647         }
648 #endif
649         return ERR_PTR(-ENOENT);
650 }
651 
652 static const struct nla_policy nft_table_policy[NFTA_TABLE_MAX + 1] = {
653         [NFTA_TABLE_NAME]       = { .type = NLA_STRING,
654                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
655         [NFTA_TABLE_FLAGS]      = { .type = NLA_U32 },
656         [NFTA_TABLE_HANDLE]     = { .type = NLA_U64 },
657 };
658 
659 static int nf_tables_fill_table_info(struct sk_buff *skb, struct net *net,
660                                      u32 portid, u32 seq, int event, u32 flags,
661                                      int family, const struct nft_table *table)
662 {
663         struct nlmsghdr *nlh;
664         struct nfgenmsg *nfmsg;
665 
666         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
667         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
668         if (nlh == NULL)
669                 goto nla_put_failure;
670 
671         nfmsg = nlmsg_data(nlh);
672         nfmsg->nfgen_family     = family;
673         nfmsg->version          = NFNETLINK_V0;
674         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
675 
676         if (nla_put_string(skb, NFTA_TABLE_NAME, table->name) ||
677             nla_put_be32(skb, NFTA_TABLE_FLAGS, htonl(table->flags)) ||
678             nla_put_be32(skb, NFTA_TABLE_USE, htonl(table->use)) ||
679             nla_put_be64(skb, NFTA_TABLE_HANDLE, cpu_to_be64(table->handle),
680                          NFTA_TABLE_PAD))
681                 goto nla_put_failure;
682 
683         nlmsg_end(skb, nlh);
684         return 0;
685 
686 nla_put_failure:
687         nlmsg_trim(skb, nlh);
688         return -1;
689 }
690 
691 static void nf_tables_table_notify(const struct nft_ctx *ctx, int event)
692 {
693         struct sk_buff *skb;
694         int err;
695 
696         if (!ctx->report &&
697             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
698                 return;
699 
700         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
701         if (skb == NULL)
702                 goto err;
703 
704         err = nf_tables_fill_table_info(skb, ctx->net, ctx->portid, ctx->seq,
705                                         event, 0, ctx->family, ctx->table);
706         if (err < 0) {
707                 kfree_skb(skb);
708                 goto err;
709         }
710 
711         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
712                        ctx->report, GFP_KERNEL);
713         return;
714 err:
715         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
716 }
717 
718 static int nf_tables_dump_tables(struct sk_buff *skb,
719                                  struct netlink_callback *cb)
720 {
721         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
722         const struct nft_table *table;
723         unsigned int idx = 0, s_idx = cb->args[0];
724         struct net *net = sock_net(skb->sk);
725         int family = nfmsg->nfgen_family;
726 
727         rcu_read_lock();
728         cb->seq = net->nft.base_seq;
729 
730         list_for_each_entry_rcu(table, &net->nft.tables, list) {
731                 if (family != NFPROTO_UNSPEC && family != table->family)
732                         continue;
733 
734                 if (idx < s_idx)
735                         goto cont;
736                 if (idx > s_idx)
737                         memset(&cb->args[1], 0,
738                                sizeof(cb->args) - sizeof(cb->args[0]));
739                 if (!nft_is_active(net, table))
740                         continue;
741                 if (nf_tables_fill_table_info(skb, net,
742                                               NETLINK_CB(cb->skb).portid,
743                                               cb->nlh->nlmsg_seq,
744                                               NFT_MSG_NEWTABLE, NLM_F_MULTI,
745                                               table->family, table) < 0)
746                         goto done;
747 
748                 nl_dump_check_consistent(cb, nlmsg_hdr(skb));
749 cont:
750                 idx++;
751         }
752 done:
753         rcu_read_unlock();
754         cb->args[0] = idx;
755         return skb->len;
756 }
757 
758 static int nft_netlink_dump_start_rcu(struct sock *nlsk, struct sk_buff *skb,
759                                       const struct nlmsghdr *nlh,
760                                       struct netlink_dump_control *c)
761 {
762         int err;
763 
764         if (!try_module_get(THIS_MODULE))
765                 return -EINVAL;
766 
767         rcu_read_unlock();
768         err = netlink_dump_start(nlsk, skb, nlh, c);
769         rcu_read_lock();
770         module_put(THIS_MODULE);
771 
772         return err;
773 }
774 
775 /* called with rcu_read_lock held */
776 static int nf_tables_gettable(struct net *net, struct sock *nlsk,
777                               struct sk_buff *skb, const struct nlmsghdr *nlh,
778                               const struct nlattr * const nla[],
779                               struct netlink_ext_ack *extack)
780 {
781         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
782         u8 genmask = nft_genmask_cur(net);
783         const struct nft_table *table;
784         struct sk_buff *skb2;
785         int family = nfmsg->nfgen_family;
786         int err;
787 
788         if (nlh->nlmsg_flags & NLM_F_DUMP) {
789                 struct netlink_dump_control c = {
790                         .dump = nf_tables_dump_tables,
791                         .module = THIS_MODULE,
792                 };
793 
794                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
795         }
796 
797         table = nft_table_lookup(net, nla[NFTA_TABLE_NAME], family, genmask);
798         if (IS_ERR(table)) {
799                 NL_SET_BAD_ATTR(extack, nla[NFTA_TABLE_NAME]);
800                 return PTR_ERR(table);
801         }
802 
803         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
804         if (!skb2)
805                 return -ENOMEM;
806 
807         err = nf_tables_fill_table_info(skb2, net, NETLINK_CB(skb).portid,
808                                         nlh->nlmsg_seq, NFT_MSG_NEWTABLE, 0,
809                                         family, table);
810         if (err < 0)
811                 goto err;
812 
813         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
814 
815 err:
816         kfree_skb(skb2);
817         return err;
818 }
819 
820 static void nft_table_disable(struct net *net, struct nft_table *table, u32 cnt)
821 {
822         struct nft_chain *chain;
823         u32 i = 0;
824 
825         list_for_each_entry(chain, &table->chains, list) {
826                 if (!nft_is_active_next(net, chain))
827                         continue;
828                 if (!nft_is_base_chain(chain))
829                         continue;
830 
831                 if (cnt && i++ == cnt)
832                         break;
833 
834                 nft_unregister_basechain_hooks(net, table->family,
835                                                nft_base_chain(chain));
836         }
837 }
838 
839 static int nf_tables_table_enable(struct net *net, struct nft_table *table)
840 {
841         struct nft_chain *chain;
842         int err, i = 0;
843 
844         list_for_each_entry(chain, &table->chains, list) {
845                 if (!nft_is_active_next(net, chain))
846                         continue;
847                 if (!nft_is_base_chain(chain))
848                         continue;
849 
850                 err = nft_register_basechain_hooks(net, table->family,
851                                                    nft_base_chain(chain));
852                 if (err < 0)
853                         goto err_register_hooks;
854 
855                 i++;
856         }
857         return 0;
858 
859 err_register_hooks:
860         if (i)
861                 nft_table_disable(net, table, i);
862         return err;
863 }
864 
865 static void nf_tables_table_disable(struct net *net, struct nft_table *table)
866 {
867         nft_table_disable(net, table, 0);
868 }
869 
870 static int nf_tables_updtable(struct nft_ctx *ctx)
871 {
872         struct nft_trans *trans;
873         u32 flags;
874         int ret = 0;
875 
876         if (!ctx->nla[NFTA_TABLE_FLAGS])
877                 return 0;
878 
879         flags = ntohl(nla_get_be32(ctx->nla[NFTA_TABLE_FLAGS]));
880         if (flags & ~NFT_TABLE_F_DORMANT)
881                 return -EINVAL;
882 
883         if (flags == ctx->table->flags)
884                 return 0;
885 
886         trans = nft_trans_alloc(ctx, NFT_MSG_NEWTABLE,
887                                 sizeof(struct nft_trans_table));
888         if (trans == NULL)
889                 return -ENOMEM;
890 
891         if ((flags & NFT_TABLE_F_DORMANT) &&
892             !(ctx->table->flags & NFT_TABLE_F_DORMANT)) {
893                 nft_trans_table_enable(trans) = false;
894         } else if (!(flags & NFT_TABLE_F_DORMANT) &&
895                    ctx->table->flags & NFT_TABLE_F_DORMANT) {
896                 ret = nf_tables_table_enable(ctx->net, ctx->table);
897                 if (ret >= 0) {
898                         ctx->table->flags &= ~NFT_TABLE_F_DORMANT;
899                         nft_trans_table_enable(trans) = true;
900                 }
901         }
902         if (ret < 0)
903                 goto err;
904 
905         nft_trans_table_update(trans) = true;
906         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
907         return 0;
908 err:
909         nft_trans_destroy(trans);
910         return ret;
911 }
912 
913 static u32 nft_chain_hash(const void *data, u32 len, u32 seed)
914 {
915         const char *name = data;
916 
917         return jhash(name, strlen(name), seed);
918 }
919 
920 static u32 nft_chain_hash_obj(const void *data, u32 len, u32 seed)
921 {
922         const struct nft_chain *chain = data;
923 
924         return nft_chain_hash(chain->name, 0, seed);
925 }
926 
927 static int nft_chain_hash_cmp(struct rhashtable_compare_arg *arg,
928                               const void *ptr)
929 {
930         const struct nft_chain *chain = ptr;
931         const char *name = arg->key;
932 
933         return strcmp(chain->name, name);
934 }
935 
936 static u32 nft_objname_hash(const void *data, u32 len, u32 seed)
937 {
938         const struct nft_object_hash_key *k = data;
939 
940         seed ^= hash_ptr(k->table, 32);
941 
942         return jhash(k->name, strlen(k->name), seed);
943 }
944 
945 static u32 nft_objname_hash_obj(const void *data, u32 len, u32 seed)
946 {
947         const struct nft_object *obj = data;
948 
949         return nft_objname_hash(&obj->key, 0, seed);
950 }
951 
952 static int nft_objname_hash_cmp(struct rhashtable_compare_arg *arg,
953                                 const void *ptr)
954 {
955         const struct nft_object_hash_key *k = arg->key;
956         const struct nft_object *obj = ptr;
957 
958         if (obj->key.table != k->table)
959                 return -1;
960 
961         return strcmp(obj->key.name, k->name);
962 }
963 
964 static int nf_tables_newtable(struct net *net, struct sock *nlsk,
965                               struct sk_buff *skb, const struct nlmsghdr *nlh,
966                               const struct nlattr * const nla[],
967                               struct netlink_ext_ack *extack)
968 {
969         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
970         u8 genmask = nft_genmask_next(net);
971         int family = nfmsg->nfgen_family;
972         const struct nlattr *attr;
973         struct nft_table *table;
974         u32 flags = 0;
975         struct nft_ctx ctx;
976         int err;
977 
978         lockdep_assert_held(&net->nft.commit_mutex);
979         attr = nla[NFTA_TABLE_NAME];
980         table = nft_table_lookup(net, attr, family, genmask);
981         if (IS_ERR(table)) {
982                 if (PTR_ERR(table) != -ENOENT)
983                         return PTR_ERR(table);
984         } else {
985                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
986                         NL_SET_BAD_ATTR(extack, attr);
987                         return -EEXIST;
988                 }
989                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
990                         return -EOPNOTSUPP;
991 
992                 nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
993                 return nf_tables_updtable(&ctx);
994         }
995 
996         if (nla[NFTA_TABLE_FLAGS]) {
997                 flags = ntohl(nla_get_be32(nla[NFTA_TABLE_FLAGS]));
998                 if (flags & ~NFT_TABLE_F_DORMANT)
999                         return -EINVAL;
1000         }
1001 
1002         err = -ENOMEM;
1003         table = kzalloc(sizeof(*table), GFP_KERNEL);
1004         if (table == NULL)
1005                 goto err_kzalloc;
1006 
1007         table->name = nla_strdup(attr, GFP_KERNEL);
1008         if (table->name == NULL)
1009                 goto err_strdup;
1010 
1011         err = rhltable_init(&table->chains_ht, &nft_chain_ht_params);
1012         if (err)
1013                 goto err_chain_ht;
1014 
1015         INIT_LIST_HEAD(&table->chains);
1016         INIT_LIST_HEAD(&table->sets);
1017         INIT_LIST_HEAD(&table->objects);
1018         INIT_LIST_HEAD(&table->flowtables);
1019         table->family = family;
1020         table->flags = flags;
1021         table->handle = ++table_handle;
1022 
1023         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
1024         err = nft_trans_table_add(&ctx, NFT_MSG_NEWTABLE);
1025         if (err < 0)
1026                 goto err_trans;
1027 
1028         list_add_tail_rcu(&table->list, &net->nft.tables);
1029         return 0;
1030 err_trans:
1031         rhltable_destroy(&table->chains_ht);
1032 err_chain_ht:
1033         kfree(table->name);
1034 err_strdup:
1035         kfree(table);
1036 err_kzalloc:
1037         return err;
1038 }
1039 
1040 static int nft_flush_table(struct nft_ctx *ctx)
1041 {
1042         struct nft_flowtable *flowtable, *nft;
1043         struct nft_chain *chain, *nc;
1044         struct nft_object *obj, *ne;
1045         struct nft_set *set, *ns;
1046         int err;
1047 
1048         list_for_each_entry(chain, &ctx->table->chains, list) {
1049                 if (!nft_is_active_next(ctx->net, chain))
1050                         continue;
1051 
1052                 ctx->chain = chain;
1053 
1054                 err = nft_delrule_by_chain(ctx);
1055                 if (err < 0)
1056                         goto out;
1057         }
1058 
1059         list_for_each_entry_safe(set, ns, &ctx->table->sets, list) {
1060                 if (!nft_is_active_next(ctx->net, set))
1061                         continue;
1062 
1063                 if (nft_set_is_anonymous(set) &&
1064                     !list_empty(&set->bindings))
1065                         continue;
1066 
1067                 err = nft_delset(ctx, set);
1068                 if (err < 0)
1069                         goto out;
1070         }
1071 
1072         list_for_each_entry_safe(flowtable, nft, &ctx->table->flowtables, list) {
1073                 if (!nft_is_active_next(ctx->net, flowtable))
1074                         continue;
1075 
1076                 err = nft_delflowtable(ctx, flowtable);
1077                 if (err < 0)
1078                         goto out;
1079         }
1080 
1081         list_for_each_entry_safe(obj, ne, &ctx->table->objects, list) {
1082                 if (!nft_is_active_next(ctx->net, obj))
1083                         continue;
1084 
1085                 err = nft_delobj(ctx, obj);
1086                 if (err < 0)
1087                         goto out;
1088         }
1089 
1090         list_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {
1091                 if (!nft_is_active_next(ctx->net, chain))
1092                         continue;
1093 
1094                 ctx->chain = chain;
1095 
1096                 err = nft_delchain(ctx);
1097                 if (err < 0)
1098                         goto out;
1099         }
1100 
1101         err = nft_deltable(ctx);
1102 out:
1103         return err;
1104 }
1105 
1106 static int nft_flush(struct nft_ctx *ctx, int family)
1107 {
1108         struct nft_table *table, *nt;
1109         const struct nlattr * const *nla = ctx->nla;
1110         int err = 0;
1111 
1112         list_for_each_entry_safe(table, nt, &ctx->net->nft.tables, list) {
1113                 if (family != AF_UNSPEC && table->family != family)
1114                         continue;
1115 
1116                 ctx->family = table->family;
1117 
1118                 if (!nft_is_active_next(ctx->net, table))
1119                         continue;
1120 
1121                 if (nla[NFTA_TABLE_NAME] &&
1122                     nla_strcmp(nla[NFTA_TABLE_NAME], table->name) != 0)
1123                         continue;
1124 
1125                 ctx->table = table;
1126 
1127                 err = nft_flush_table(ctx);
1128                 if (err < 0)
1129                         goto out;
1130         }
1131 out:
1132         return err;
1133 }
1134 
1135 static int nf_tables_deltable(struct net *net, struct sock *nlsk,
1136                               struct sk_buff *skb, const struct nlmsghdr *nlh,
1137                               const struct nlattr * const nla[],
1138                               struct netlink_ext_ack *extack)
1139 {
1140         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1141         u8 genmask = nft_genmask_next(net);
1142         int family = nfmsg->nfgen_family;
1143         const struct nlattr *attr;
1144         struct nft_table *table;
1145         struct nft_ctx ctx;
1146 
1147         nft_ctx_init(&ctx, net, skb, nlh, 0, NULL, NULL, nla);
1148         if (family == AF_UNSPEC ||
1149             (!nla[NFTA_TABLE_NAME] && !nla[NFTA_TABLE_HANDLE]))
1150                 return nft_flush(&ctx, family);
1151 
1152         if (nla[NFTA_TABLE_HANDLE]) {
1153                 attr = nla[NFTA_TABLE_HANDLE];
1154                 table = nft_table_lookup_byhandle(net, attr, genmask);
1155         } else {
1156                 attr = nla[NFTA_TABLE_NAME];
1157                 table = nft_table_lookup(net, attr, family, genmask);
1158         }
1159 
1160         if (IS_ERR(table)) {
1161                 NL_SET_BAD_ATTR(extack, attr);
1162                 return PTR_ERR(table);
1163         }
1164 
1165         if (nlh->nlmsg_flags & NLM_F_NONREC &&
1166             table->use > 0)
1167                 return -EBUSY;
1168 
1169         ctx.family = family;
1170         ctx.table = table;
1171 
1172         return nft_flush_table(&ctx);
1173 }
1174 
1175 static void nf_tables_table_destroy(struct nft_ctx *ctx)
1176 {
1177         if (WARN_ON(ctx->table->use > 0))
1178                 return;
1179 
1180         rhltable_destroy(&ctx->table->chains_ht);
1181         kfree(ctx->table->name);
1182         kfree(ctx->table);
1183 }
1184 
1185 void nft_register_chain_type(const struct nft_chain_type *ctype)
1186 {
1187         nfnl_lock(NFNL_SUBSYS_NFTABLES);
1188         if (WARN_ON(__nft_chain_type_get(ctype->family, ctype->type))) {
1189                 nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1190                 return;
1191         }
1192         chain_type[ctype->family][ctype->type] = ctype;
1193         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1194 }
1195 EXPORT_SYMBOL_GPL(nft_register_chain_type);
1196 
1197 void nft_unregister_chain_type(const struct nft_chain_type *ctype)
1198 {
1199         nfnl_lock(NFNL_SUBSYS_NFTABLES);
1200         chain_type[ctype->family][ctype->type] = NULL;
1201         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1202 }
1203 EXPORT_SYMBOL_GPL(nft_unregister_chain_type);
1204 
1205 /*
1206  * Chains
1207  */
1208 
1209 static struct nft_chain *
1210 nft_chain_lookup_byhandle(const struct nft_table *table, u64 handle, u8 genmask)
1211 {
1212         struct nft_chain *chain;
1213 
1214         list_for_each_entry(chain, &table->chains, list) {
1215                 if (chain->handle == handle &&
1216                     nft_active_genmask(chain, genmask))
1217                         return chain;
1218         }
1219 
1220         return ERR_PTR(-ENOENT);
1221 }
1222 
1223 static bool lockdep_commit_lock_is_held(const struct net *net)
1224 {
1225 #ifdef CONFIG_PROVE_LOCKING
1226         return lockdep_is_held(&net->nft.commit_mutex);
1227 #else
1228         return true;
1229 #endif
1230 }
1231 
1232 static struct nft_chain *nft_chain_lookup(struct net *net,
1233                                           struct nft_table *table,
1234                                           const struct nlattr *nla, u8 genmask)
1235 {
1236         char search[NFT_CHAIN_MAXNAMELEN + 1];
1237         struct rhlist_head *tmp, *list;
1238         struct nft_chain *chain;
1239 
1240         if (nla == NULL)
1241                 return ERR_PTR(-EINVAL);
1242 
1243         nla_strlcpy(search, nla, sizeof(search));
1244 
1245         WARN_ON(!rcu_read_lock_held() &&
1246                 !lockdep_commit_lock_is_held(net));
1247 
1248         chain = ERR_PTR(-ENOENT);
1249         rcu_read_lock();
1250         list = rhltable_lookup(&table->chains_ht, search, nft_chain_ht_params);
1251         if (!list)
1252                 goto out_unlock;
1253 
1254         rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) {
1255                 if (nft_active_genmask(chain, genmask))
1256                         goto out_unlock;
1257         }
1258         chain = ERR_PTR(-ENOENT);
1259 out_unlock:
1260         rcu_read_unlock();
1261         return chain;
1262 }
1263 
1264 static const struct nla_policy nft_chain_policy[NFTA_CHAIN_MAX + 1] = {
1265         [NFTA_CHAIN_TABLE]      = { .type = NLA_STRING,
1266                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
1267         [NFTA_CHAIN_HANDLE]     = { .type = NLA_U64 },
1268         [NFTA_CHAIN_NAME]       = { .type = NLA_STRING,
1269                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
1270         [NFTA_CHAIN_HOOK]       = { .type = NLA_NESTED },
1271         [NFTA_CHAIN_POLICY]     = { .type = NLA_U32 },
1272         [NFTA_CHAIN_TYPE]       = { .type = NLA_STRING,
1273                                     .len = NFT_MODULE_AUTOLOAD_LIMIT },
1274         [NFTA_CHAIN_COUNTERS]   = { .type = NLA_NESTED },
1275         [NFTA_CHAIN_FLAGS]      = { .type = NLA_U32 },
1276 };
1277 
1278 static const struct nla_policy nft_hook_policy[NFTA_HOOK_MAX + 1] = {
1279         [NFTA_HOOK_HOOKNUM]     = { .type = NLA_U32 },
1280         [NFTA_HOOK_PRIORITY]    = { .type = NLA_U32 },
1281         [NFTA_HOOK_DEV]         = { .type = NLA_STRING,
1282                                     .len = IFNAMSIZ - 1 },
1283 };
1284 
1285 static int nft_dump_stats(struct sk_buff *skb, struct nft_stats __percpu *stats)
1286 {
1287         struct nft_stats *cpu_stats, total;
1288         struct nlattr *nest;
1289         unsigned int seq;
1290         u64 pkts, bytes;
1291         int cpu;
1292 
1293         if (!stats)
1294                 return 0;
1295 
1296         memset(&total, 0, sizeof(total));
1297         for_each_possible_cpu(cpu) {
1298                 cpu_stats = per_cpu_ptr(stats, cpu);
1299                 do {
1300                         seq = u64_stats_fetch_begin_irq(&cpu_stats->syncp);
1301                         pkts = cpu_stats->pkts;
1302                         bytes = cpu_stats->bytes;
1303                 } while (u64_stats_fetch_retry_irq(&cpu_stats->syncp, seq));
1304                 total.pkts += pkts;
1305                 total.bytes += bytes;
1306         }
1307         nest = nla_nest_start_noflag(skb, NFTA_CHAIN_COUNTERS);
1308         if (nest == NULL)
1309                 goto nla_put_failure;
1310 
1311         if (nla_put_be64(skb, NFTA_COUNTER_PACKETS, cpu_to_be64(total.pkts),
1312                          NFTA_COUNTER_PAD) ||
1313             nla_put_be64(skb, NFTA_COUNTER_BYTES, cpu_to_be64(total.bytes),
1314                          NFTA_COUNTER_PAD))
1315                 goto nla_put_failure;
1316 
1317         nla_nest_end(skb, nest);
1318         return 0;
1319 
1320 nla_put_failure:
1321         return -ENOSPC;
1322 }
1323 
1324 static int nft_dump_basechain_hook(struct sk_buff *skb, int family,
1325                                    const struct nft_base_chain *basechain)
1326 {
1327         const struct nf_hook_ops *ops = &basechain->ops;
1328         struct nft_hook *hook, *first = NULL;
1329         struct nlattr *nest, *nest_devs;
1330         int n = 0;
1331 
1332         nest = nla_nest_start_noflag(skb, NFTA_CHAIN_HOOK);
1333         if (nest == NULL)
1334                 goto nla_put_failure;
1335         if (nla_put_be32(skb, NFTA_HOOK_HOOKNUM, htonl(ops->hooknum)))
1336                 goto nla_put_failure;
1337         if (nla_put_be32(skb, NFTA_HOOK_PRIORITY, htonl(ops->priority)))
1338                 goto nla_put_failure;
1339 
1340         if (family == NFPROTO_NETDEV) {
1341                 nest_devs = nla_nest_start_noflag(skb, NFTA_HOOK_DEVS);
1342                 list_for_each_entry(hook, &basechain->hook_list, list) {
1343                         if (!first)
1344                                 first = hook;
1345 
1346                         if (nla_put_string(skb, NFTA_DEVICE_NAME,
1347                                            hook->ops.dev->name))
1348                                 goto nla_put_failure;
1349                         n++;
1350                 }
1351                 nla_nest_end(skb, nest_devs);
1352 
1353                 if (n == 1 &&
1354                     nla_put_string(skb, NFTA_HOOK_DEV, first->ops.dev->name))
1355                         goto nla_put_failure;
1356         }
1357         nla_nest_end(skb, nest);
1358 
1359         return 0;
1360 nla_put_failure:
1361         return -1;
1362 }
1363 
1364 static int nf_tables_fill_chain_info(struct sk_buff *skb, struct net *net,
1365                                      u32 portid, u32 seq, int event, u32 flags,
1366                                      int family, const struct nft_table *table,
1367                                      const struct nft_chain *chain)
1368 {
1369         struct nlmsghdr *nlh;
1370         struct nfgenmsg *nfmsg;
1371 
1372         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
1373         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
1374         if (nlh == NULL)
1375                 goto nla_put_failure;
1376 
1377         nfmsg = nlmsg_data(nlh);
1378         nfmsg->nfgen_family     = family;
1379         nfmsg->version          = NFNETLINK_V0;
1380         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
1381 
1382         if (nla_put_string(skb, NFTA_CHAIN_TABLE, table->name))
1383                 goto nla_put_failure;
1384         if (nla_put_be64(skb, NFTA_CHAIN_HANDLE, cpu_to_be64(chain->handle),
1385                          NFTA_CHAIN_PAD))
1386                 goto nla_put_failure;
1387         if (nla_put_string(skb, NFTA_CHAIN_NAME, chain->name))
1388                 goto nla_put_failure;
1389 
1390         if (nft_is_base_chain(chain)) {
1391                 const struct nft_base_chain *basechain = nft_base_chain(chain);
1392                 struct nft_stats __percpu *stats;
1393 
1394                 if (nft_dump_basechain_hook(skb, family, basechain))
1395                         goto nla_put_failure;
1396 
1397                 if (nla_put_be32(skb, NFTA_CHAIN_POLICY,
1398                                  htonl(basechain->policy)))
1399                         goto nla_put_failure;
1400 
1401                 if (nla_put_string(skb, NFTA_CHAIN_TYPE, basechain->type->name))
1402                         goto nla_put_failure;
1403 
1404                 stats = rcu_dereference_check(basechain->stats,
1405                                               lockdep_commit_lock_is_held(net));
1406                 if (nft_dump_stats(skb, stats))
1407                         goto nla_put_failure;
1408 
1409                 if ((chain->flags & NFT_CHAIN_HW_OFFLOAD) &&
1410                     nla_put_be32(skb, NFTA_CHAIN_FLAGS,
1411                                  htonl(NFT_CHAIN_HW_OFFLOAD)))
1412                         goto nla_put_failure;
1413         }
1414 
1415         if (nla_put_be32(skb, NFTA_CHAIN_USE, htonl(chain->use)))
1416                 goto nla_put_failure;
1417 
1418         nlmsg_end(skb, nlh);
1419         return 0;
1420 
1421 nla_put_failure:
1422         nlmsg_trim(skb, nlh);
1423         return -1;
1424 }
1425 
1426 static void nf_tables_chain_notify(const struct nft_ctx *ctx, int event)
1427 {
1428         struct sk_buff *skb;
1429         int err;
1430 
1431         if (!ctx->report &&
1432             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
1433                 return;
1434 
1435         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1436         if (skb == NULL)
1437                 goto err;
1438 
1439         err = nf_tables_fill_chain_info(skb, ctx->net, ctx->portid, ctx->seq,
1440                                         event, 0, ctx->family, ctx->table,
1441                                         ctx->chain);
1442         if (err < 0) {
1443                 kfree_skb(skb);
1444                 goto err;
1445         }
1446 
1447         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
1448                        ctx->report, GFP_KERNEL);
1449         return;
1450 err:
1451         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
1452 }
1453 
1454 static int nf_tables_dump_chains(struct sk_buff *skb,
1455                                  struct netlink_callback *cb)
1456 {
1457         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
1458         const struct nft_table *table;
1459         const struct nft_chain *chain;
1460         unsigned int idx = 0, s_idx = cb->args[0];
1461         struct net *net = sock_net(skb->sk);
1462         int family = nfmsg->nfgen_family;
1463 
1464         rcu_read_lock();
1465         cb->seq = net->nft.base_seq;
1466 
1467         list_for_each_entry_rcu(table, &net->nft.tables, list) {
1468                 if (family != NFPROTO_UNSPEC && family != table->family)
1469                         continue;
1470 
1471                 list_for_each_entry_rcu(chain, &table->chains, list) {
1472                         if (idx < s_idx)
1473                                 goto cont;
1474                         if (idx > s_idx)
1475                                 memset(&cb->args[1], 0,
1476                                        sizeof(cb->args) - sizeof(cb->args[0]));
1477                         if (!nft_is_active(net, chain))
1478                                 continue;
1479                         if (nf_tables_fill_chain_info(skb, net,
1480                                                       NETLINK_CB(cb->skb).portid,
1481                                                       cb->nlh->nlmsg_seq,
1482                                                       NFT_MSG_NEWCHAIN,
1483                                                       NLM_F_MULTI,
1484                                                       table->family, table,
1485                                                       chain) < 0)
1486                                 goto done;
1487 
1488                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
1489 cont:
1490                         idx++;
1491                 }
1492         }
1493 done:
1494         rcu_read_unlock();
1495         cb->args[0] = idx;
1496         return skb->len;
1497 }
1498 
1499 /* called with rcu_read_lock held */
1500 static int nf_tables_getchain(struct net *net, struct sock *nlsk,
1501                               struct sk_buff *skb, const struct nlmsghdr *nlh,
1502                               const struct nlattr * const nla[],
1503                               struct netlink_ext_ack *extack)
1504 {
1505         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1506         u8 genmask = nft_genmask_cur(net);
1507         const struct nft_chain *chain;
1508         struct nft_table *table;
1509         struct sk_buff *skb2;
1510         int family = nfmsg->nfgen_family;
1511         int err;
1512 
1513         if (nlh->nlmsg_flags & NLM_F_DUMP) {
1514                 struct netlink_dump_control c = {
1515                         .dump = nf_tables_dump_chains,
1516                         .module = THIS_MODULE,
1517                 };
1518 
1519                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
1520         }
1521 
1522         table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
1523         if (IS_ERR(table)) {
1524                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1525                 return PTR_ERR(table);
1526         }
1527 
1528         chain = nft_chain_lookup(net, table, nla[NFTA_CHAIN_NAME], genmask);
1529         if (IS_ERR(chain)) {
1530                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_NAME]);
1531                 return PTR_ERR(chain);
1532         }
1533 
1534         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
1535         if (!skb2)
1536                 return -ENOMEM;
1537 
1538         err = nf_tables_fill_chain_info(skb2, net, NETLINK_CB(skb).portid,
1539                                         nlh->nlmsg_seq, NFT_MSG_NEWCHAIN, 0,
1540                                         family, table, chain);
1541         if (err < 0)
1542                 goto err;
1543 
1544         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
1545 
1546 err:
1547         kfree_skb(skb2);
1548         return err;
1549 }
1550 
1551 static const struct nla_policy nft_counter_policy[NFTA_COUNTER_MAX + 1] = {
1552         [NFTA_COUNTER_PACKETS]  = { .type = NLA_U64 },
1553         [NFTA_COUNTER_BYTES]    = { .type = NLA_U64 },
1554 };
1555 
1556 static struct nft_stats __percpu *nft_stats_alloc(const struct nlattr *attr)
1557 {
1558         struct nlattr *tb[NFTA_COUNTER_MAX+1];
1559         struct nft_stats __percpu *newstats;
1560         struct nft_stats *stats;
1561         int err;
1562 
1563         err = nla_parse_nested_deprecated(tb, NFTA_COUNTER_MAX, attr,
1564                                           nft_counter_policy, NULL);
1565         if (err < 0)
1566                 return ERR_PTR(err);
1567 
1568         if (!tb[NFTA_COUNTER_BYTES] || !tb[NFTA_COUNTER_PACKETS])
1569                 return ERR_PTR(-EINVAL);
1570 
1571         newstats = netdev_alloc_pcpu_stats(struct nft_stats);
1572         if (newstats == NULL)
1573                 return ERR_PTR(-ENOMEM);
1574 
1575         /* Restore old counters on this cpu, no problem. Per-cpu statistics
1576          * are not exposed to userspace.
1577          */
1578         preempt_disable();
1579         stats = this_cpu_ptr(newstats);
1580         stats->bytes = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_BYTES]));
1581         stats->pkts = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_PACKETS]));
1582         preempt_enable();
1583 
1584         return newstats;
1585 }
1586 
1587 static void nft_chain_stats_replace(struct nft_trans *trans)
1588 {
1589         struct nft_base_chain *chain = nft_base_chain(trans->ctx.chain);
1590 
1591         if (!nft_trans_chain_stats(trans))
1592                 return;
1593 
1594         nft_trans_chain_stats(trans) =
1595                 rcu_replace_pointer(chain->stats, nft_trans_chain_stats(trans),
1596                                     lockdep_commit_lock_is_held(trans->ctx.net));
1597 
1598         if (!nft_trans_chain_stats(trans))
1599                 static_branch_inc(&nft_counters_enabled);
1600 }
1601 
1602 static void nf_tables_chain_free_chain_rules(struct nft_chain *chain)
1603 {
1604         struct nft_rule **g0 = rcu_dereference_raw(chain->rules_gen_0);
1605         struct nft_rule **g1 = rcu_dereference_raw(chain->rules_gen_1);
1606 
1607         if (g0 != g1)
1608                 kvfree(g1);
1609         kvfree(g0);
1610 
1611         /* should be NULL either via abort or via successful commit */
1612         WARN_ON_ONCE(chain->rules_next);
1613         kvfree(chain->rules_next);
1614 }
1615 
1616 static void nf_tables_chain_destroy(struct nft_ctx *ctx)
1617 {
1618         struct nft_chain *chain = ctx->chain;
1619         struct nft_hook *hook, *next;
1620 
1621         if (WARN_ON(chain->use > 0))
1622                 return;
1623 
1624         /* no concurrent access possible anymore */
1625         nf_tables_chain_free_chain_rules(chain);
1626 
1627         if (nft_is_base_chain(chain)) {
1628                 struct nft_base_chain *basechain = nft_base_chain(chain);
1629 
1630                 if (ctx->family == NFPROTO_NETDEV) {
1631                         list_for_each_entry_safe(hook, next,
1632                                                  &basechain->hook_list, list) {
1633                                 list_del_rcu(&hook->list);
1634                                 kfree_rcu(hook, rcu);
1635                         }
1636                 }
1637                 module_put(basechain->type->owner);
1638                 if (rcu_access_pointer(basechain->stats)) {
1639                         static_branch_dec(&nft_counters_enabled);
1640                         free_percpu(rcu_dereference_raw(basechain->stats));
1641                 }
1642                 kfree(chain->name);
1643                 kfree(basechain);
1644         } else {
1645                 kfree(chain->name);
1646                 kfree(chain);
1647         }
1648 }
1649 
1650 static struct nft_hook *nft_netdev_hook_alloc(struct net *net,
1651                                               const struct nlattr *attr)
1652 {
1653         struct net_device *dev;
1654         char ifname[IFNAMSIZ];
1655         struct nft_hook *hook;
1656         int err;
1657 
1658         hook = kmalloc(sizeof(struct nft_hook), GFP_KERNEL);
1659         if (!hook) {
1660                 err = -ENOMEM;
1661                 goto err_hook_alloc;
1662         }
1663 
1664         nla_strlcpy(ifname, attr, IFNAMSIZ);
1665         dev = __dev_get_by_name(net, ifname);
1666         if (!dev) {
1667                 err = -ENOENT;
1668                 goto err_hook_dev;
1669         }
1670         hook->ops.dev = dev;
1671 
1672         return hook;
1673 
1674 err_hook_dev:
1675         kfree(hook);
1676 err_hook_alloc:
1677         return ERR_PTR(err);
1678 }
1679 
1680 static bool nft_hook_list_find(struct list_head *hook_list,
1681                                const struct nft_hook *this)
1682 {
1683         struct nft_hook *hook;
1684 
1685         list_for_each_entry(hook, hook_list, list) {
1686                 if (this->ops.dev == hook->ops.dev)
1687                         return true;
1688         }
1689 
1690         return false;
1691 }
1692 
1693 static int nf_tables_parse_netdev_hooks(struct net *net,
1694                                         const struct nlattr *attr,
1695                                         struct list_head *hook_list)
1696 {
1697         struct nft_hook *hook, *next;
1698         const struct nlattr *tmp;
1699         int rem, n = 0, err;
1700 
1701         nla_for_each_nested(tmp, attr, rem) {
1702                 if (nla_type(tmp) != NFTA_DEVICE_NAME) {
1703                         err = -EINVAL;
1704                         goto err_hook;
1705                 }
1706 
1707                 hook = nft_netdev_hook_alloc(net, tmp);
1708                 if (IS_ERR(hook)) {
1709                         err = PTR_ERR(hook);
1710                         goto err_hook;
1711                 }
1712                 if (nft_hook_list_find(hook_list, hook)) {
1713                         kfree(hook);
1714                         err = -EEXIST;
1715                         goto err_hook;
1716                 }
1717                 list_add_tail(&hook->list, hook_list);
1718                 n++;
1719 
1720                 if (n == NFT_NETDEVICE_MAX) {
1721                         err = -EFBIG;
1722                         goto err_hook;
1723                 }
1724         }
1725         if (!n)
1726                 return -EINVAL;
1727 
1728         return 0;
1729 
1730 err_hook:
1731         list_for_each_entry_safe(hook, next, hook_list, list) {
1732                 list_del(&hook->list);
1733                 kfree(hook);
1734         }
1735         return err;
1736 }
1737 
1738 struct nft_chain_hook {
1739         u32                             num;
1740         s32                             priority;
1741         const struct nft_chain_type     *type;
1742         struct list_head                list;
1743 };
1744 
1745 static int nft_chain_parse_netdev(struct net *net,
1746                                   struct nlattr *tb[],
1747                                   struct list_head *hook_list)
1748 {
1749         struct nft_hook *hook;
1750         int err;
1751 
1752         if (tb[NFTA_HOOK_DEV]) {
1753                 hook = nft_netdev_hook_alloc(net, tb[NFTA_HOOK_DEV]);
1754                 if (IS_ERR(hook))
1755                         return PTR_ERR(hook);
1756 
1757                 list_add_tail(&hook->list, hook_list);
1758         } else if (tb[NFTA_HOOK_DEVS]) {
1759                 err = nf_tables_parse_netdev_hooks(net, tb[NFTA_HOOK_DEVS],
1760                                                    hook_list);
1761                 if (err < 0)
1762                         return err;
1763         } else {
1764                 return -EINVAL;
1765         }
1766 
1767         return 0;
1768 }
1769 
1770 static int nft_chain_parse_hook(struct net *net,
1771                                 const struct nlattr * const nla[],
1772                                 struct nft_chain_hook *hook, u8 family,
1773                                 bool autoload)
1774 {
1775         struct nlattr *ha[NFTA_HOOK_MAX + 1];
1776         const struct nft_chain_type *type;
1777         int err;
1778 
1779         lockdep_assert_held(&net->nft.commit_mutex);
1780         lockdep_nfnl_nft_mutex_not_held();
1781 
1782         err = nla_parse_nested_deprecated(ha, NFTA_HOOK_MAX,
1783                                           nla[NFTA_CHAIN_HOOK],
1784                                           nft_hook_policy, NULL);
1785         if (err < 0)
1786                 return err;
1787 
1788         if (ha[NFTA_HOOK_HOOKNUM] == NULL ||
1789             ha[NFTA_HOOK_PRIORITY] == NULL)
1790                 return -EINVAL;
1791 
1792         hook->num = ntohl(nla_get_be32(ha[NFTA_HOOK_HOOKNUM]));
1793         hook->priority = ntohl(nla_get_be32(ha[NFTA_HOOK_PRIORITY]));
1794 
1795         type = __nft_chain_type_get(family, NFT_CHAIN_T_DEFAULT);
1796         if (!type)
1797                 return -EOPNOTSUPP;
1798 
1799         if (nla[NFTA_CHAIN_TYPE]) {
1800                 type = nf_tables_chain_type_lookup(net, nla[NFTA_CHAIN_TYPE],
1801                                                    family, autoload);
1802                 if (IS_ERR(type))
1803                         return PTR_ERR(type);
1804         }
1805         if (hook->num > NF_MAX_HOOKS || !(type->hook_mask & (1 << hook->num)))
1806                 return -EOPNOTSUPP;
1807 
1808         if (type->type == NFT_CHAIN_T_NAT &&
1809             hook->priority <= NF_IP_PRI_CONNTRACK)
1810                 return -EOPNOTSUPP;
1811 
1812         if (!try_module_get(type->owner))
1813                 return -ENOENT;
1814 
1815         hook->type = type;
1816 
1817         INIT_LIST_HEAD(&hook->list);
1818         if (family == NFPROTO_NETDEV) {
1819                 err = nft_chain_parse_netdev(net, ha, &hook->list);
1820                 if (err < 0) {
1821                         module_put(type->owner);
1822                         return err;
1823                 }
1824         } else if (ha[NFTA_HOOK_DEV] || ha[NFTA_HOOK_DEVS]) {
1825                 module_put(type->owner);
1826                 return -EOPNOTSUPP;
1827         }
1828 
1829         return 0;
1830 }
1831 
1832 static void nft_chain_release_hook(struct nft_chain_hook *hook)
1833 {
1834         struct nft_hook *h, *next;
1835 
1836         list_for_each_entry_safe(h, next, &hook->list, list) {
1837                 list_del(&h->list);
1838                 kfree(h);
1839         }
1840         module_put(hook->type->owner);
1841 }
1842 
1843 struct nft_rules_old {
1844         struct rcu_head h;
1845         struct nft_rule **start;
1846 };
1847 
1848 static struct nft_rule **nf_tables_chain_alloc_rules(const struct nft_chain *chain,
1849                                                      unsigned int alloc)
1850 {
1851         if (alloc > INT_MAX)
1852                 return NULL;
1853 
1854         alloc += 1;     /* NULL, ends rules */
1855         if (sizeof(struct nft_rule *) > INT_MAX / alloc)
1856                 return NULL;
1857 
1858         alloc *= sizeof(struct nft_rule *);
1859         alloc += sizeof(struct nft_rules_old);
1860 
1861         return kvmalloc(alloc, GFP_KERNEL);
1862 }
1863 
1864 static void nft_basechain_hook_init(struct nf_hook_ops *ops, u8 family,
1865                                     const struct nft_chain_hook *hook,
1866                                     struct nft_chain *chain)
1867 {
1868         ops->pf         = family;
1869         ops->hooknum    = hook->num;
1870         ops->priority   = hook->priority;
1871         ops->priv       = chain;
1872         ops->hook       = hook->type->hooks[ops->hooknum];
1873 }
1874 
1875 static int nft_basechain_init(struct nft_base_chain *basechain, u8 family,
1876                               struct nft_chain_hook *hook, u32 flags)
1877 {
1878         struct nft_chain *chain;
1879         struct nft_hook *h;
1880 
1881         basechain->type = hook->type;
1882         INIT_LIST_HEAD(&basechain->hook_list);
1883         chain = &basechain->chain;
1884 
1885         if (family == NFPROTO_NETDEV) {
1886                 list_splice_init(&hook->list, &basechain->hook_list);
1887                 list_for_each_entry(h, &basechain->hook_list, list)
1888                         nft_basechain_hook_init(&h->ops, family, hook, chain);
1889 
1890                 basechain->ops.hooknum  = hook->num;
1891                 basechain->ops.priority = hook->priority;
1892         } else {
1893                 nft_basechain_hook_init(&basechain->ops, family, hook, chain);
1894         }
1895 
1896         chain->flags |= NFT_BASE_CHAIN | flags;
1897         basechain->policy = NF_ACCEPT;
1898         if (chain->flags & NFT_CHAIN_HW_OFFLOAD &&
1899             nft_chain_offload_priority(basechain) < 0)
1900                 return -EOPNOTSUPP;
1901 
1902         flow_block_init(&basechain->flow_block);
1903 
1904         return 0;
1905 }
1906 
1907 static int nf_tables_addchain(struct nft_ctx *ctx, u8 family, u8 genmask,
1908                               u8 policy, u32 flags)
1909 {
1910         const struct nlattr * const *nla = ctx->nla;
1911         struct nft_table *table = ctx->table;
1912         struct nft_base_chain *basechain;
1913         struct nft_stats __percpu *stats;
1914         struct net *net = ctx->net;
1915         struct nft_trans *trans;
1916         struct nft_chain *chain;
1917         struct nft_rule **rules;
1918         int err;
1919 
1920         if (table->use == UINT_MAX)
1921                 return -EOVERFLOW;
1922 
1923         if (nla[NFTA_CHAIN_HOOK]) {
1924                 struct nft_chain_hook hook;
1925 
1926                 err = nft_chain_parse_hook(net, nla, &hook, family, true);
1927                 if (err < 0)
1928                         return err;
1929 
1930                 basechain = kzalloc(sizeof(*basechain), GFP_KERNEL);
1931                 if (basechain == NULL) {
1932                         nft_chain_release_hook(&hook);
1933                         return -ENOMEM;
1934                 }
1935                 chain = &basechain->chain;
1936 
1937                 if (nla[NFTA_CHAIN_COUNTERS]) {
1938                         stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
1939                         if (IS_ERR(stats)) {
1940                                 nft_chain_release_hook(&hook);
1941                                 kfree(basechain);
1942                                 return PTR_ERR(stats);
1943                         }
1944                         rcu_assign_pointer(basechain->stats, stats);
1945                         static_branch_inc(&nft_counters_enabled);
1946                 }
1947 
1948                 err = nft_basechain_init(basechain, family, &hook, flags);
1949                 if (err < 0) {
1950                         nft_chain_release_hook(&hook);
1951                         kfree(basechain);
1952                         return err;
1953                 }
1954         } else {
1955                 chain = kzalloc(sizeof(*chain), GFP_KERNEL);
1956                 if (chain == NULL)
1957                         return -ENOMEM;
1958         }
1959         ctx->chain = chain;
1960 
1961         INIT_LIST_HEAD(&chain->rules);
1962         chain->handle = nf_tables_alloc_handle(table);
1963         chain->table = table;
1964         chain->name = nla_strdup(nla[NFTA_CHAIN_NAME], GFP_KERNEL);
1965         if (!chain->name) {
1966                 err = -ENOMEM;
1967                 goto err1;
1968         }
1969 
1970         rules = nf_tables_chain_alloc_rules(chain, 0);
1971         if (!rules) {
1972                 err = -ENOMEM;
1973                 goto err1;
1974         }
1975 
1976         *rules = NULL;
1977         rcu_assign_pointer(chain->rules_gen_0, rules);
1978         rcu_assign_pointer(chain->rules_gen_1, rules);
1979 
1980         err = nf_tables_register_hook(net, table, chain);
1981         if (err < 0)
1982                 goto err1;
1983 
1984         err = rhltable_insert_key(&table->chains_ht, chain->name,
1985                                   &chain->rhlhead, nft_chain_ht_params);
1986         if (err)
1987                 goto err2;
1988 
1989         trans = nft_trans_chain_add(ctx, NFT_MSG_NEWCHAIN);
1990         if (IS_ERR(trans)) {
1991                 err = PTR_ERR(trans);
1992                 rhltable_remove(&table->chains_ht, &chain->rhlhead,
1993                                 nft_chain_ht_params);
1994                 goto err2;
1995         }
1996 
1997         nft_trans_chain_policy(trans) = NFT_CHAIN_POLICY_UNSET;
1998         if (nft_is_base_chain(chain))
1999                 nft_trans_chain_policy(trans) = policy;
2000 
2001         table->use++;
2002         list_add_tail_rcu(&chain->list, &table->chains);
2003 
2004         return 0;
2005 err2:
2006         nf_tables_unregister_hook(net, table, chain);
2007 err1:
2008         nf_tables_chain_destroy(ctx);
2009 
2010         return err;
2011 }
2012 
2013 static bool nft_hook_list_equal(struct list_head *hook_list1,
2014                                 struct list_head *hook_list2)
2015 {
2016         struct nft_hook *hook;
2017         int n = 0, m = 0;
2018 
2019         n = 0;
2020         list_for_each_entry(hook, hook_list2, list) {
2021                 if (!nft_hook_list_find(hook_list1, hook))
2022                         return false;
2023 
2024                 n++;
2025         }
2026         list_for_each_entry(hook, hook_list1, list)
2027                 m++;
2028 
2029         return n == m;
2030 }
2031 
2032 static int nf_tables_updchain(struct nft_ctx *ctx, u8 genmask, u8 policy,
2033                               u32 flags)
2034 {
2035         const struct nlattr * const *nla = ctx->nla;
2036         struct nft_table *table = ctx->table;
2037         struct nft_chain *chain = ctx->chain;
2038         struct nft_base_chain *basechain;
2039         struct nft_stats *stats = NULL;
2040         struct nft_chain_hook hook;
2041         struct nf_hook_ops *ops;
2042         struct nft_trans *trans;
2043         int err;
2044 
2045         if (chain->flags ^ flags)
2046                 return -EOPNOTSUPP;
2047 
2048         if (nla[NFTA_CHAIN_HOOK]) {
2049                 if (!nft_is_base_chain(chain))
2050                         return -EBUSY;
2051 
2052                 err = nft_chain_parse_hook(ctx->net, nla, &hook, ctx->family,
2053                                            false);
2054                 if (err < 0)
2055                         return err;
2056 
2057                 basechain = nft_base_chain(chain);
2058                 if (basechain->type != hook.type) {
2059                         nft_chain_release_hook(&hook);
2060                         return -EBUSY;
2061                 }
2062 
2063                 if (ctx->family == NFPROTO_NETDEV) {
2064                         if (!nft_hook_list_equal(&basechain->hook_list,
2065                                                  &hook.list)) {
2066                                 nft_chain_release_hook(&hook);
2067                                 return -EBUSY;
2068                         }
2069                 } else {
2070                         ops = &basechain->ops;
2071                         if (ops->hooknum != hook.num ||
2072                             ops->priority != hook.priority) {
2073                                 nft_chain_release_hook(&hook);
2074                                 return -EBUSY;
2075                         }
2076                 }
2077                 nft_chain_release_hook(&hook);
2078         }
2079 
2080         if (nla[NFTA_CHAIN_HANDLE] &&
2081             nla[NFTA_CHAIN_NAME]) {
2082                 struct nft_chain *chain2;
2083 
2084                 chain2 = nft_chain_lookup(ctx->net, table,
2085                                           nla[NFTA_CHAIN_NAME], genmask);
2086                 if (!IS_ERR(chain2))
2087                         return -EEXIST;
2088         }
2089 
2090         if (nla[NFTA_CHAIN_COUNTERS]) {
2091                 if (!nft_is_base_chain(chain))
2092                         return -EOPNOTSUPP;
2093 
2094                 stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
2095                 if (IS_ERR(stats))
2096                         return PTR_ERR(stats);
2097         }
2098 
2099         err = -ENOMEM;
2100         trans = nft_trans_alloc(ctx, NFT_MSG_NEWCHAIN,
2101                                 sizeof(struct nft_trans_chain));
2102         if (trans == NULL)
2103                 goto err;
2104 
2105         nft_trans_chain_stats(trans) = stats;
2106         nft_trans_chain_update(trans) = true;
2107 
2108         if (nla[NFTA_CHAIN_POLICY])
2109                 nft_trans_chain_policy(trans) = policy;
2110         else
2111                 nft_trans_chain_policy(trans) = -1;
2112 
2113         if (nla[NFTA_CHAIN_HANDLE] &&
2114             nla[NFTA_CHAIN_NAME]) {
2115                 struct nft_trans *tmp;
2116                 char *name;
2117 
2118                 err = -ENOMEM;
2119                 name = nla_strdup(nla[NFTA_CHAIN_NAME], GFP_KERNEL);
2120                 if (!name)
2121                         goto err;
2122 
2123                 err = -EEXIST;
2124                 list_for_each_entry(tmp, &ctx->net->nft.commit_list, list) {
2125                         if (tmp->msg_type == NFT_MSG_NEWCHAIN &&
2126                             tmp->ctx.table == table &&
2127                             nft_trans_chain_update(tmp) &&
2128                             nft_trans_chain_name(tmp) &&
2129                             strcmp(name, nft_trans_chain_name(tmp)) == 0) {
2130                                 kfree(name);
2131                                 goto err;
2132                         }
2133                 }
2134 
2135                 nft_trans_chain_name(trans) = name;
2136         }
2137         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
2138 
2139         return 0;
2140 err:
2141         free_percpu(stats);
2142         kfree(trans);
2143         return err;
2144 }
2145 
2146 static int nf_tables_newchain(struct net *net, struct sock *nlsk,
2147                               struct sk_buff *skb, const struct nlmsghdr *nlh,
2148                               const struct nlattr * const nla[],
2149                               struct netlink_ext_ack *extack)
2150 {
2151         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2152         u8 genmask = nft_genmask_next(net);
2153         int family = nfmsg->nfgen_family;
2154         const struct nlattr *attr;
2155         struct nft_table *table;
2156         struct nft_chain *chain;
2157         u8 policy = NF_ACCEPT;
2158         struct nft_ctx ctx;
2159         u64 handle = 0;
2160         u32 flags = 0;
2161 
2162         lockdep_assert_held(&net->nft.commit_mutex);
2163 
2164         table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
2165         if (IS_ERR(table)) {
2166                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
2167                 return PTR_ERR(table);
2168         }
2169 
2170         chain = NULL;
2171         attr = nla[NFTA_CHAIN_NAME];
2172 
2173         if (nla[NFTA_CHAIN_HANDLE]) {
2174                 handle = be64_to_cpu(nla_get_be64(nla[NFTA_CHAIN_HANDLE]));
2175                 chain = nft_chain_lookup_byhandle(table, handle, genmask);
2176                 if (IS_ERR(chain)) {
2177                         NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_HANDLE]);
2178                         return PTR_ERR(chain);
2179                 }
2180                 attr = nla[NFTA_CHAIN_HANDLE];
2181         } else {
2182                 chain = nft_chain_lookup(net, table, attr, genmask);
2183                 if (IS_ERR(chain)) {
2184                         if (PTR_ERR(chain) != -ENOENT) {
2185                                 NL_SET_BAD_ATTR(extack, attr);
2186                                 return PTR_ERR(chain);
2187                         }
2188                         chain = NULL;
2189                 }
2190         }
2191 
2192         if (nla[NFTA_CHAIN_POLICY]) {
2193                 if (chain != NULL &&
2194                     !nft_is_base_chain(chain)) {
2195                         NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_POLICY]);
2196                         return -EOPNOTSUPP;
2197                 }
2198 
2199                 if (chain == NULL &&
2200                     nla[NFTA_CHAIN_HOOK] == NULL) {
2201                         NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_POLICY]);
2202                         return -EOPNOTSUPP;
2203                 }
2204 
2205                 policy = ntohl(nla_get_be32(nla[NFTA_CHAIN_POLICY]));
2206                 switch (policy) {
2207                 case NF_DROP:
2208                 case NF_ACCEPT:
2209                         break;
2210                 default:
2211                         return -EINVAL;
2212                 }
2213         }
2214 
2215         if (nla[NFTA_CHAIN_FLAGS])
2216                 flags = ntohl(nla_get_be32(nla[NFTA_CHAIN_FLAGS]));
2217         else if (chain)
2218                 flags = chain->flags;
2219 
2220         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
2221 
2222         if (chain != NULL) {
2223                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
2224                         NL_SET_BAD_ATTR(extack, attr);
2225                         return -EEXIST;
2226                 }
2227                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
2228                         return -EOPNOTSUPP;
2229 
2230                 flags |= chain->flags & NFT_BASE_CHAIN;
2231                 return nf_tables_updchain(&ctx, genmask, policy, flags);
2232         }
2233 
2234         return nf_tables_addchain(&ctx, family, genmask, policy, flags);
2235 }
2236 
2237 static int nf_tables_delchain(struct net *net, struct sock *nlsk,
2238                               struct sk_buff *skb, const struct nlmsghdr *nlh,
2239                               const struct nlattr * const nla[],
2240                               struct netlink_ext_ack *extack)
2241 {
2242         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2243         u8 genmask = nft_genmask_next(net);
2244         int family = nfmsg->nfgen_family;
2245         const struct nlattr *attr;
2246         struct nft_table *table;
2247         struct nft_chain *chain;
2248         struct nft_rule *rule;
2249         struct nft_ctx ctx;
2250         u64 handle;
2251         u32 use;
2252         int err;
2253 
2254         table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
2255         if (IS_ERR(table)) {
2256                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
2257                 return PTR_ERR(table);
2258         }
2259 
2260         if (nla[NFTA_CHAIN_HANDLE]) {
2261                 attr = nla[NFTA_CHAIN_HANDLE];
2262                 handle = be64_to_cpu(nla_get_be64(attr));
2263                 chain = nft_chain_lookup_byhandle(table, handle, genmask);
2264         } else {
2265                 attr = nla[NFTA_CHAIN_NAME];
2266                 chain = nft_chain_lookup(net, table, attr, genmask);
2267         }
2268         if (IS_ERR(chain)) {
2269                 NL_SET_BAD_ATTR(extack, attr);
2270                 return PTR_ERR(chain);
2271         }
2272 
2273         if (nlh->nlmsg_flags & NLM_F_NONREC &&
2274             chain->use > 0)
2275                 return -EBUSY;
2276 
2277         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
2278 
2279         use = chain->use;
2280         list_for_each_entry(rule, &chain->rules, list) {
2281                 if (!nft_is_active_next(net, rule))
2282                         continue;
2283                 use--;
2284 
2285                 err = nft_delrule(&ctx, rule);
2286                 if (err < 0)
2287                         return err;
2288         }
2289 
2290         /* There are rules and elements that are still holding references to us,
2291          * we cannot do a recursive removal in this case.
2292          */
2293         if (use > 0) {
2294                 NL_SET_BAD_ATTR(extack, attr);
2295                 return -EBUSY;
2296         }
2297 
2298         return nft_delchain(&ctx);
2299 }
2300 
2301 /*
2302  * Expressions
2303  */
2304 
2305 /**
2306  *      nft_register_expr - register nf_tables expr type
2307  *      @ops: expr type
2308  *
2309  *      Registers the expr type for use with nf_tables. Returns zero on
2310  *      success or a negative errno code otherwise.
2311  */
2312 int nft_register_expr(struct nft_expr_type *type)
2313 {
2314         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2315         if (type->family == NFPROTO_UNSPEC)
2316                 list_add_tail_rcu(&type->list, &nf_tables_expressions);
2317         else
2318                 list_add_rcu(&type->list, &nf_tables_expressions);
2319         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2320         return 0;
2321 }
2322 EXPORT_SYMBOL_GPL(nft_register_expr);
2323 
2324 /**
2325  *      nft_unregister_expr - unregister nf_tables expr type
2326  *      @ops: expr type
2327  *
2328  *      Unregisters the expr typefor use with nf_tables.
2329  */
2330 void nft_unregister_expr(struct nft_expr_type *type)
2331 {
2332         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2333         list_del_rcu(&type->list);
2334         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2335 }
2336 EXPORT_SYMBOL_GPL(nft_unregister_expr);
2337 
2338 static const struct nft_expr_type *__nft_expr_type_get(u8 family,
2339                                                        struct nlattr *nla)
2340 {
2341         const struct nft_expr_type *type, *candidate = NULL;
2342 
2343         list_for_each_entry(type, &nf_tables_expressions, list) {
2344                 if (!nla_strcmp(nla, type->name)) {
2345                         if (!type->family && !candidate)
2346                                 candidate = type;
2347                         else if (type->family == family)
2348                                 candidate = type;
2349                 }
2350         }
2351         return candidate;
2352 }
2353 
2354 #ifdef CONFIG_MODULES
2355 static int nft_expr_type_request_module(struct net *net, u8 family,
2356                                         struct nlattr *nla)
2357 {
2358         if (nft_request_module(net, "nft-expr-%u-%.*s", family,
2359                                nla_len(nla), (char *)nla_data(nla)) == -EAGAIN)
2360                 return -EAGAIN;
2361 
2362         return 0;
2363 }
2364 #endif
2365 
2366 static const struct nft_expr_type *nft_expr_type_get(struct net *net,
2367                                                      u8 family,
2368                                                      struct nlattr *nla)
2369 {
2370         const struct nft_expr_type *type;
2371 
2372         if (nla == NULL)
2373                 return ERR_PTR(-EINVAL);
2374 
2375         type = __nft_expr_type_get(family, nla);
2376         if (type != NULL && try_module_get(type->owner))
2377                 return type;
2378 
2379         lockdep_nfnl_nft_mutex_not_held();
2380 #ifdef CONFIG_MODULES
2381         if (type == NULL) {
2382                 if (nft_expr_type_request_module(net, family, nla) == -EAGAIN)
2383                         return ERR_PTR(-EAGAIN);
2384 
2385                 if (nft_request_module(net, "nft-expr-%.*s",
2386                                        nla_len(nla),
2387                                        (char *)nla_data(nla)) == -EAGAIN)
2388                         return ERR_PTR(-EAGAIN);
2389         }
2390 #endif
2391         return ERR_PTR(-ENOENT);
2392 }
2393 
2394 static const struct nla_policy nft_expr_policy[NFTA_EXPR_MAX + 1] = {
2395         [NFTA_EXPR_NAME]        = { .type = NLA_STRING,
2396                                     .len = NFT_MODULE_AUTOLOAD_LIMIT },
2397         [NFTA_EXPR_DATA]        = { .type = NLA_NESTED },
2398 };
2399 
2400 static int nf_tables_fill_expr_info(struct sk_buff *skb,
2401                                     const struct nft_expr *expr)
2402 {
2403         if (nla_put_string(skb, NFTA_EXPR_NAME, expr->ops->type->name))
2404                 goto nla_put_failure;
2405 
2406         if (expr->ops->dump) {
2407                 struct nlattr *data = nla_nest_start_noflag(skb,
2408                                                             NFTA_EXPR_DATA);
2409                 if (data == NULL)
2410                         goto nla_put_failure;
2411                 if (expr->ops->dump(skb, expr) < 0)
2412                         goto nla_put_failure;
2413                 nla_nest_end(skb, data);
2414         }
2415 
2416         return skb->len;
2417 
2418 nla_put_failure:
2419         return -1;
2420 };
2421 
2422 int nft_expr_dump(struct sk_buff *skb, unsigned int attr,
2423                   const struct nft_expr *expr)
2424 {
2425         struct nlattr *nest;
2426 
2427         nest = nla_nest_start_noflag(skb, attr);
2428         if (!nest)
2429                 goto nla_put_failure;
2430         if (nf_tables_fill_expr_info(skb, expr) < 0)
2431                 goto nla_put_failure;
2432         nla_nest_end(skb, nest);
2433         return 0;
2434 
2435 nla_put_failure:
2436         return -1;
2437 }
2438 
2439 struct nft_expr_info {
2440         const struct nft_expr_ops       *ops;
2441         struct nlattr                   *tb[NFT_EXPR_MAXATTR + 1];
2442 };
2443 
2444 static int nf_tables_expr_parse(const struct nft_ctx *ctx,
2445                                 const struct nlattr *nla,
2446                                 struct nft_expr_info *info)
2447 {
2448         const struct nft_expr_type *type;
2449         const struct nft_expr_ops *ops;
2450         struct nlattr *tb[NFTA_EXPR_MAX + 1];
2451         int err;
2452 
2453         err = nla_parse_nested_deprecated(tb, NFTA_EXPR_MAX, nla,
2454                                           nft_expr_policy, NULL);
2455         if (err < 0)
2456                 return err;
2457 
2458         type = nft_expr_type_get(ctx->net, ctx->family, tb[NFTA_EXPR_NAME]);
2459         if (IS_ERR(type))
2460                 return PTR_ERR(type);
2461 
2462         if (tb[NFTA_EXPR_DATA]) {
2463                 err = nla_parse_nested_deprecated(info->tb, type->maxattr,
2464                                                   tb[NFTA_EXPR_DATA],
2465                                                   type->policy, NULL);
2466                 if (err < 0)
2467                         goto err1;
2468         } else
2469                 memset(info->tb, 0, sizeof(info->tb[0]) * (type->maxattr + 1));
2470 
2471         if (type->select_ops != NULL) {
2472                 ops = type->select_ops(ctx,
2473                                        (const struct nlattr * const *)info->tb);
2474                 if (IS_ERR(ops)) {
2475                         err = PTR_ERR(ops);
2476 #ifdef CONFIG_MODULES
2477                         if (err == -EAGAIN)
2478                                 if (nft_expr_type_request_module(ctx->net,
2479                                                                  ctx->family,
2480                                                                  tb[NFTA_EXPR_NAME]) != -EAGAIN)
2481                                         err = -ENOENT;
2482 #endif
2483                         goto err1;
2484                 }
2485         } else
2486                 ops = type->ops;
2487 
2488         info->ops = ops;
2489         return 0;
2490 
2491 err1:
2492         module_put(type->owner);
2493         return err;
2494 }
2495 
2496 static int nf_tables_newexpr(const struct nft_ctx *ctx,
2497                              const struct nft_expr_info *info,
2498                              struct nft_expr *expr)
2499 {
2500         const struct nft_expr_ops *ops = info->ops;
2501         int err;
2502 
2503         expr->ops = ops;
2504         if (ops->init) {
2505                 err = ops->init(ctx, expr, (const struct nlattr **)info->tb);
2506                 if (err < 0)
2507                         goto err1;
2508         }
2509 
2510         return 0;
2511 err1:
2512         expr->ops = NULL;
2513         return err;
2514 }
2515 
2516 static void nf_tables_expr_destroy(const struct nft_ctx *ctx,
2517                                    struct nft_expr *expr)
2518 {
2519         const struct nft_expr_type *type = expr->ops->type;
2520 
2521         if (expr->ops->destroy)
2522                 expr->ops->destroy(ctx, expr);
2523         module_put(type->owner);
2524 }
2525 
2526 struct nft_expr *nft_expr_init(const struct nft_ctx *ctx,
2527                                const struct nlattr *nla)
2528 {
2529         struct nft_expr_info info;
2530         struct nft_expr *expr;
2531         struct module *owner;
2532         int err;
2533 
2534         err = nf_tables_expr_parse(ctx, nla, &info);
2535         if (err < 0)
2536                 goto err1;
2537 
2538         err = -ENOMEM;
2539         expr = kzalloc(info.ops->size, GFP_KERNEL);
2540         if (expr == NULL)
2541                 goto err2;
2542 
2543         err = nf_tables_newexpr(ctx, &info, expr);
2544         if (err < 0)
2545                 goto err3;
2546 
2547         return expr;
2548 err3:
2549         kfree(expr);
2550 err2:
2551         owner = info.ops->type->owner;
2552         if (info.ops->type->release_ops)
2553                 info.ops->type->release_ops(info.ops);
2554 
2555         module_put(owner);
2556 err1:
2557         return ERR_PTR(err);
2558 }
2559 
2560 void nft_expr_destroy(const struct nft_ctx *ctx, struct nft_expr *expr)
2561 {
2562         nf_tables_expr_destroy(ctx, expr);
2563         kfree(expr);
2564 }
2565 
2566 /*
2567  * Rules
2568  */
2569 
2570 static struct nft_rule *__nft_rule_lookup(const struct nft_chain *chain,
2571                                           u64 handle)
2572 {
2573         struct nft_rule *rule;
2574 
2575         // FIXME: this sucks
2576         list_for_each_entry_rcu(rule, &chain->rules, list) {
2577                 if (handle == rule->handle)
2578                         return rule;
2579         }
2580 
2581         return ERR_PTR(-ENOENT);
2582 }
2583 
2584 static struct nft_rule *nft_rule_lookup(const struct nft_chain *chain,
2585                                         const struct nlattr *nla)
2586 {
2587         if (nla == NULL)
2588                 return ERR_PTR(-EINVAL);
2589 
2590         return __nft_rule_lookup(chain, be64_to_cpu(nla_get_be64(nla)));
2591 }
2592 
2593 static const struct nla_policy nft_rule_policy[NFTA_RULE_MAX + 1] = {
2594         [NFTA_RULE_TABLE]       = { .type = NLA_STRING,
2595                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
2596         [NFTA_RULE_CHAIN]       = { .type = NLA_STRING,
2597                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
2598         [NFTA_RULE_HANDLE]      = { .type = NLA_U64 },
2599         [NFTA_RULE_EXPRESSIONS] = { .type = NLA_NESTED },
2600         [NFTA_RULE_COMPAT]      = { .type = NLA_NESTED },
2601         [NFTA_RULE_POSITION]    = { .type = NLA_U64 },
2602         [NFTA_RULE_USERDATA]    = { .type = NLA_BINARY,
2603                                     .len = NFT_USERDATA_MAXLEN },
2604         [NFTA_RULE_ID]          = { .type = NLA_U32 },
2605         [NFTA_RULE_POSITION_ID] = { .type = NLA_U32 },
2606 };
2607 
2608 static int nf_tables_fill_rule_info(struct sk_buff *skb, struct net *net,
2609                                     u32 portid, u32 seq, int event,
2610                                     u32 flags, int family,
2611                                     const struct nft_table *table,
2612                                     const struct nft_chain *chain,
2613                                     const struct nft_rule *rule,
2614                                     const struct nft_rule *prule)
2615 {
2616         struct nlmsghdr *nlh;
2617         struct nfgenmsg *nfmsg;
2618         const struct nft_expr *expr, *next;
2619         struct nlattr *list;
2620         u16 type = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
2621 
2622         nlh = nlmsg_put(skb, portid, seq, type, sizeof(struct nfgenmsg), flags);
2623         if (nlh == NULL)
2624                 goto nla_put_failure;
2625 
2626         nfmsg = nlmsg_data(nlh);
2627         nfmsg->nfgen_family     = family;
2628         nfmsg->version          = NFNETLINK_V0;
2629         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
2630 
2631         if (nla_put_string(skb, NFTA_RULE_TABLE, table->name))
2632                 goto nla_put_failure;
2633         if (nla_put_string(skb, NFTA_RULE_CHAIN, chain->name))
2634                 goto nla_put_failure;
2635         if (nla_put_be64(skb, NFTA_RULE_HANDLE, cpu_to_be64(rule->handle),
2636                          NFTA_RULE_PAD))
2637                 goto nla_put_failure;
2638 
2639         if (event != NFT_MSG_DELRULE && prule) {
2640                 if (nla_put_be64(skb, NFTA_RULE_POSITION,
2641                                  cpu_to_be64(prule->handle),
2642                                  NFTA_RULE_PAD))
2643                         goto nla_put_failure;
2644         }
2645 
2646         list = nla_nest_start_noflag(skb, NFTA_RULE_EXPRESSIONS);
2647         if (list == NULL)
2648                 goto nla_put_failure;
2649         nft_rule_for_each_expr(expr, next, rule) {
2650                 if (nft_expr_dump(skb, NFTA_LIST_ELEM, expr) < 0)
2651                         goto nla_put_failure;
2652         }
2653         nla_nest_end(skb, list);
2654 
2655         if (rule->udata) {
2656                 struct nft_userdata *udata = nft_userdata(rule);
2657                 if (nla_put(skb, NFTA_RULE_USERDATA, udata->len + 1,
2658                             udata->data) < 0)
2659                         goto nla_put_failure;
2660         }
2661 
2662         nlmsg_end(skb, nlh);
2663         return 0;
2664 
2665 nla_put_failure:
2666         nlmsg_trim(skb, nlh);
2667         return -1;
2668 }
2669 
2670 static void nf_tables_rule_notify(const struct nft_ctx *ctx,
2671                                   const struct nft_rule *rule, int event)
2672 {
2673         struct sk_buff *skb;
2674         int err;
2675 
2676         if (!ctx->report &&
2677             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
2678                 return;
2679 
2680         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
2681         if (skb == NULL)
2682                 goto err;
2683 
2684         err = nf_tables_fill_rule_info(skb, ctx->net, ctx->portid, ctx->seq,
2685                                        event, 0, ctx->family, ctx->table,
2686                                        ctx->chain, rule, NULL);
2687         if (err < 0) {
2688                 kfree_skb(skb);
2689                 goto err;
2690         }
2691 
2692         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
2693                        ctx->report, GFP_KERNEL);
2694         return;
2695 err:
2696         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
2697 }
2698 
2699 struct nft_rule_dump_ctx {
2700         char *table;
2701         char *chain;
2702 };
2703 
2704 static int __nf_tables_dump_rules(struct sk_buff *skb,
2705                                   unsigned int *idx,
2706                                   struct netlink_callback *cb,
2707                                   const struct nft_table *table,
2708                                   const struct nft_chain *chain)
2709 {
2710         struct net *net = sock_net(skb->sk);
2711         const struct nft_rule *rule, *prule;
2712         unsigned int s_idx = cb->args[0];
2713 
2714         prule = NULL;
2715         list_for_each_entry_rcu(rule, &chain->rules, list) {
2716                 if (!nft_is_active(net, rule))
2717                         goto cont_skip;
2718                 if (*idx < s_idx)
2719                         goto cont;
2720                 if (*idx > s_idx) {
2721                         memset(&cb->args[1], 0,
2722                                         sizeof(cb->args) - sizeof(cb->args[0]));
2723                 }
2724                 if (nf_tables_fill_rule_info(skb, net, NETLINK_CB(cb->skb).portid,
2725                                         cb->nlh->nlmsg_seq,
2726                                         NFT_MSG_NEWRULE,
2727                                         NLM_F_MULTI | NLM_F_APPEND,
2728                                         table->family,
2729                                         table, chain, rule, prule) < 0)
2730                         return 1;
2731 
2732                 nl_dump_check_consistent(cb, nlmsg_hdr(skb));
2733 cont:
2734                 prule = rule;
2735 cont_skip:
2736                 (*idx)++;
2737         }
2738         return 0;
2739 }
2740 
2741 static int nf_tables_dump_rules(struct sk_buff *skb,
2742                                 struct netlink_callback *cb)
2743 {
2744         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
2745         const struct nft_rule_dump_ctx *ctx = cb->data;
2746         struct nft_table *table;
2747         const struct nft_chain *chain;
2748         unsigned int idx = 0;
2749         struct net *net = sock_net(skb->sk);
2750         int family = nfmsg->nfgen_family;
2751 
2752         rcu_read_lock();
2753         cb->seq = net->nft.base_seq;
2754 
2755         list_for_each_entry_rcu(table, &net->nft.tables, list) {
2756                 if (family != NFPROTO_UNSPEC && family != table->family)
2757                         continue;
2758 
2759                 if (ctx && ctx->table && strcmp(ctx->table, table->name) != 0)
2760                         continue;
2761 
2762                 if (ctx && ctx->table && ctx->chain) {
2763                         struct rhlist_head *list, *tmp;
2764 
2765                         list = rhltable_lookup(&table->chains_ht, ctx->chain,
2766                                                nft_chain_ht_params);
2767                         if (!list)
2768                                 goto done;
2769 
2770                         rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) {
2771                                 if (!nft_is_active(net, chain))
2772                                         continue;
2773                                 __nf_tables_dump_rules(skb, &idx,
2774                                                        cb, table, chain);
2775                                 break;
2776                         }
2777                         goto done;
2778                 }
2779 
2780                 list_for_each_entry_rcu(chain, &table->chains, list) {
2781                         if (__nf_tables_dump_rules(skb, &idx, cb, table, chain))
2782                                 goto done;
2783                 }
2784 
2785                 if (ctx && ctx->table)
2786                         break;
2787         }
2788 done:
2789         rcu_read_unlock();
2790 
2791         cb->args[0] = idx;
2792         return skb->len;
2793 }
2794 
2795 static int nf_tables_dump_rules_start(struct netlink_callback *cb)
2796 {
2797         const struct nlattr * const *nla = cb->data;
2798         struct nft_rule_dump_ctx *ctx = NULL;
2799 
2800         if (nla[NFTA_RULE_TABLE] || nla[NFTA_RULE_CHAIN]) {
2801                 ctx = kzalloc(sizeof(*ctx), GFP_ATOMIC);
2802                 if (!ctx)
2803                         return -ENOMEM;
2804 
2805                 if (nla[NFTA_RULE_TABLE]) {
2806                         ctx->table = nla_strdup(nla[NFTA_RULE_TABLE],
2807                                                         GFP_ATOMIC);
2808                         if (!ctx->table) {
2809                                 kfree(ctx);
2810                                 return -ENOMEM;
2811                         }
2812                 }
2813                 if (nla[NFTA_RULE_CHAIN]) {
2814                         ctx->chain = nla_strdup(nla[NFTA_RULE_CHAIN],
2815                                                 GFP_ATOMIC);
2816                         if (!ctx->chain) {
2817                                 kfree(ctx->table);
2818                                 kfree(ctx);
2819                                 return -ENOMEM;
2820                         }
2821                 }
2822         }
2823 
2824         cb->data = ctx;
2825         return 0;
2826 }
2827 
2828 static int nf_tables_dump_rules_done(struct netlink_callback *cb)
2829 {
2830         struct nft_rule_dump_ctx *ctx = cb->data;
2831 
2832         if (ctx) {
2833                 kfree(ctx->table);
2834                 kfree(ctx->chain);
2835                 kfree(ctx);
2836         }
2837         return 0;
2838 }
2839 
2840 /* called with rcu_read_lock held */
2841 static int nf_tables_getrule(struct net *net, struct sock *nlsk,
2842                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2843                              const struct nlattr * const nla[],
2844                              struct netlink_ext_ack *extack)
2845 {
2846         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2847         u8 genmask = nft_genmask_cur(net);
2848         const struct nft_chain *chain;
2849         const struct nft_rule *rule;
2850         struct nft_table *table;
2851         struct sk_buff *skb2;
2852         int family = nfmsg->nfgen_family;
2853         int err;
2854 
2855         if (nlh->nlmsg_flags & NLM_F_DUMP) {
2856                 struct netlink_dump_control c = {
2857                         .start= nf_tables_dump_rules_start,
2858                         .dump = nf_tables_dump_rules,
2859                         .done = nf_tables_dump_rules_done,
2860                         .module = THIS_MODULE,
2861                         .data = (void *)nla,
2862                 };
2863 
2864                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
2865         }
2866 
2867         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2868         if (IS_ERR(table)) {
2869                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2870                 return PTR_ERR(table);
2871         }
2872 
2873         chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
2874         if (IS_ERR(chain)) {
2875                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2876                 return PTR_ERR(chain);
2877         }
2878 
2879         rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
2880         if (IS_ERR(rule)) {
2881                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2882                 return PTR_ERR(rule);
2883         }
2884 
2885         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
2886         if (!skb2)
2887                 return -ENOMEM;
2888 
2889         err = nf_tables_fill_rule_info(skb2, net, NETLINK_CB(skb).portid,
2890                                        nlh->nlmsg_seq, NFT_MSG_NEWRULE, 0,
2891                                        family, table, chain, rule, NULL);
2892         if (err < 0)
2893                 goto err;
2894 
2895         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
2896 
2897 err:
2898         kfree_skb(skb2);
2899         return err;
2900 }
2901 
2902 static void nf_tables_rule_destroy(const struct nft_ctx *ctx,
2903                                    struct nft_rule *rule)
2904 {
2905         struct nft_expr *expr, *next;
2906 
2907         /*
2908          * Careful: some expressions might not be initialized in case this
2909          * is called on error from nf_tables_newrule().
2910          */
2911         expr = nft_expr_first(rule);
2912         while (expr != nft_expr_last(rule) && expr->ops) {
2913                 next = nft_expr_next(expr);
2914                 nf_tables_expr_destroy(ctx, expr);
2915                 expr = next;
2916         }
2917         kfree(rule);
2918 }
2919 
2920 static void nf_tables_rule_release(const struct nft_ctx *ctx,
2921                                    struct nft_rule *rule)
2922 {
2923         nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_RELEASE);
2924         nf_tables_rule_destroy(ctx, rule);
2925 }
2926 
2927 int nft_chain_validate(const struct nft_ctx *ctx, const struct nft_chain *chain)
2928 {
2929         struct nft_expr *expr, *last;
2930         const struct nft_data *data;
2931         struct nft_rule *rule;
2932         int err;
2933 
2934         if (ctx->level == NFT_JUMP_STACK_SIZE)
2935                 return -EMLINK;
2936 
2937         list_for_each_entry(rule, &chain->rules, list) {
2938                 if (!nft_is_active_next(ctx->net, rule))
2939                         continue;
2940 
2941                 nft_rule_for_each_expr(expr, last, rule) {
2942                         if (!expr->ops->validate)
2943                                 continue;
2944 
2945                         err = expr->ops->validate(ctx, expr, &data);
2946                         if (err < 0)
2947                                 return err;
2948                 }
2949         }
2950 
2951         return 0;
2952 }
2953 EXPORT_SYMBOL_GPL(nft_chain_validate);
2954 
2955 static int nft_table_validate(struct net *net, const struct nft_table *table)
2956 {
2957         struct nft_chain *chain;
2958         struct nft_ctx ctx = {
2959                 .net    = net,
2960                 .family = table->family,
2961         };
2962         int err;
2963 
2964         list_for_each_entry(chain, &table->chains, list) {
2965                 if (!nft_is_base_chain(chain))
2966                         continue;
2967 
2968                 ctx.chain = chain;
2969                 err = nft_chain_validate(&ctx, chain);
2970                 if (err < 0)
2971                         return err;
2972         }
2973 
2974         return 0;
2975 }
2976 
2977 static struct nft_rule *nft_rule_lookup_byid(const struct net *net,
2978                                              const struct nlattr *nla);
2979 
2980 #define NFT_RULE_MAXEXPRS       128
2981 
2982 static int nf_tables_newrule(struct net *net, struct sock *nlsk,
2983                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2984                              const struct nlattr * const nla[],
2985                              struct netlink_ext_ack *extack)
2986 {
2987         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2988         u8 genmask = nft_genmask_next(net);
2989         struct nft_expr_info *info = NULL;
2990         int family = nfmsg->nfgen_family;
2991         struct nft_flow_rule *flow;
2992         struct nft_table *table;
2993         struct nft_chain *chain;
2994         struct nft_rule *rule, *old_rule = NULL;
2995         struct nft_userdata *udata;
2996         struct nft_trans *trans = NULL;
2997         struct nft_expr *expr;
2998         struct nft_ctx ctx;
2999         struct nlattr *tmp;
3000         unsigned int size, i, n, ulen = 0, usize = 0;
3001         int err, rem;
3002         u64 handle, pos_handle;
3003 
3004         lockdep_assert_held(&net->nft.commit_mutex);
3005 
3006         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
3007         if (IS_ERR(table)) {
3008                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
3009                 return PTR_ERR(table);
3010         }
3011 
3012         chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
3013         if (IS_ERR(chain)) {
3014                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
3015                 return PTR_ERR(chain);
3016         }
3017 
3018         if (nla[NFTA_RULE_HANDLE]) {
3019                 handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_HANDLE]));
3020                 rule = __nft_rule_lookup(chain, handle);
3021                 if (IS_ERR(rule)) {
3022                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
3023                         return PTR_ERR(rule);
3024                 }
3025 
3026                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
3027                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
3028                         return -EEXIST;
3029                 }
3030                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
3031                         old_rule = rule;
3032                 else
3033                         return -EOPNOTSUPP;
3034         } else {
3035                 if (!(nlh->nlmsg_flags & NLM_F_CREATE) ||
3036                     nlh->nlmsg_flags & NLM_F_REPLACE)
3037                         return -EINVAL;
3038                 handle = nf_tables_alloc_handle(table);
3039 
3040                 if (chain->use == UINT_MAX)
3041                         return -EOVERFLOW;
3042 
3043                 if (nla[NFTA_RULE_POSITION]) {
3044                         pos_handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_POSITION]));
3045                         old_rule = __nft_rule_lookup(chain, pos_handle);
3046                         if (IS_ERR(old_rule)) {
3047                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_POSITION]);
3048                                 return PTR_ERR(old_rule);
3049                         }
3050                 } else if (nla[NFTA_RULE_POSITION_ID]) {
3051                         old_rule = nft_rule_lookup_byid(net, nla[NFTA_RULE_POSITION_ID]);
3052                         if (IS_ERR(old_rule)) {
3053                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_POSITION_ID]);
3054                                 return PTR_ERR(old_rule);
3055                         }
3056                 }
3057         }
3058 
3059         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
3060 
3061         n = 0;
3062         size = 0;
3063         if (nla[NFTA_RULE_EXPRESSIONS]) {
3064                 info = kvmalloc_array(NFT_RULE_MAXEXPRS,
3065                                       sizeof(struct nft_expr_info),
3066                                       GFP_KERNEL);
3067                 if (!info)
3068                         return -ENOMEM;
3069 
3070                 nla_for_each_nested(tmp, nla[NFTA_RULE_EXPRESSIONS], rem) {
3071                         err = -EINVAL;
3072                         if (nla_type(tmp) != NFTA_LIST_ELEM)
3073                                 goto err1;
3074                         if (n == NFT_RULE_MAXEXPRS)
3075                                 goto err1;
3076                         err = nf_tables_expr_parse(&ctx, tmp, &info[n]);
3077                         if (err < 0)
3078                                 goto err1;
3079                         size += info[n].ops->size;
3080                         n++;
3081                 }
3082         }
3083         /* Check for overflow of dlen field */
3084         err = -EFBIG;
3085         if (size >= 1 << 12)
3086                 goto err1;
3087 
3088         if (nla[NFTA_RULE_USERDATA]) {
3089                 ulen = nla_len(nla[NFTA_RULE_USERDATA]);
3090                 if (ulen > 0)
3091                         usize = sizeof(struct nft_userdata) + ulen;
3092         }
3093 
3094         err = -ENOMEM;
3095         rule = kzalloc(sizeof(*rule) + size + usize, GFP_KERNEL);
3096         if (rule == NULL)
3097                 goto err1;
3098 
3099         nft_activate_next(net, rule);
3100 
3101         rule->handle = handle;
3102         rule->dlen   = size;
3103         rule->udata  = ulen ? 1 : 0;
3104 
3105         if (ulen) {
3106                 udata = nft_userdata(rule);
3107                 udata->len = ulen - 1;
3108                 nla_memcpy(udata->data, nla[NFTA_RULE_USERDATA], ulen);
3109         }
3110 
3111         expr = nft_expr_first(rule);
3112         for (i = 0; i < n; i++) {
3113                 err = nf_tables_newexpr(&ctx, &info[i], expr);
3114                 if (err < 0)
3115                         goto err2;
3116 
3117                 if (info[i].ops->validate)
3118                         nft_validate_state_update(net, NFT_VALIDATE_NEED);
3119 
3120                 info[i].ops = NULL;
3121                 expr = nft_expr_next(expr);
3122         }
3123 
3124         if (nlh->nlmsg_flags & NLM_F_REPLACE) {
3125                 trans = nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule);
3126                 if (trans == NULL) {
3127                         err = -ENOMEM;
3128                         goto err2;
3129                 }
3130                 err = nft_delrule(&ctx, old_rule);
3131                 if (err < 0) {
3132                         nft_trans_destroy(trans);
3133                         goto err2;
3134                 }
3135 
3136                 list_add_tail_rcu(&rule->list, &old_rule->list);
3137         } else {
3138                 trans = nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule);
3139                 if (!trans) {
3140                         err = -ENOMEM;
3141                         goto err2;
3142                 }
3143 
3144                 if (nlh->nlmsg_flags & NLM_F_APPEND) {
3145                         if (old_rule)
3146                                 list_add_rcu(&rule->list, &old_rule->list);
3147                         else
3148                                 list_add_tail_rcu(&rule->list, &chain->rules);
3149                  } else {
3150                         if (old_rule)
3151                                 list_add_tail_rcu(&rule->list, &old_rule->list);
3152                         else
3153                                 list_add_rcu(&rule->list, &chain->rules);
3154                 }
3155         }
3156         kvfree(info);
3157         chain->use++;
3158 
3159         if (net->nft.validate_state == NFT_VALIDATE_DO)
3160                 return nft_table_validate(net, table);
3161 
3162         if (chain->flags & NFT_CHAIN_HW_OFFLOAD) {
3163                 flow = nft_flow_rule_create(net, rule);
3164                 if (IS_ERR(flow))
3165                         return PTR_ERR(flow);
3166 
3167                 nft_trans_flow_rule(trans) = flow;
3168         }
3169 
3170         return 0;
3171 err2:
3172         nf_tables_rule_release(&ctx, rule);
3173 err1:
3174         for (i = 0; i < n; i++) {
3175                 if (info[i].ops) {
3176                         module_put(info[i].ops->type->owner);
3177                         if (info[i].ops->type->release_ops)
3178                                 info[i].ops->type->release_ops(info[i].ops);
3179                 }
3180         }
3181         kvfree(info);
3182         return err;
3183 }
3184 
3185 static struct nft_rule *nft_rule_lookup_byid(const struct net *net,
3186                                              const struct nlattr *nla)
3187 {
3188         u32 id = ntohl(nla_get_be32(nla));
3189         struct nft_trans *trans;
3190 
3191         list_for_each_entry(trans, &net->nft.commit_list, list) {
3192                 struct nft_rule *rule = nft_trans_rule(trans);
3193 
3194                 if (trans->msg_type == NFT_MSG_NEWRULE &&
3195                     id == nft_trans_rule_id(trans))
3196                         return rule;
3197         }
3198         return ERR_PTR(-ENOENT);
3199 }
3200 
3201 static int nf_tables_delrule(struct net *net, struct sock *nlsk,
3202                              struct sk_buff *skb, const struct nlmsghdr *nlh,
3203                              const struct nlattr * const nla[],
3204                              struct netlink_ext_ack *extack)
3205 {
3206         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3207         u8 genmask = nft_genmask_next(net);
3208         struct nft_table *table;
3209         struct nft_chain *chain = NULL;
3210         struct nft_rule *rule;
3211         int family = nfmsg->nfgen_family, err = 0;
3212         struct nft_ctx ctx;
3213 
3214         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
3215         if (IS_ERR(table)) {
3216                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
3217                 return PTR_ERR(table);
3218         }
3219 
3220         if (nla[NFTA_RULE_CHAIN]) {
3221                 chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN],
3222                                          genmask);
3223                 if (IS_ERR(chain)) {
3224                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
3225                         return PTR_ERR(chain);
3226                 }
3227         }
3228 
3229         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
3230 
3231         if (chain) {
3232                 if (nla[NFTA_RULE_HANDLE]) {
3233                         rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
3234                         if (IS_ERR(rule)) {
3235                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
3236                                 return PTR_ERR(rule);
3237                         }
3238 
3239                         err = nft_delrule(&ctx, rule);
3240                 } else if (nla[NFTA_RULE_ID]) {
3241                         rule = nft_rule_lookup_byid(net, nla[NFTA_RULE_ID]);
3242                         if (IS_ERR(rule)) {
3243                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_ID]);
3244                                 return PTR_ERR(rule);
3245                         }
3246 
3247                         err = nft_delrule(&ctx, rule);
3248                 } else {
3249                         err = nft_delrule_by_chain(&ctx);
3250                 }
3251         } else {
3252                 list_for_each_entry(chain, &table->chains, list) {
3253                         if (!nft_is_active_next(net, chain))
3254                                 continue;
3255 
3256                         ctx.chain = chain;
3257                         err = nft_delrule_by_chain(&ctx);
3258                         if (err < 0)
3259                                 break;
3260                 }
3261         }
3262 
3263         return err;
3264 }
3265 
3266 /*
3267  * Sets
3268  */
3269 
3270 static LIST_HEAD(nf_tables_set_types);
3271 
3272 int nft_register_set(struct nft_set_type *type)
3273 {
3274         nfnl_lock(NFNL_SUBSYS_NFTABLES);
3275         list_add_tail_rcu(&type->list, &nf_tables_set_types);
3276         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
3277         return 0;
3278 }
3279 EXPORT_SYMBOL_GPL(nft_register_set);
3280 
3281 void nft_unregister_set(struct nft_set_type *type)
3282 {
3283         nfnl_lock(NFNL_SUBSYS_NFTABLES);
3284         list_del_rcu(&type->list);
3285         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
3286 }
3287 EXPORT_SYMBOL_GPL(nft_unregister_set);
3288 
3289 #define NFT_SET_FEATURES        (NFT_SET_INTERVAL | NFT_SET_MAP | \
3290                                  NFT_SET_TIMEOUT | NFT_SET_OBJECT | \
3291                                  NFT_SET_EVAL)
3292 
3293 static bool nft_set_ops_candidate(const struct nft_set_type *type, u32 flags)
3294 {
3295         return (flags & type->features) == (flags & NFT_SET_FEATURES);
3296 }
3297 
3298 /*
3299  * Select a set implementation based on the data characteristics and the
3300  * given policy. The total memory use might not be known if no size is
3301  * given, in that case the amount of memory per element is used.
3302  */
3303 static const struct nft_set_ops *
3304 nft_select_set_ops(const struct nft_ctx *ctx,
3305                    const struct nlattr * const nla[],
3306                    const struct nft_set_desc *desc,
3307                    enum nft_set_policies policy)
3308 {
3309         const struct nft_set_ops *ops, *bops;
3310         struct nft_set_estimate est, best;
3311         const struct nft_set_type *type;
3312         u32 flags = 0;
3313 
3314         lockdep_assert_held(&ctx->net->nft.commit_mutex);
3315         lockdep_nfnl_nft_mutex_not_held();
3316 #ifdef CONFIG_MODULES
3317         if (list_empty(&nf_tables_set_types)) {
3318                 if (nft_request_module(ctx->net, "nft-set") == -EAGAIN)
3319                         return ERR_PTR(-EAGAIN);
3320         }
3321 #endif
3322         if (nla[NFTA_SET_FLAGS] != NULL)
3323                 flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
3324 
3325         bops        = NULL;
3326         best.size   = ~0;
3327         best.lookup = ~0;
3328         best.space  = ~0;
3329 
3330         list_for_each_entry(type, &nf_tables_set_types, list) {
3331                 ops = &type->ops;
3332 
3333                 if (!nft_set_ops_candidate(type, flags))
3334                         continue;
3335                 if (!ops->estimate(desc, flags, &est))
3336                         continue;
3337 
3338                 switch (policy) {
3339                 case NFT_SET_POL_PERFORMANCE:
3340                         if (est.lookup < best.lookup)
3341                                 break;
3342                         if (est.lookup == best.lookup &&
3343                             est.space < best.space)
3344                                 break;
3345                         continue;
3346                 case NFT_SET_POL_MEMORY:
3347                         if (!desc->size) {
3348                                 if (est.space < best.space)
3349                                         break;
3350                                 if (est.space == best.space &&
3351                                     est.lookup < best.lookup)
3352                                         break;
3353                         } else if (est.size < best.size || !bops) {
3354                                 break;
3355                         }
3356                         continue;
3357                 default:
3358                         break;
3359                 }
3360 
3361                 if (!try_module_get(type->owner))
3362                         continue;
3363                 if (bops != NULL)
3364                         module_put(to_set_type(bops)->owner);
3365 
3366                 bops = ops;
3367                 best = est;
3368         }
3369 
3370         if (bops != NULL)
3371                 return bops;
3372 
3373         return ERR_PTR(-EOPNOTSUPP);
3374 }
3375 
3376 static const struct nla_policy nft_set_policy[NFTA_SET_MAX + 1] = {
3377         [NFTA_SET_TABLE]                = { .type = NLA_STRING,
3378                                             .len = NFT_TABLE_MAXNAMELEN - 1 },
3379         [NFTA_SET_NAME]                 = { .type = NLA_STRING,
3380                                             .len = NFT_SET_MAXNAMELEN - 1 },
3381         [NFTA_SET_FLAGS]                = { .type = NLA_U32 },
3382         [NFTA_SET_KEY_TYPE]             = { .type = NLA_U32 },
3383         [NFTA_SET_KEY_LEN]              = { .type = NLA_U32 },
3384         [NFTA_SET_DATA_TYPE]            = { .type = NLA_U32 },
3385         [NFTA_SET_DATA_LEN]             = { .type = NLA_U32 },
3386         [NFTA_SET_POLICY]               = { .type = NLA_U32 },
3387         [NFTA_SET_DESC]                 = { .type = NLA_NESTED },
3388         [NFTA_SET_ID]                   = { .type = NLA_U32 },
3389         [NFTA_SET_TIMEOUT]              = { .type = NLA_U64 },
3390         [NFTA_SET_GC_INTERVAL]          = { .type = NLA_U32 },
3391         [NFTA_SET_USERDATA]             = { .type = NLA_BINARY,
3392                                             .len  = NFT_USERDATA_MAXLEN },
3393         [NFTA_SET_OBJ_TYPE]             = { .type = NLA_U32 },
3394         [NFTA_SET_HANDLE]               = { .type = NLA_U64 },
3395 };
3396 
3397 static const struct nla_policy nft_set_desc_policy[NFTA_SET_DESC_MAX + 1] = {
3398         [NFTA_SET_DESC_SIZE]            = { .type = NLA_U32 },
3399         [NFTA_SET_DESC_CONCAT]          = { .type = NLA_NESTED },
3400 };
3401 
3402 static int nft_ctx_init_from_setattr(struct nft_ctx *ctx, struct net *net,
3403                                      const struct sk_buff *skb,
3404                                      const struct nlmsghdr *nlh,
3405                                      const struct nlattr * const nla[],
3406                                      struct netlink_ext_ack *extack,
3407                                      u8 genmask)
3408 {
3409         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3410         int family = nfmsg->nfgen_family;
3411         struct nft_table *table = NULL;
3412 
3413         if (nla[NFTA_SET_TABLE] != NULL) {
3414                 table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family,
3415                                          genmask);
3416                 if (IS_ERR(table)) {
3417                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
3418                         return PTR_ERR(table);
3419                 }
3420         }
3421 
3422         nft_ctx_init(ctx, net, skb, nlh, family, table, NULL, nla);
3423         return 0;
3424 }
3425 
3426 static struct nft_set *nft_set_lookup(const struct nft_table *table,
3427                                       const struct nlattr *nla, u8 genmask)
3428 {
3429         struct nft_set *set;
3430 
3431         if (nla == NULL)
3432                 return ERR_PTR(-EINVAL);
3433 
3434         list_for_each_entry_rcu(set, &table->sets, list) {
3435                 if (!nla_strcmp(nla, set->name) &&
3436                     nft_active_genmask(set, genmask))
3437                         return set;
3438         }
3439         return ERR_PTR(-ENOENT);
3440 }
3441 
3442 static struct nft_set *nft_set_lookup_byhandle(const struct nft_table *table,
3443                                                const struct nlattr *nla,
3444                                                u8 genmask)
3445 {
3446         struct nft_set *set;
3447 
3448         list_for_each_entry(set, &table->sets, list) {
3449                 if (be64_to_cpu(nla_get_be64(nla)) == set->handle &&
3450                     nft_active_genmask(set, genmask))
3451                         return set;
3452         }
3453         return ERR_PTR(-ENOENT);
3454 }
3455 
3456 static struct nft_set *nft_set_lookup_byid(const struct net *net,
3457                                            const struct nlattr *nla, u8 genmask)
3458 {
3459         struct nft_trans *trans;
3460         u32 id = ntohl(nla_get_be32(nla));
3461 
3462         list_for_each_entry(trans, &net->nft.commit_list, list) {
3463                 if (trans->msg_type == NFT_MSG_NEWSET) {
3464                         struct nft_set *set = nft_trans_set(trans);
3465 
3466                         if (id == nft_trans_set_id(trans) &&
3467                             nft_active_genmask(set, genmask))
3468                                 return set;
3469                 }
3470         }
3471         return ERR_PTR(-ENOENT);
3472 }
3473 
3474 struct nft_set *nft_set_lookup_global(const struct net *net,
3475                                       const struct nft_table *table,
3476                                       const struct nlattr *nla_set_name,
3477                                       const struct nlattr *nla_set_id,
3478                                       u8 genmask)
3479 {
3480         struct nft_set *set;
3481 
3482         set = nft_set_lookup(table, nla_set_name, genmask);
3483         if (IS_ERR(set)) {
3484                 if (!nla_set_id)
3485                         return set;
3486 
3487                 set = nft_set_lookup_byid(net, nla_set_id, genmask);
3488         }
3489         return set;
3490 }
3491 EXPORT_SYMBOL_GPL(nft_set_lookup_global);
3492 
3493 static int nf_tables_set_alloc_name(struct nft_ctx *ctx, struct nft_set *set,
3494                                     const char *name)
3495 {
3496         const struct nft_set *i;
3497         const char *p;
3498         unsigned long *inuse;
3499         unsigned int n = 0, min = 0;
3500 
3501         p = strchr(name, '%');
3502         if (p != NULL) {
3503                 if (p[1] != 'd' || strchr(p + 2, '%'))
3504                         return -EINVAL;
3505 
3506                 inuse = (unsigned long *)get_zeroed_page(GFP_KERNEL);
3507                 if (inuse == NULL)
3508                         return -ENOMEM;
3509 cont:
3510                 list_for_each_entry(i, &ctx->table->sets, list) {
3511                         int tmp;
3512 
3513                         if (!nft_is_active_next(ctx->net, set))
3514                                 continue;
3515                         if (!sscanf(i->name, name, &tmp))
3516                                 continue;
3517                         if (tmp < min || tmp >= min + BITS_PER_BYTE * PAGE_SIZE)
3518                                 continue;
3519 
3520                         set_bit(tmp - min, inuse);
3521                 }
3522 
3523                 n = find_first_zero_bit(inuse, BITS_PER_BYTE * PAGE_SIZE);
3524                 if (n >= BITS_PER_BYTE * PAGE_SIZE) {
3525                         min += BITS_PER_BYTE * PAGE_SIZE;
3526                         memset(inuse, 0, PAGE_SIZE);
3527                         goto cont;
3528                 }
3529                 free_page((unsigned long)inuse);
3530         }
3531 
3532         set->name = kasprintf(GFP_KERNEL, name, min + n);
3533         if (!set->name)
3534                 return -ENOMEM;
3535 
3536         list_for_each_entry(i, &ctx->table->sets, list) {
3537                 if (!nft_is_active_next(ctx->net, i))
3538                         continue;
3539                 if (!strcmp(set->name, i->name)) {
3540                         kfree(set->name);
3541                         return -ENFILE;
3542                 }
3543         }
3544         return 0;
3545 }
3546 
3547 static int nf_msecs_to_jiffies64(const struct nlattr *nla, u64 *result)
3548 {
3549         u64 ms = be64_to_cpu(nla_get_be64(nla));
3550         u64 max = (u64)(~((u64)0));
3551 
3552         max = div_u64(max, NSEC_PER_MSEC);
3553         if (ms >= max)
3554                 return -ERANGE;
3555 
3556         ms *= NSEC_PER_MSEC;
3557         *result = nsecs_to_jiffies64(ms);
3558         return 0;
3559 }
3560 
3561 static __be64 nf_jiffies64_to_msecs(u64 input)
3562 {
3563         return cpu_to_be64(jiffies64_to_msecs(input));
3564 }
3565 
3566 static int nf_tables_fill_set_concat(struct sk_buff *skb,
3567                                      const struct nft_set *set)
3568 {
3569         struct nlattr *concat, *field;
3570         int i;
3571 
3572         concat = nla_nest_start_noflag(skb, NFTA_SET_DESC_CONCAT);
3573         if (!concat)
3574                 return -ENOMEM;
3575 
3576         for (i = 0; i < set->field_count; i++) {
3577                 field = nla_nest_start_noflag(skb, NFTA_LIST_ELEM);
3578                 if (!field)
3579                         return -ENOMEM;
3580 
3581                 if (nla_put_be32(skb, NFTA_SET_FIELD_LEN,
3582                                  htonl(set->field_len[i])))
3583                         return -ENOMEM;
3584 
3585                 nla_nest_end(skb, field);
3586         }
3587 
3588         nla_nest_end(skb, concat);
3589 
3590         return 0;
3591 }
3592 
3593 static int nf_tables_fill_set(struct sk_buff *skb, const struct nft_ctx *ctx,
3594                               const struct nft_set *set, u16 event, u16 flags)
3595 {
3596         struct nfgenmsg *nfmsg;
3597         struct nlmsghdr *nlh;
3598         struct nlattr *desc;
3599         u32 portid = ctx->portid;
3600         u32 seq = ctx->seq;
3601 
3602         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
3603         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
3604                         flags);
3605         if (nlh == NULL)
3606                 goto nla_put_failure;
3607 
3608         nfmsg = nlmsg_data(nlh);
3609         nfmsg->nfgen_family     = ctx->family;
3610         nfmsg->version          = NFNETLINK_V0;
3611         nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
3612 
3613         if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
3614                 goto nla_put_failure;
3615         if (nla_put_string(skb, NFTA_SET_NAME, set->name))
3616                 goto nla_put_failure;
3617         if (nla_put_be64(skb, NFTA_SET_HANDLE, cpu_to_be64(set->handle),
3618                          NFTA_SET_PAD))
3619                 goto nla_put_failure;
3620         if (set->flags != 0)
3621                 if (nla_put_be32(skb, NFTA_SET_FLAGS, htonl(set->flags)))
3622                         goto nla_put_failure;
3623 
3624         if (nla_put_be32(skb, NFTA_SET_KEY_TYPE, htonl(set->ktype)))
3625                 goto nla_put_failure;
3626         if (nla_put_be32(skb, NFTA_SET_KEY_LEN, htonl(set->klen)))
3627                 goto nla_put_failure;
3628         if (set->flags & NFT_SET_MAP) {
3629                 if (nla_put_be32(skb, NFTA_SET_DATA_TYPE, htonl(set->dtype)))
3630                         goto nla_put_failure;
3631                 if (nla_put_be32(skb, NFTA_SET_DATA_LEN, htonl(set->dlen)))
3632                         goto nla_put_failure;
3633         }
3634         if (set->flags & NFT_SET_OBJECT &&
3635             nla_put_be32(skb, NFTA_SET_OBJ_TYPE, htonl(set->objtype)))
3636                 goto nla_put_failure;
3637 
3638         if (set->timeout &&
3639             nla_put_be64(skb, NFTA_SET_TIMEOUT,
3640                          nf_jiffies64_to_msecs(set->timeout),
3641                          NFTA_SET_PAD))
3642                 goto nla_put_failure;
3643         if (set->gc_int &&
3644             nla_put_be32(skb, NFTA_SET_GC_INTERVAL, htonl(set->gc_int)))
3645                 goto nla_put_failure;
3646 
3647         if (set->policy != NFT_SET_POL_PERFORMANCE) {
3648                 if (nla_put_be32(skb, NFTA_SET_POLICY, htonl(set->policy)))
3649                         goto nla_put_failure;
3650         }
3651 
3652         if (nla_put(skb, NFTA_SET_USERDATA, set->udlen, set->udata))
3653                 goto nla_put_failure;
3654 
3655         desc = nla_nest_start_noflag(skb, NFTA_SET_DESC);
3656 
3657         if (desc == NULL)
3658                 goto nla_put_failure;
3659         if (set->size &&
3660             nla_put_be32(skb, NFTA_SET_DESC_SIZE, htonl(set->size)))
3661                 goto nla_put_failure;
3662 
3663         if (set->field_count > 1 &&
3664             nf_tables_fill_set_concat(skb, set))
3665                 goto nla_put_failure;
3666 
3667         nla_nest_end(skb, desc);
3668 
3669         nlmsg_end(skb, nlh);
3670         return 0;
3671 
3672 nla_put_failure:
3673         nlmsg_trim(skb, nlh);
3674         return -1;
3675 }
3676 
3677 static void nf_tables_set_notify(const struct nft_ctx *ctx,
3678                                  const struct nft_set *set, int event,
3679                                  gfp_t gfp_flags)
3680 {
3681         struct sk_buff *skb;
3682         u32 portid = ctx->portid;
3683         int err;
3684 
3685         if (!ctx->report &&
3686             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
3687                 return;
3688 
3689         skb = nlmsg_new(NLMSG_GOODSIZE, gfp_flags);
3690         if (skb == NULL)
3691                 goto err;
3692 
3693         err = nf_tables_fill_set(skb, ctx, set, event, 0);
3694         if (err < 0) {
3695                 kfree_skb(skb);
3696                 goto err;
3697         }
3698 
3699         nfnetlink_send(skb, ctx->net, portid, NFNLGRP_NFTABLES, ctx->report,
3700                        gfp_flags);
3701         return;
3702 err:
3703         nfnetlink_set_err(ctx->net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
3704 }
3705 
3706 static int nf_tables_dump_sets(struct sk_buff *skb, struct netlink_callback *cb)
3707 {
3708         const struct nft_set *set;
3709         unsigned int idx, s_idx = cb->args[0];
3710         struct nft_table *table, *cur_table = (struct nft_table *)cb->args[2];
3711         struct net *net = sock_net(skb->sk);
3712         struct nft_ctx *ctx = cb->data, ctx_set;
3713 
3714         if (cb->args[1])
3715                 return skb->len;
3716 
3717         rcu_read_lock();
3718         cb->seq = net->nft.base_seq;
3719 
3720         list_for_each_entry_rcu(table, &net->nft.tables, list) {
3721                 if (ctx->family != NFPROTO_UNSPEC &&
3722                     ctx->family != table->family)
3723                         continue;
3724 
3725                 if (ctx->table && ctx->table != table)
3726                         continue;
3727 
3728                 if (cur_table) {
3729                         if (cur_table != table)
3730                                 continue;
3731 
3732                         cur_table = NULL;
3733                 }
3734                 idx = 0;
3735                 list_for_each_entry_rcu(set, &table->sets, list) {
3736                         if (idx < s_idx)
3737                                 goto cont;
3738                         if (!nft_is_active(net, set))
3739                                 goto cont;
3740 
3741                         ctx_set = *ctx;
3742                         ctx_set.table = table;
3743                         ctx_set.family = table->family;
3744 
3745                         if (nf_tables_fill_set(skb, &ctx_set, set,
3746                                                NFT_MSG_NEWSET,
3747                                                NLM_F_MULTI) < 0) {
3748                                 cb->args[0] = idx;
3749                                 cb->args[2] = (unsigned long) table;
3750                                 goto done;
3751                         }
3752                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
3753 cont:
3754                         idx++;
3755                 }
3756                 if (s_idx)
3757                         s_idx = 0;
3758         }
3759         cb->args[1] = 1;
3760 done:
3761         rcu_read_unlock();
3762         return skb->len;
3763 }
3764 
3765 static int nf_tables_dump_sets_start(struct netlink_callback *cb)
3766 {
3767         struct nft_ctx *ctx_dump = NULL;
3768 
3769         ctx_dump = kmemdup(cb->data, sizeof(*ctx_dump), GFP_ATOMIC);
3770         if (ctx_dump == NULL)
3771                 return -ENOMEM;
3772 
3773         cb->data = ctx_dump;
3774         return 0;
3775 }
3776 
3777 static int nf_tables_dump_sets_done(struct netlink_callback *cb)
3778 {
3779         kfree(cb->data);
3780         return 0;
3781 }
3782 
3783 /* called with rcu_read_lock held */
3784 static int nf_tables_getset(struct net *net, struct sock *nlsk,
3785                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3786                             const struct nlattr * const nla[],
3787                             struct netlink_ext_ack *extack)
3788 {
3789         u8 genmask = nft_genmask_cur(net);
3790         const struct nft_set *set;
3791         struct nft_ctx ctx;
3792         struct sk_buff *skb2;
3793         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3794         int err;
3795 
3796         /* Verify existence before starting dump */
3797         err = nft_ctx_init_from_setattr(&ctx, net, skb, nlh, nla, extack,
3798                                         genmask);
3799         if (err < 0)
3800                 return err;
3801 
3802         if (nlh->nlmsg_flags & NLM_F_DUMP) {
3803                 struct netlink_dump_control c = {
3804                         .start = nf_tables_dump_sets_start,
3805                         .dump = nf_tables_dump_sets,
3806                         .done = nf_tables_dump_sets_done,
3807                         .data = &ctx,
3808                         .module = THIS_MODULE,
3809                 };
3810 
3811                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
3812         }
3813 
3814         /* Only accept unspec with dump */
3815         if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
3816                 return -EAFNOSUPPORT;
3817         if (!nla[NFTA_SET_TABLE])
3818                 return -EINVAL;
3819 
3820         set = nft_set_lookup(ctx.table, nla[NFTA_SET_NAME], genmask);
3821         if (IS_ERR(set))
3822                 return PTR_ERR(set);
3823 
3824         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
3825         if (skb2 == NULL)
3826                 return -ENOMEM;
3827 
3828         err = nf_tables_fill_set(skb2, &ctx, set, NFT_MSG_NEWSET, 0);
3829         if (err < 0)
3830                 goto err;
3831 
3832         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
3833 
3834 err:
3835         kfree_skb(skb2);
3836         return err;
3837 }
3838 
3839 static const struct nla_policy nft_concat_policy[NFTA_SET_FIELD_MAX + 1] = {
3840         [NFTA_SET_FIELD_LEN]    = { .type = NLA_U32 },
3841 };
3842 
3843 static int nft_set_desc_concat_parse(const struct nlattr *attr,
3844                                      struct nft_set_desc *desc)
3845 {
3846         struct nlattr *tb[NFTA_SET_FIELD_MAX + 1];
3847         u32 len;
3848         int err;
3849 
3850         err = nla_parse_nested_deprecated(tb, NFTA_SET_FIELD_MAX, attr,
3851                                           nft_concat_policy, NULL);
3852         if (err < 0)
3853                 return err;
3854 
3855         if (!tb[NFTA_SET_FIELD_LEN])
3856                 return -EINVAL;
3857 
3858         len = ntohl(nla_get_be32(tb[NFTA_SET_FIELD_LEN]));
3859 
3860         if (len * BITS_PER_BYTE / 32 > NFT_REG32_COUNT)
3861                 return -E2BIG;
3862 
3863         desc->field_len[desc->field_count++] = len;
3864 
3865         return 0;
3866 }
3867 
3868 static int nft_set_desc_concat(struct nft_set_desc *desc,
3869                                const struct nlattr *nla)
3870 {
3871         struct nlattr *attr;
3872         int rem, err;
3873 
3874         nla_for_each_nested(attr, nla, rem) {
3875                 if (nla_type(attr) != NFTA_LIST_ELEM)
3876                         return -EINVAL;
3877 
3878                 err = nft_set_desc_concat_parse(attr, desc);
3879                 if (err < 0)
3880                         return err;
3881         }
3882 
3883         return 0;
3884 }
3885 
3886 static int nf_tables_set_desc_parse(struct nft_set_desc *desc,
3887                                     const struct nlattr *nla)
3888 {
3889         struct nlattr *da[NFTA_SET_DESC_MAX + 1];
3890         int err;
3891 
3892         err = nla_parse_nested_deprecated(da, NFTA_SET_DESC_MAX, nla,
3893                                           nft_set_desc_policy, NULL);
3894         if (err < 0)
3895                 return err;
3896 
3897         if (da[NFTA_SET_DESC_SIZE] != NULL)
3898                 desc->size = ntohl(nla_get_be32(da[NFTA_SET_DESC_SIZE]));
3899         if (da[NFTA_SET_DESC_CONCAT])
3900                 err = nft_set_desc_concat(desc, da[NFTA_SET_DESC_CONCAT]);
3901 
3902         return err;
3903 }
3904 
3905 static int nf_tables_newset(struct net *net, struct sock *nlsk,
3906                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3907                             const struct nlattr * const nla[],
3908                             struct netlink_ext_ack *extack)
3909 {
3910         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3911         u8 genmask = nft_genmask_next(net);
3912         int family = nfmsg->nfgen_family;
3913         const struct nft_set_ops *ops;
3914         struct nft_table *table;
3915         struct nft_set *set;
3916         struct nft_ctx ctx;
3917         char *name;
3918         u64 size;
3919         u64 timeout;
3920         u32 ktype, dtype, flags, policy, gc_int, objtype;
3921         struct nft_set_desc desc;
3922         unsigned char *udata;
3923         u16 udlen;
3924         int err;
3925         int i;
3926 
3927         if (nla[NFTA_SET_TABLE] == NULL ||
3928             nla[NFTA_SET_NAME] == NULL ||
3929             nla[NFTA_SET_KEY_LEN] == NULL ||
3930             nla[NFTA_SET_ID] == NULL)
3931                 return -EINVAL;
3932 
3933         memset(&desc, 0, sizeof(desc));
3934 
3935         ktype = NFT_DATA_VALUE;
3936         if (nla[NFTA_SET_KEY_TYPE] != NULL) {
3937                 ktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));
3938                 if ((ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)
3939                         return -EINVAL;
3940         }
3941 
3942         desc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));
3943         if (desc.klen == 0 || desc.klen > NFT_DATA_VALUE_MAXLEN)
3944                 return -EINVAL;
3945 
3946         flags = 0;
3947         if (nla[NFTA_SET_FLAGS] != NULL) {
3948                 flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
3949                 if (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |
3950                               NFT_SET_INTERVAL | NFT_SET_TIMEOUT |
3951                               NFT_SET_MAP | NFT_SET_EVAL |
3952                               NFT_SET_OBJECT | NFT_SET_CONCAT))
3953                         return -EOPNOTSUPP;
3954                 /* Only one of these operations is supported */
3955                 if ((flags & (NFT_SET_MAP | NFT_SET_OBJECT)) ==
3956                              (NFT_SET_MAP | NFT_SET_OBJECT))
3957                         return -EOPNOTSUPP;
3958                 if ((flags & (NFT_SET_EVAL | NFT_SET_OBJECT)) ==
3959                              (NFT_SET_EVAL | NFT_SET_OBJECT))
3960                         return -EOPNOTSUPP;
3961         }
3962 
3963         dtype = 0;
3964         if (nla[NFTA_SET_DATA_TYPE] != NULL) {
3965                 if (!(flags & NFT_SET_MAP))
3966                         return -EINVAL;
3967 
3968                 dtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));
3969                 if ((dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&
3970                     dtype != NFT_DATA_VERDICT)
3971                         return -EINVAL;
3972 
3973                 if (dtype != NFT_DATA_VERDICT) {
3974                         if (nla[NFTA_SET_DATA_LEN] == NULL)
3975                                 return -EINVAL;
3976                         desc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));
3977                         if (desc.dlen == 0 || desc.dlen > NFT_DATA_VALUE_MAXLEN)
3978                                 return -EINVAL;
3979                 } else
3980                         desc.dlen = sizeof(struct nft_verdict);
3981         } else if (flags & NFT_SET_MAP)
3982                 return -EINVAL;
3983 
3984         if (nla[NFTA_SET_OBJ_TYPE] != NULL) {
3985                 if (!(flags & NFT_SET_OBJECT))
3986                         return -EINVAL;
3987 
3988                 objtype = ntohl(nla_get_be32(nla[NFTA_SET_OBJ_TYPE]));
3989                 if (objtype == NFT_OBJECT_UNSPEC ||
3990                     objtype > NFT_OBJECT_MAX)
3991                         return -EOPNOTSUPP;
3992         } else if (flags & NFT_SET_OBJECT)
3993                 return -EINVAL;
3994         else
3995                 objtype = NFT_OBJECT_UNSPEC;
3996 
3997         timeout = 0;
3998         if (nla[NFTA_SET_TIMEOUT] != NULL) {
3999                 if (!(flags & NFT_SET_TIMEOUT))
4000                         return -EINVAL;
4001 
4002                 err = nf_msecs_to_jiffies64(nla[NFTA_SET_TIMEOUT], &timeout);
4003                 if (err)
4004                         return err;
4005         }
4006         gc_int = 0;
4007         if (nla[NFTA_SET_GC_INTERVAL] != NULL) {
4008                 if (!(flags & NFT_SET_TIMEOUT))
4009                         return -EINVAL;
4010                 gc_int = ntohl(nla_get_be32(nla[NFTA_SET_GC_INTERVAL]));
4011         }
4012 
4013         policy = NFT_SET_POL_PERFORMANCE;
4014         if (nla[NFTA_SET_POLICY] != NULL)
4015                 policy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));
4016 
4017         if (nla[NFTA_SET_DESC] != NULL) {
4018                 err = nf_tables_set_desc_parse(&desc, nla[NFTA_SET_DESC]);
4019                 if (err < 0)
4020                         return err;
4021         }
4022 
4023         table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family, genmask);
4024         if (IS_ERR(table)) {
4025                 NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
4026                 return PTR_ERR(table);
4027         }
4028 
4029         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
4030 
4031         set = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);
4032         if (IS_ERR(set)) {
4033                 if (PTR_ERR(set) != -ENOENT) {
4034                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
4035                         return PTR_ERR(set);
4036                 }
4037         } else {
4038                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
4039                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
4040                         return -EEXIST;
4041                 }
4042                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
4043                         return -EOPNOTSUPP;
4044 
4045                 return 0;
4046         }
4047 
4048         if (!(nlh->nlmsg_flags & NLM_F_CREATE))
4049                 return -ENOENT;
4050 
4051         ops = nft_select_set_ops(&ctx, nla, &desc, policy);
4052         if (IS_ERR(ops))
4053                 return PTR_ERR(ops);
4054 
4055         udlen = 0;
4056         if (nla[NFTA_SET_USERDATA])
4057                 udlen = nla_len(nla[NFTA_SET_USERDATA]);
4058 
4059         size = 0;
4060         if (ops->privsize != NULL)
4061                 size = ops->privsize(nla, &desc);
4062 
4063         set = kvzalloc(sizeof(*set) + size + udlen, GFP_KERNEL);
4064         if (!set) {
4065                 err = -ENOMEM;
4066                 goto err1;
4067         }
4068 
4069         name = nla_strdup(nla[NFTA_SET_NAME], GFP_KERNEL);
4070         if (!name) {
4071                 err = -ENOMEM;
4072                 goto err2;
4073         }
4074 
4075         err = nf_tables_set_alloc_name(&ctx, set, name);
4076         kfree(name);
4077         if (err < 0)
4078                 goto err2;
4079 
4080         udata = NULL;
4081         if (udlen) {
4082                 udata = set->data + size;
4083                 nla_memcpy(udata, nla[NFTA_SET_USERDATA], udlen);
4084         }
4085 
4086         INIT_LIST_HEAD(&set->bindings);
4087         set->table = table;
4088         write_pnet(&set->net, net);
4089         set->ops   = ops;
4090         set->ktype = ktype;
4091         set->klen  = desc.klen;
4092         set->dtype = dtype;
4093         set->objtype = objtype;
4094         set->dlen  = desc.dlen;
4095         set->flags = flags;
4096         set->size  = desc.size;
4097         set->policy = policy;
4098         set->udlen  = udlen;
4099         set->udata  = udata;
4100         set->timeout = timeout;
4101         set->gc_int = gc_int;
4102         set->handle = nf_tables_alloc_handle(table);
4103 
4104         set->field_count = desc.field_count;
4105         for (i = 0; i < desc.field_count; i++)
4106                 set->field_len[i] = desc.field_len[i];
4107 
4108         err = ops->init(set, &desc, nla);
4109         if (err < 0)
4110                 goto err3;
4111 
4112         err = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);
4113         if (err < 0)
4114                 goto err4;
4115 
4116         list_add_tail_rcu(&set->list, &table->sets);
4117         table->use++;
4118         return 0;
4119 
4120 err4:
4121         ops->destroy(set);
4122 err3:
4123         kfree(set->name);
4124 err2:
4125         kvfree(set);
4126 err1:
4127         module_put(to_set_type(ops)->owner);
4128         return err;
4129 }
4130 
4131 static void nft_set_destroy(struct nft_set *set)
4132 {
4133         if (WARN_ON(set->use > 0))
4134                 return;
4135 
4136         set->ops->destroy(set);
4137         module_put(to_set_type(set->ops)->owner);
4138         kfree(set->name);
4139         kvfree(set);
4140 }
4141 
4142 static int nf_tables_delset(struct net *net, struct sock *nlsk,
4143                             struct sk_buff *skb, const struct nlmsghdr *nlh,
4144                             const struct nlattr * const nla[],
4145                             struct netlink_ext_ack *extack)
4146 {
4147         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
4148         u8 genmask = nft_genmask_next(net);
4149         const struct nlattr *attr;
4150         struct nft_set *set;
4151         struct nft_ctx ctx;
4152         int err;
4153 
4154         if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
4155                 return -EAFNOSUPPORT;
4156         if (nla[NFTA_SET_TABLE] == NULL)
4157                 return -EINVAL;
4158 
4159         err = nft_ctx_init_from_setattr(&ctx, net, skb, nlh, nla, extack,
4160                                         genmask);
4161         if (err < 0)
4162                 return err;
4163 
4164         if (nla[NFTA_SET_HANDLE]) {
4165                 attr = nla[NFTA_SET_HANDLE];
4166                 set = nft_set_lookup_byhandle(ctx.table, attr, genmask);
4167         } else {
4168                 attr = nla[NFTA_SET_NAME];
4169                 set = nft_set_lookup(ctx.table, attr, genmask);
4170         }
4171 
4172         if (IS_ERR(set)) {
4173                 NL_SET_BAD_ATTR(extack, attr);
4174                 return PTR_ERR(set);
4175         }
4176         if (set->use ||
4177             (nlh->nlmsg_flags & NLM_F_NONREC && atomic_read(&set->nelems) > 0)) {
4178                 NL_SET_BAD_ATTR(extack, attr);
4179                 return -EBUSY;
4180         }
4181 
4182         return nft_delset(&ctx, set);
4183 }
4184 
4185 static int nf_tables_bind_check_setelem(const struct nft_ctx *ctx,
4186                                         struct nft_set *set,
4187                                         const struct nft_set_iter *iter,
4188                                         struct nft_set_elem *elem)
4189 {
4190         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
4191         enum nft_registers dreg;
4192 
4193         dreg = nft_type_to_reg(set->dtype);
4194         return nft_validate_register_store(ctx, dreg, nft_set_ext_data(ext),
4195                                            set->dtype == NFT_DATA_VERDICT ?
4196                                            NFT_DATA_VERDICT : NFT_DATA_VALUE,
4197                                            set->dlen);
4198 }
4199 
4200 int nf_tables_bind_set(const struct nft_ctx *ctx, struct nft_set *set,
4201                        struct nft_set_binding *binding)
4202 {
4203         struct nft_set_binding *i;
4204         struct nft_set_iter iter;
4205 
4206         if (set->use == UINT_MAX)
4207                 return -EOVERFLOW;
4208 
4209         if (!list_empty(&set->bindings) && nft_set_is_anonymous(set))
4210                 return -EBUSY;
4211 
4212         if (binding->flags & NFT_SET_MAP) {
4213                 /* If the set is already bound to the same chain all
4214                  * jumps are already validated for that chain.
4215                  */
4216                 list_for_each_entry(i, &set->bindings, list) {
4217                         if (i->flags & NFT_SET_MAP &&
4218                             i->chain == binding->chain)
4219                                 goto bind;
4220                 }
4221 
4222                 iter.genmask    = nft_genmask_next(ctx->net);
4223                 iter.skip       = 0;
4224                 iter.count      = 0;
4225                 iter.err        = 0;
4226                 iter.fn         = nf_tables_bind_check_setelem;
4227 
4228                 set->ops->walk(ctx, set, &iter);
4229                 if (iter.err < 0)
4230                         return iter.err;
4231         }
4232 bind:
4233         binding->chain = ctx->chain;
4234         list_add_tail_rcu(&binding->list, &set->bindings);
4235         nft_set_trans_bind(ctx, set);
4236         set->use++;
4237 
4238         return 0;
4239 }
4240 EXPORT_SYMBOL_GPL(nf_tables_bind_set);
4241 
4242 static void nf_tables_unbind_set(const struct nft_ctx *ctx, struct nft_set *set,
4243                                  struct nft_set_binding *binding, bool event)
4244 {
4245         list_del_rcu(&binding->list);
4246 
4247         if (list_empty(&set->bindings) && nft_set_is_anonymous(set)) {
4248                 list_del_rcu(&set->list);
4249                 if (event)
4250                         nf_tables_set_notify(ctx, set, NFT_MSG_DELSET,
4251                                              GFP_KERNEL);
4252         }
4253 }
4254 
4255 void nf_tables_deactivate_set(const struct nft_ctx *ctx, struct nft_set *set,
4256                               struct nft_set_binding *binding,
4257                               enum nft_trans_phase phase)
4258 {
4259         switch (phase) {
4260         case NFT_TRANS_PREPARE:
4261                 set->use--;
4262                 return;
4263         case NFT_TRANS_ABORT:
4264         case NFT_TRANS_RELEASE:
4265                 set->use--;
4266                 /* fall through */
4267         default:
4268                 nf_tables_unbind_set(ctx, set, binding,
4269                                      phase == NFT_TRANS_COMMIT);
4270         }
4271 }
4272 EXPORT_SYMBOL_GPL(nf_tables_deactivate_set);
4273 
4274 void nf_tables_destroy_set(const struct nft_ctx *ctx, struct nft_set *set)
4275 {
4276         if (list_empty(&set->bindings) && nft_set_is_anonymous(set))
4277                 nft_set_destroy(set);
4278 }
4279 EXPORT_SYMBOL_GPL(nf_tables_destroy_set);
4280 
4281 const struct nft_set_ext_type nft_set_ext_types[] = {
4282         [NFT_SET_EXT_KEY]               = {
4283                 .align  = __alignof__(u32),
4284         },
4285         [NFT_SET_EXT_DATA]              = {
4286                 .align  = __alignof__(u32),
4287         },
4288         [NFT_SET_EXT_EXPR]              = {
4289                 .align  = __alignof__(struct nft_expr),
4290         },
4291         [NFT_SET_EXT_OBJREF]            = {
4292                 .len    = sizeof(struct nft_object *),
4293                 .align  = __alignof__(struct nft_object *),
4294         },
4295         [NFT_SET_EXT_FLAGS]             = {
4296                 .len    = sizeof(u8),
4297                 .align  = __alignof__(u8),
4298         },
4299         [NFT_SET_EXT_TIMEOUT]           = {
4300                 .len    = sizeof(u64),
4301                 .align  = __alignof__(u64),
4302         },
4303         [NFT_SET_EXT_EXPIRATION]        = {
4304                 .len    = sizeof(u64),
4305                 .align  = __alignof__(u64),
4306         },
4307         [NFT_SET_EXT_USERDATA]          = {
4308                 .len    = sizeof(struct nft_userdata),
4309                 .align  = __alignof__(struct nft_userdata),
4310         },
4311         [NFT_SET_EXT_KEY_END]           = {
4312                 .align  = __alignof__(u32),
4313         },
4314 };
4315 EXPORT_SYMBOL_GPL(nft_set_ext_types);
4316 
4317 /*
4318  * Set elements
4319  */
4320 
4321 static const struct nla_policy nft_set_elem_policy[NFTA_SET_ELEM_MAX + 1] = {
4322         [NFTA_SET_ELEM_KEY]             = { .type = NLA_NESTED },
4323         [NFTA_SET_ELEM_DATA]            = { .type = NLA_NESTED },
4324         [NFTA_SET_ELEM_FLAGS]           = { .type = NLA_U32 },
4325         [NFTA_SET_ELEM_TIMEOUT]         = { .type = NLA_U64 },
4326         [NFTA_SET_ELEM_EXPIRATION]      = { .type = NLA_U64 },
4327         [NFTA_SET_ELEM_USERDATA]        = { .type = NLA_BINARY,
4328                                             .len = NFT_USERDATA_MAXLEN },
4329         [NFTA_SET_ELEM_EXPR]            = { .type = NLA_NESTED },
4330         [NFTA_SET_ELEM_OBJREF]          = { .type = NLA_STRING,
4331                                             .len = NFT_OBJ_MAXNAMELEN - 1 },
4332         [NFTA_SET_ELEM_KEY_END]         = { .type = NLA_NESTED },
4333 };
4334 
4335 static const struct nla_policy nft_set_elem_list_policy[NFTA_SET_ELEM_LIST_MAX + 1] = {
4336         [NFTA_SET_ELEM_LIST_TABLE]      = { .type = NLA_STRING,
4337                                             .len = NFT_TABLE_MAXNAMELEN - 1 },
4338         [NFTA_SET_ELEM_LIST_SET]        = { .type = NLA_STRING,
4339                                             .len = NFT_SET_MAXNAMELEN - 1 },
4340         [NFTA_SET_ELEM_LIST_ELEMENTS]   = { .type = NLA_NESTED },
4341         [NFTA_SET_ELEM_LIST_SET_ID]     = { .type = NLA_U32 },
4342 };
4343 
4344 static int nft_ctx_init_from_elemattr(struct nft_ctx *ctx, struct net *net,
4345                                       const struct sk_buff *skb,
4346                                       const struct nlmsghdr *nlh,
4347                                       const struct nlattr * const nla[],
4348                                       struct netlink_ext_ack *extack,
4349                                       u8 genmask)
4350 {
4351         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
4352         int family = nfmsg->nfgen_family;
4353         struct nft_table *table;
4354 
4355         table = nft_table_lookup(net, nla[NFTA_SET_ELEM_LIST_TABLE], family,
4356                                  genmask);
4357         if (IS_ERR(table)) {
4358                 NL_SET_BAD_ATTR(extack, nla[NFTA_SET_ELEM_LIST_TABLE]);
4359                 return PTR_ERR(table);
4360         }
4361 
4362         nft_ctx_init(ctx, net, skb, nlh, family, table, NULL, nla);
4363         return 0;
4364 }
4365 
4366 static int nf_tables_fill_setelem(struct sk_buff *skb,
4367                                   const struct nft_set *set,
4368                                   const struct nft_set_elem *elem)
4369 {
4370         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
4371         unsigned char *b = skb_tail_pointer(skb);
4372         struct nlattr *nest;
4373 
4374         nest = nla_nest_start_noflag(skb, NFTA_LIST_ELEM);
4375         if (nest == NULL)
4376                 goto nla_put_failure;
4377 
4378         if (nft_data_dump(skb, NFTA_SET_ELEM_KEY, nft_set_ext_key(ext),
4379                           NFT_DATA_VALUE, set->klen) < 0)
4380                 goto nla_put_failure;
4381 
4382         if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY_END) &&
4383             nft_data_dump(skb, NFTA_SET_ELEM_KEY_END, nft_set_ext_key_end(ext),
4384                           NFT_DATA_VALUE, set->klen) < 0)
4385                 goto nla_put_failure;
4386 
4387         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
4388             nft_data_dump(skb, NFTA_SET_ELEM_DATA, nft_set_ext_data(ext),
4389                           set->dtype == NFT_DATA_VERDICT ? NFT_DATA_VERDICT : NFT_DATA_VALUE,
4390                           set->dlen) < 0)
4391                 goto nla_put_failure;
4392 
4393         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPR) &&
4394             nft_expr_dump(skb, NFTA_SET_ELEM_EXPR, nft_set_ext_expr(ext)) < 0)
4395                 goto nla_put_failure;
4396 
4397         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
4398             nla_put_string(skb, NFTA_SET_ELEM_OBJREF,
4399                            (*nft_set_ext_obj(ext))->key.name) < 0)
4400                 goto nla_put_failure;
4401 
4402         if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
4403             nla_put_be32(skb, NFTA_SET_ELEM_FLAGS,
4404                          htonl(*nft_set_ext_flags(ext))))
4405                 goto nla_put_failure;
4406 
4407         if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT) &&
4408             nla_put_be64(skb, NFTA_SET_ELEM_TIMEOUT,
4409                          nf_jiffies64_to_msecs(*nft_set_ext_timeout(ext)),
4410                          NFTA_SET_ELEM_PAD))
4411                 goto nla_put_failure;
4412 
4413         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION)) {
4414                 u64 expires, now = get_jiffies_64();
4415 
4416                 expires = *nft_set_ext_expiration(ext);
4417                 if (time_before64(now, expires))
4418                         expires -= now;
4419                 else
4420                         expires = 0;
4421 
4422                 if (nla_put_be64(skb, NFTA_SET_ELEM_EXPIRATION,
4423                                  nf_jiffies64_to_msecs(expires),
4424                                  NFTA_SET_ELEM_PAD))
4425                         goto nla_put_failure;
4426         }
4427 
4428         if (nft_set_ext_exists(ext, NFT_SET_EXT_USERDATA)) {
4429                 struct nft_userdata *udata;
4430 
4431                 udata = nft_set_ext_userdata(ext);
4432                 if (nla_put(skb, NFTA_SET_ELEM_USERDATA,
4433                             udata->len + 1, udata->data))
4434                         goto nla_put_failure;
4435         }
4436 
4437         nla_nest_end(skb, nest);
4438         return 0;
4439 
4440 nla_put_failure:
4441         nlmsg_trim(skb, b);
4442         return -EMSGSIZE;
4443 }
4444 
4445 struct nft_set_dump_args {
4446         const struct netlink_callback   *cb;
4447         struct nft_set_iter             iter;
4448         struct sk_buff                  *skb;
4449 };
4450 
4451 static int nf_tables_dump_setelem(const struct nft_ctx *ctx,
4452                                   struct nft_set *set,
4453                                   const struct nft_set_iter *iter,
4454                                   struct nft_set_elem *elem)
4455 {
4456         struct nft_set_dump_args *args;
4457 
4458         args = container_of(iter, struct nft_set_dump_args, iter);
4459         return nf_tables_fill_setelem(args->skb, set, elem);
4460 }
4461 
4462 struct nft_set_dump_ctx {
4463         const struct nft_set    *set;
4464         struct nft_ctx          ctx;
4465 };
4466 
4467 static int nf_tables_dump_set(struct sk_buff *skb, struct netlink_callback *cb)
4468 {
4469         struct nft_set_dump_ctx *dump_ctx = cb->data;
4470         struct net *net = sock_net(skb->sk);
4471         struct nft_table *table;
4472         struct nft_set *set;
4473         struct nft_set_dump_args args;
4474         bool set_found = false;
4475         struct nfgenmsg *nfmsg;
4476         struct nlmsghdr *nlh;
4477         struct nlattr *nest;
4478         u32 portid, seq;
4479         int event;
4480 
4481         rcu_read_lock();
4482         list_for_each_entry_rcu(table, &net->nft.tables, list) {
4483                 if (dump_ctx->ctx.family != NFPROTO_UNSPEC &&
4484                     dump_ctx->ctx.family != table->family)
4485                         continue;
4486 
4487                 if (table != dump_ctx->ctx.table)
4488                         continue;
4489 
4490                 list_for_each_entry_rcu(set, &table->sets, list) {
4491                         if (set == dump_ctx->set) {
4492                                 set_found = true;
4493                                 break;
4494                         }
4495                 }
4496                 break;
4497         }
4498 
4499         if (!set_found) {
4500                 rcu_read_unlock();
4501                 return -ENOENT;
4502         }
4503 
4504         event  = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWSETELEM);
4505         portid = NETLINK_CB(cb->skb).portid;
4506         seq    = cb->nlh->nlmsg_seq;
4507 
4508         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
4509                         NLM_F_MULTI);
4510         if (nlh == NULL)
4511                 goto nla_put_failure;
4512 
4513         nfmsg = nlmsg_data(nlh);
4514         nfmsg->nfgen_family = table->family;
4515         nfmsg->version      = NFNETLINK_V0;
4516         nfmsg->res_id       = htons(net->nft.base_seq & 0xffff);
4517 
4518         if (nla_put_string(skb, NFTA_SET_ELEM_LIST_TABLE, table->name))
4519                 goto nla_put_failure;
4520         if (nla_put_string(skb, NFTA_SET_ELEM_LIST_SET, set->name))
4521                 goto nla_put_failure;
4522 
4523         nest = nla_nest_start_noflag(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
4524         if (nest == NULL)
4525                 goto nla_put_failure;
4526 
4527         args.cb                 = cb;
4528         args.skb                = skb;
4529         args.iter.genmask       = nft_genmask_cur(net);
4530         args.iter.skip          = cb->args[0];
4531         args.iter.count         = 0;
4532         args.iter.err           = 0;
4533         args.iter.fn            = nf_tables_dump_setelem;
4534         set->ops->walk(&dump_ctx->ctx, set, &args.iter);
4535         rcu_read_unlock();
4536 
4537         nla_nest_end(skb, nest);
4538         nlmsg_end(skb, nlh);
4539 
4540         if (args.iter.err && args.iter.err != -EMSGSIZE)
4541                 return args.iter.err;
4542         if (args.iter.count == cb->args[0])
4543                 return 0;
4544 
4545         cb->args[0] = args.iter.count;
4546         return skb->len;
4547 
4548 nla_put_failure:
4549         rcu_read_unlock();
4550         return -ENOSPC;
4551 }
4552 
4553 static int nf_tables_dump_set_start(struct netlink_callback *cb)
4554 {
4555         struct nft_set_dump_ctx *dump_ctx = cb->data;
4556 
4557         cb->data = kmemdup(dump_ctx, sizeof(*dump_ctx), GFP_ATOMIC);
4558 
4559         return cb->data ? 0 : -ENOMEM;
4560 }
4561 
4562 static int nf_tables_dump_set_done(struct netlink_callback *cb)
4563 {
4564         kfree(cb->data);
4565         return 0;
4566 }
4567 
4568 static int nf_tables_fill_setelem_info(struct sk_buff *skb,
4569                                        const struct nft_ctx *ctx, u32 seq,
4570                                        u32 portid, int event, u16 flags,
4571                                        const struct nft_set *set,
4572                                        const struct nft_set_elem *elem)
4573 {
4574         struct nfgenmsg *nfmsg;
4575         struct nlmsghdr *nlh;
4576         struct nlattr *nest;
4577         int err;
4578 
4579         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
4580         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
4581                         flags);
4582         if (nlh == NULL)
4583                 goto nla_put_failure;
4584 
4585         nfmsg = nlmsg_data(nlh);
4586         nfmsg->nfgen_family     = ctx->family;
4587         nfmsg->version          = NFNETLINK_V0;
4588         nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
4589 
4590         if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
4591                 goto nla_put_failure;
4592         if (nla_put_string(skb, NFTA_SET_NAME, set->name))
4593                 goto nla_put_failure;
4594 
4595         nest = nla_nest_start_noflag(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
4596         if (nest == NULL)
4597                 goto nla_put_failure;
4598 
4599         err = nf_tables_fill_setelem(skb, set, elem);
4600         if (err < 0)
4601                 goto nla_put_failure;
4602 
4603         nla_nest_end(skb, nest);
4604 
4605         nlmsg_end(skb, nlh);
4606         return 0;
4607 
4608 nla_put_failure:
4609         nlmsg_trim(skb, nlh);
4610         return -1;
4611 }
4612 
4613 static int nft_setelem_parse_flags(const struct nft_set *set,
4614                                    const struct nlattr *attr, u32 *flags)
4615 {
4616         if (attr == NULL)
4617                 return 0;
4618 
4619         *flags = ntohl(nla_get_be32(attr));
4620         if (*flags & ~NFT_SET_ELEM_INTERVAL_END)
4621                 return -EINVAL;
4622         if (!(set->flags & NFT_SET_INTERVAL) &&
4623             *flags & NFT_SET_ELEM_INTERVAL_END)
4624                 return -EINVAL;
4625 
4626         return 0;
4627 }
4628 
4629 static int nft_setelem_parse_key(struct nft_ctx *ctx, struct nft_set *set,
4630                                  struct nft_data *key, struct nlattr *attr)
4631 {
4632         struct nft_data_desc desc;
4633         int err;
4634 
4635         err = nft_data_init(ctx, key, NFT_DATA_VALUE_MAXLEN, &desc, attr);
4636         if (err < 0)
4637                 return err;
4638 
4639         if (desc.type != NFT_DATA_VALUE || desc.len != set->klen) {
4640                 nft_data_release(key, desc.type);
4641                 return -EINVAL;
4642         }
4643 
4644         return 0;
4645 }
4646 
4647 static int nft_get_set_elem(struct nft_ctx *ctx, struct nft_set *set,
4648                             const struct nlattr *attr)
4649 {
4650         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4651         struct nft_set_elem elem;
4652         struct sk_buff *skb;
4653         uint32_t flags = 0;
4654         void *priv;
4655         int err;
4656 
4657         err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
4658                                           nft_set_elem_policy, NULL);
4659         if (err < 0)
4660                 return err;
4661 
4662         if (!nla[NFTA_SET_ELEM_KEY])
4663                 return -EINVAL;
4664 
4665         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4666         if (err < 0)
4667                 return err;
4668 
4669         err = nft_setelem_parse_key(ctx, set, &elem.key.val,
4670                                     nla[NFTA_SET_ELEM_KEY]);
4671         if (err < 0)
4672                 return err;
4673 
4674         if (nla[NFTA_SET_ELEM_KEY_END]) {
4675                 err = nft_setelem_parse_key(ctx, set, &elem.key_end.val,
4676                                             nla[NFTA_SET_ELEM_KEY_END]);
4677                 if (err < 0)
4678                         return err;
4679         }
4680 
4681         priv = set->ops->get(ctx->net, set, &elem, flags);
4682         if (IS_ERR(priv))
4683                 return PTR_ERR(priv);
4684 
4685         elem.priv = priv;
4686 
4687         err = -ENOMEM;
4688         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_ATOMIC);
4689         if (skb == NULL)
4690                 goto err1;
4691 
4692         err = nf_tables_fill_setelem_info(skb, ctx, ctx->seq, ctx->portid,
4693                                           NFT_MSG_NEWSETELEM, 0, set, &elem);
4694         if (err < 0)
4695                 goto err2;
4696 
4697         err = nfnetlink_unicast(skb, ctx->net, ctx->portid, MSG_DONTWAIT);
4698         /* This avoids a loop in nfnetlink. */
4699         if (err < 0)
4700                 goto err1;
4701 
4702         return 0;
4703 err2:
4704         kfree_skb(skb);
4705 err1:
4706         /* this avoids a loop in nfnetlink. */
4707         return err == -EAGAIN ? -ENOBUFS : err;
4708 }
4709 
4710 /* called with rcu_read_lock held */
4711 static int nf_tables_getsetelem(struct net *net, struct sock *nlsk,
4712                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
4713                                 const struct nlattr * const nla[],
4714                                 struct netlink_ext_ack *extack)
4715 {
4716         u8 genmask = nft_genmask_cur(net);
4717         struct nft_set *set;
4718         struct nlattr *attr;
4719         struct nft_ctx ctx;
4720         int rem, err = 0;
4721 
4722         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4723                                          genmask);
4724         if (err < 0)
4725                 return err;
4726 
4727         set = nft_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
4728         if (IS_ERR(set))
4729                 return PTR_ERR(set);
4730 
4731         if (nlh->nlmsg_flags & NLM_F_DUMP) {
4732                 struct netlink_dump_control c = {
4733                         .start = nf_tables_dump_set_start,
4734                         .dump = nf_tables_dump_set,
4735                         .done = nf_tables_dump_set_done,
4736                         .module = THIS_MODULE,
4737                 };
4738                 struct nft_set_dump_ctx dump_ctx = {
4739                         .set = set,
4740                         .ctx = ctx,
4741                 };
4742 
4743                 c.data = &dump_ctx;
4744                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
4745         }
4746 
4747         if (!nla[NFTA_SET_ELEM_LIST_ELEMENTS])
4748                 return -EINVAL;
4749 
4750         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4751                 err = nft_get_set_elem(&ctx, set, attr);
4752                 if (err < 0)
4753                         break;
4754         }
4755 
4756         return err;
4757 }
4758 
4759 static void nf_tables_setelem_notify(const struct nft_ctx *ctx,
4760                                      const struct nft_set *set,
4761                                      const struct nft_set_elem *elem,
4762                                      int event, u16 flags)
4763 {
4764         struct net *net = ctx->net;
4765         u32 portid = ctx->portid;
4766         struct sk_buff *skb;
4767         int err;
4768 
4769         if (!ctx->report && !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
4770                 return;
4771 
4772         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
4773         if (skb == NULL)
4774                 goto err;
4775 
4776         err = nf_tables_fill_setelem_info(skb, ctx, 0, portid, event, flags,
4777                                           set, elem);
4778         if (err < 0) {
4779                 kfree_skb(skb);
4780                 goto err;
4781         }
4782 
4783         nfnetlink_send(skb, net, portid, NFNLGRP_NFTABLES, ctx->report,
4784                        GFP_KERNEL);
4785         return;
4786 err:
4787         nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
4788 }
4789 
4790 static struct nft_trans *nft_trans_elem_alloc(struct nft_ctx *ctx,
4791                                               int msg_type,
4792                                               struct nft_set *set)
4793 {
4794         struct nft_trans *trans;
4795 
4796         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_elem));
4797         if (trans == NULL)
4798                 return NULL;
4799 
4800         nft_trans_elem_set(trans) = set;
4801         return trans;
4802 }
4803 
4804 void *nft_set_elem_init(const struct nft_set *set,
4805                         const struct nft_set_ext_tmpl *tmpl,
4806                         const u32 *key, const u32 *key_end,
4807                         const u32 *data, u64 timeout, u64 expiration, gfp_t gfp)
4808 {
4809         struct nft_set_ext *ext;
4810         void *elem;
4811 
4812         elem = kzalloc(set->ops->elemsize + tmpl->len, gfp);
4813         if (elem == NULL)
4814                 return NULL;
4815 
4816         ext = nft_set_elem_ext(set, elem);
4817         nft_set_ext_init(ext, tmpl);
4818 
4819         memcpy(nft_set_ext_key(ext), key, set->klen);
4820         if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY_END))
4821                 memcpy(nft_set_ext_key_end(ext), key_end, set->klen);
4822         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4823                 memcpy(nft_set_ext_data(ext), data, set->dlen);
4824         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION)) {
4825                 *nft_set_ext_expiration(ext) = get_jiffies_64() + expiration;
4826                 if (expiration == 0)
4827                         *nft_set_ext_expiration(ext) += timeout;
4828         }
4829         if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT))
4830                 *nft_set_ext_timeout(ext) = timeout;
4831 
4832         return elem;
4833 }
4834 
4835 void nft_set_elem_destroy(const struct nft_set *set, void *elem,
4836                           bool destroy_expr)
4837 {
4838         struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
4839         struct nft_ctx ctx = {
4840                 .net    = read_pnet(&set->net),
4841                 .family = set->table->family,
4842         };
4843 
4844         nft_data_release(nft_set_ext_key(ext), NFT_DATA_VALUE);
4845         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4846                 nft_data_release(nft_set_ext_data(ext), set->dtype);
4847         if (destroy_expr && nft_set_ext_exists(ext, NFT_SET_EXT_EXPR)) {
4848                 struct nft_expr *expr = nft_set_ext_expr(ext);
4849 
4850                 if (expr->ops->destroy_clone) {
4851                         expr->ops->destroy_clone(&ctx, expr);
4852                         module_put(expr->ops->type->owner);
4853                 } else {
4854                         nf_tables_expr_destroy(&ctx, expr);
4855                 }
4856         }
4857         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4858                 (*nft_set_ext_obj(ext))->use--;
4859         kfree(elem);
4860 }
4861 EXPORT_SYMBOL_GPL(nft_set_elem_destroy);
4862 
4863 /* Only called from commit path, nft_set_elem_deactivate() already deals with
4864  * the refcounting from the preparation phase.
4865  */
4866 static void nf_tables_set_elem_destroy(const struct nft_ctx *ctx,
4867                                        const struct nft_set *set, void *elem)
4868 {
4869         struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
4870 
4871         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPR))
4872                 nf_tables_expr_destroy(ctx, nft_set_ext_expr(ext));
4873         kfree(elem);
4874 }
4875 
4876 static int nft_add_set_elem(struct nft_ctx *ctx, struct nft_set *set,
4877                             const struct nlattr *attr, u32 nlmsg_flags)
4878 {
4879         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4880         u8 genmask = nft_genmask_next(ctx->net);
4881         struct nft_set_ext_tmpl tmpl;
4882         struct nft_set_ext *ext, *ext2;
4883         struct nft_set_elem elem;
4884         struct nft_set_binding *binding;
4885         struct nft_object *obj = NULL;
4886         struct nft_userdata *udata;
4887         struct nft_data_desc desc;
4888         struct nft_data data;
4889         enum nft_registers dreg;
4890         struct nft_trans *trans;
4891         u32 flags = 0;
4892         u64 timeout;
4893         u64 expiration;
4894         u8 ulen;
4895         int err;
4896 
4897         err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
4898                                           nft_set_elem_policy, NULL);
4899         if (err < 0)
4900                 return err;
4901 
4902         if (nla[NFTA_SET_ELEM_KEY] == NULL)
4903                 return -EINVAL;
4904 
4905         nft_set_ext_prepare(&tmpl);
4906 
4907         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4908         if (err < 0)
4909                 return err;
4910         if (flags != 0)
4911                 nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
4912 
4913         if (set->flags & NFT_SET_MAP) {
4914                 if (nla[NFTA_SET_ELEM_DATA] == NULL &&
4915                     !(flags & NFT_SET_ELEM_INTERVAL_END))
4916                         return -EINVAL;
4917         } else {
4918                 if (nla[NFTA_SET_ELEM_DATA] != NULL)
4919                         return -EINVAL;
4920         }
4921 
4922         if ((flags & NFT_SET_ELEM_INTERVAL_END) &&
4923              (nla[NFTA_SET_ELEM_DATA] ||
4924               nla[NFTA_SET_ELEM_OBJREF] ||
4925               nla[NFTA_SET_ELEM_TIMEOUT] ||
4926               nla[NFTA_SET_ELEM_EXPIRATION] ||
4927               nla[NFTA_SET_ELEM_USERDATA] ||
4928               nla[NFTA_SET_ELEM_EXPR]))
4929                 return -EINVAL;
4930 
4931         timeout = 0;
4932         if (nla[NFTA_SET_ELEM_TIMEOUT] != NULL) {
4933                 if (!(set->flags & NFT_SET_TIMEOUT))
4934                         return -EINVAL;
4935                 err = nf_msecs_to_jiffies64(nla[NFTA_SET_ELEM_TIMEOUT],
4936                                             &timeout);
4937                 if (err)
4938                         return err;
4939         } else if (set->flags & NFT_SET_TIMEOUT) {
4940                 timeout = set->timeout;
4941         }
4942 
4943         expiration = 0;
4944         if (nla[NFTA_SET_ELEM_EXPIRATION] != NULL) {
4945                 if (!(set->flags & NFT_SET_TIMEOUT))
4946                         return -EINVAL;
4947                 err = nf_msecs_to_jiffies64(nla[NFTA_SET_ELEM_EXPIRATION],
4948                                             &expiration);
4949                 if (err)
4950                         return err;
4951         }
4952 
4953         err = nft_setelem_parse_key(ctx, set, &elem.key.val,
4954                                     nla[NFTA_SET_ELEM_KEY]);
4955         if (err < 0)
4956                 return err;
4957 
4958         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, set->klen);
4959 
4960         if (nla[NFTA_SET_ELEM_KEY_END]) {
4961                 err = nft_setelem_parse_key(ctx, set, &elem.key_end.val,
4962                                             nla[NFTA_SET_ELEM_KEY_END]);
4963                 if (err < 0)
4964                         goto err_parse_key;
4965 
4966                 nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY_END, set->klen);
4967         }
4968 
4969         if (timeout > 0) {
4970                 nft_set_ext_add(&tmpl, NFT_SET_EXT_EXPIRATION);
4971                 if (timeout != set->timeout)
4972                         nft_set_ext_add(&tmpl, NFT_SET_EXT_TIMEOUT);
4973         }
4974 
4975         if (nla[NFTA_SET_ELEM_OBJREF] != NULL) {
4976                 if (!(set->flags & NFT_SET_OBJECT)) {
4977                         err = -EINVAL;
4978                         goto err_parse_key_end;
4979                 }
4980                 obj = nft_obj_lookup(ctx->net, ctx->table,
4981                                      nla[NFTA_SET_ELEM_OBJREF],
4982                                      set->objtype, genmask);
4983                 if (IS_ERR(obj)) {
4984                         err = PTR_ERR(obj);
4985                         goto err_parse_key_end;
4986                 }
4987                 nft_set_ext_add(&tmpl, NFT_SET_EXT_OBJREF);
4988         }
4989 
4990         if (nla[NFTA_SET_ELEM_DATA] != NULL) {
4991                 err = nft_data_init(ctx, &data, sizeof(data), &desc,
4992                                     nla[NFTA_SET_ELEM_DATA]);
4993                 if (err < 0)
4994                         goto err_parse_key_end;
4995 
4996                 err = -EINVAL;
4997                 if (set->dtype != NFT_DATA_VERDICT && desc.len != set->dlen)
4998                         goto err_parse_data;
4999 
5000                 dreg = nft_type_to_reg(set->dtype);
5001                 list_for_each_entry(binding, &set->bindings, list) {
5002                         struct nft_ctx bind_ctx = {
5003                                 .net    = ctx->net,
5004                                 .family = ctx->family,
5005                                 .table  = ctx->table,
5006                                 .chain  = (struct nft_chain *)binding->chain,
5007                         };
5008 
5009                         if (!(binding->flags & NFT_SET_MAP))
5010                                 continue;
5011 
5012                         err = nft_validate_register_store(&bind_ctx, dreg,
5013                                                           &data,
5014                                                           desc.type, desc.len);
5015                         if (err < 0)
5016                                 goto err_parse_data;
5017 
5018                         if (desc.type == NFT_DATA_VERDICT &&
5019                             (data.verdict.code == NFT_GOTO ||
5020                              data.verdict.code == NFT_JUMP))
5021                                 nft_validate_state_update(ctx->net,
5022                                                           NFT_VALIDATE_NEED);
5023                 }
5024 
5025                 nft_set_ext_add_length(&tmpl, NFT_SET_EXT_DATA, desc.len);
5026         }
5027 
5028         /* The full maximum length of userdata can exceed the maximum
5029          * offset value (U8_MAX) for following extensions, therefor it
5030          * must be the last extension added.
5031          */
5032         ulen = 0;
5033         if (nla[NFTA_SET_ELEM_USERDATA] != NULL) {
5034                 ulen = nla_len(nla[NFTA_SET_ELEM_USERDATA]);
5035                 if (ulen > 0)
5036                         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_USERDATA,
5037                                                ulen);
5038         }
5039 
5040         err = -ENOMEM;
5041         elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data,
5042                                       elem.key_end.val.data, data.data,
5043                                       timeout, expiration, GFP_KERNEL);
5044         if (elem.priv == NULL)
5045                 goto err_parse_data;
5046 
5047         ext = nft_set_elem_ext(set, elem.priv);
5048         if (flags)
5049                 *nft_set_ext_flags(ext) = flags;
5050         if (ulen > 0) {
5051                 udata = nft_set_ext_userdata(ext);
5052                 udata->len = ulen - 1;
5053                 nla_memcpy(&udata->data, nla[NFTA_SET_ELEM_USERDATA], ulen);
5054         }
5055         if (obj) {
5056                 *nft_set_ext_obj(ext) = obj;
5057                 obj->use++;
5058         }
5059 
5060         trans = nft_trans_elem_alloc(ctx, NFT_MSG_NEWSETELEM, set);
5061         if (trans == NULL)
5062                 goto err_trans;
5063 
5064         ext->genmask = nft_genmask_cur(ctx->net) | NFT_SET_ELEM_BUSY_MASK;
5065         err = set->ops->insert(ctx->net, set, &elem, &ext2);
5066         if (err) {
5067                 if (err == -EEXIST) {
5068                         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) ^
5069                             nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) ||
5070                             nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) ^
5071                             nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF)) {
5072                                 err = -EBUSY;
5073                                 goto err_element_clash;
5074                         }
5075                         if ((nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
5076                              nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) &&
5077                              memcmp(nft_set_ext_data(ext),
5078                                     nft_set_ext_data(ext2), set->dlen) != 0) ||
5079                             (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
5080                              nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF) &&
5081                              *nft_set_ext_obj(ext) != *nft_set_ext_obj(ext2)))
5082                                 err = -EBUSY;
5083                         else if (!(nlmsg_flags & NLM_F_EXCL))
5084                                 err = 0;
5085                 } else if (err == -ENOTEMPTY) {
5086                         /* ENOTEMPTY reports overlapping between this element
5087                          * and an existing one.
5088                          */
5089                         err = -EEXIST;
5090                 }
5091                 goto err_element_clash;
5092         }
5093 
5094         if (set->size &&
5095             !atomic_add_unless(&set->nelems, 1, set->size + set->ndeact)) {
5096                 err = -ENFILE;
5097                 goto err_set_full;
5098         }
5099 
5100         nft_trans_elem(trans) = elem;
5101         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
5102         return 0;
5103 
5104 err_set_full:
5105         set->ops->remove(ctx->net, set, &elem);
5106 err_element_clash:
5107         kfree(trans);
5108 err_trans:
5109         if (obj)
5110                 obj->use--;
5111         kfree(elem.priv);
5112 err_parse_data:
5113         if (nla[NFTA_SET_ELEM_DATA] != NULL)
5114                 nft_data_release(&data, desc.type);
5115 err_parse_key_end:
5116         nft_data_release(&elem.key_end.val, NFT_DATA_VALUE);
5117 err_parse_key:
5118         nft_data_release(&elem.key.val, NFT_DATA_VALUE);
5119 
5120         return err;
5121 }
5122 
5123 static int nf_tables_newsetelem(struct net *net, struct sock *nlsk,
5124                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
5125                                 const struct nlattr * const nla[],
5126                                 struct netlink_ext_ack *extack)
5127 {
5128         u8 genmask = nft_genmask_next(net);
5129         const struct nlattr *attr;
5130         struct nft_set *set;
5131         struct nft_ctx ctx;
5132         int rem, err;
5133 
5134         if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL)
5135                 return -EINVAL;
5136 
5137         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
5138                                          genmask);
5139         if (err < 0)
5140                 return err;
5141 
5142         set = nft_set_lookup_global(net, ctx.table, nla[NFTA_SET_ELEM_LIST_SET],
5143                                     nla[NFTA_SET_ELEM_LIST_SET_ID], genmask);
5144         if (IS_ERR(set))
5145                 return PTR_ERR(set);
5146 
5147         if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
5148                 return -EBUSY;
5149 
5150         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
5151                 err = nft_add_set_elem(&ctx, set, attr, nlh->nlmsg_flags);
5152                 if (err < 0)
5153                         return err;
5154         }
5155 
5156         if (net->nft.validate_state == NFT_VALIDATE_DO)
5157                 return nft_table_validate(net, ctx.table);
5158 
5159         return 0;
5160 }
5161 
5162 /**
5163  *      nft_data_hold - hold a nft_data item
5164  *
5165  *      @data: struct nft_data to release
5166  *      @type: type of data
5167  *
5168  *      Hold a nft_data item. NFT_DATA_VALUE types can be silently discarded,
5169  *      NFT_DATA_VERDICT bumps the reference to chains in case of NFT_JUMP and
5170  *      NFT_GOTO verdicts. This function must be called on active data objects
5171  *      from the second phase of the commit protocol.
5172  */
5173 void nft_data_hold(const struct nft_data *data, enum nft_data_types type)
5174 {
5175         if (type == NFT_DATA_VERDICT) {
5176                 switch (data->verdict.code) {
5177                 case NFT_JUMP:
5178                 case NFT_GOTO:
5179                         data->verdict.chain->use++;
5180                         break;
5181                 }
5182         }
5183 }
5184 
5185 static void nft_set_elem_activate(const struct net *net,
5186                                   const struct nft_set *set,
5187                                   struct nft_set_elem *elem)
5188 {
5189         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
5190 
5191         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
5192                 nft_data_hold(nft_set_ext_data(ext), set->dtype);
5193         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
5194                 (*nft_set_ext_obj(ext))->use++;
5195 }
5196 
5197 static void nft_set_elem_deactivate(const struct net *net,
5198                                     const struct nft_set *set,
5199                                     struct nft_set_elem *elem)
5200 {
5201         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
5202 
5203         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
5204                 nft_data_release(nft_set_ext_data(ext), set->dtype);
5205         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
5206                 (*nft_set_ext_obj(ext))->use--;
5207 }
5208 
5209 static int nft_del_setelem(struct nft_ctx *ctx, struct nft_set *set,
5210                            const struct nlattr *attr)
5211 {
5212         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
5213         struct nft_set_ext_tmpl tmpl;
5214         struct nft_set_elem elem;
5215         struct nft_set_ext *ext;
5216         struct nft_trans *trans;
5217         u32 flags = 0;
5218         void *priv;
5219         int err;
5220 
5221         err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
5222                                           nft_set_elem_policy, NULL);
5223         if (err < 0)
5224                 return err;
5225 
5226         if (nla[NFTA_SET_ELEM_KEY] == NULL)
5227                 return -EINVAL;
5228 
5229         nft_set_ext_prepare(&tmpl);
5230 
5231         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
5232         if (err < 0)
5233                 return err;
5234         if (flags != 0)
5235                 nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
5236 
5237         err = nft_setelem_parse_key(ctx, set, &elem.key.val,
5238                                     nla[NFTA_SET_ELEM_KEY]);
5239         if (err < 0)
5240                 return err;
5241 
5242         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, set->klen);
5243 
5244         if (nla[NFTA_SET_ELEM_KEY_END]) {
5245                 err = nft_setelem_parse_key(ctx, set, &elem.key_end.val,
5246                                             nla[NFTA_SET_ELEM_KEY_END]);
5247                 if (err < 0)
5248                         return err;
5249 
5250                 nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY_END, set->klen);
5251         }
5252 
5253         err = -ENOMEM;
5254         elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data,
5255                                       elem.key_end.val.data, NULL, 0, 0,
5256                                       GFP_KERNEL);
5257         if (elem.priv == NULL)
5258                 goto fail_elem;
5259 
5260         ext = nft_set_elem_ext(set, elem.priv);
5261         if (flags)
5262                 *nft_set_ext_flags(ext) = flags;
5263 
5264         trans = nft_trans_elem_alloc(ctx, NFT_MSG_DELSETELEM, set);
5265         if (trans == NULL)
5266                 goto fail_trans;
5267 
5268         priv = set->ops->deactivate(ctx->net, set, &elem);
5269         if (priv == NULL) {
5270                 err = -ENOENT;
5271                 goto fail_ops;
5272         }
5273         kfree(elem.priv);
5274         elem.priv = priv;
5275 
5276         nft_set_elem_deactivate(ctx->net, set, &elem);
5277 
5278         nft_trans_elem(trans) = elem;
5279         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
5280         return 0;
5281 
5282 fail_ops:
5283         kfree(trans);
5284 fail_trans:
5285         kfree(elem.priv);
5286 fail_elem:
5287         nft_data_release(&elem.key.val, NFT_DATA_VALUE);
5288         return err;
5289 }
5290 
5291 static int nft_flush_set(const struct nft_ctx *ctx,
5292                          struct nft_set *set,
5293                          const struct nft_set_iter *iter,
5294                          struct nft_set_elem *elem)
5295 {
5296         struct nft_trans *trans;
5297         int err;
5298 
5299         trans = nft_trans_alloc_gfp(ctx, NFT_MSG_DELSETELEM,
5300                                     sizeof(struct nft_trans_elem), GFP_ATOMIC);
5301         if (!trans)
5302                 return -ENOMEM;
5303 
5304         if (!set->ops->flush(ctx->net, set, elem->priv)) {
5305                 err = -ENOENT;
5306                 goto err1;
5307         }
5308         set->ndeact++;
5309 
5310