xref: /linux/net/sched/cls_api.c (revision f4cdf7ca9a1fdcca413157df19753f388a5a224e)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * net/sched/cls_api.c	Packet classifier API.
4  *
5  * Authors:	Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
6  *
7  * Changes:
8  *
9  * Eduardo J. Blanco <ejbs@netlabs.com.uy> :990222: kmod support
10  */
11 
12 #include <linux/module.h>
13 #include <linux/types.h>
14 #include <linux/kernel.h>
15 #include <linux/string.h>
16 #include <linux/errno.h>
17 #include <linux/err.h>
18 #include <linux/skbuff.h>
19 #include <linux/init.h>
20 #include <linux/kmod.h>
21 #include <linux/slab.h>
22 #include <linux/idr.h>
23 #include <linux/jhash.h>
24 #include <linux/rculist.h>
25 #include <linux/rhashtable.h>
26 #include <net/net_namespace.h>
27 #include <net/sock.h>
28 #include <net/netlink.h>
29 #include <net/pkt_sched.h>
30 #include <net/pkt_cls.h>
31 #include <net/tc_act/tc_pedit.h>
32 #include <net/tc_act/tc_mirred.h>
33 #include <net/tc_act/tc_vlan.h>
34 #include <net/tc_act/tc_tunnel_key.h>
35 #include <net/tc_act/tc_csum.h>
36 #include <net/tc_act/tc_gact.h>
37 #include <net/tc_act/tc_police.h>
38 #include <net/tc_act/tc_sample.h>
39 #include <net/tc_act/tc_skbedit.h>
40 #include <net/tc_act/tc_ct.h>
41 #include <net/tc_act/tc_mpls.h>
42 #include <net/tc_act/tc_gate.h>
43 #include <net/flow_offload.h>
44 #include <net/tc_wrapper.h>
45 
46 /* The list of all installed classifier types */
47 static LIST_HEAD(tcf_proto_base);
48 
49 /* Protects list of registered TC modules. It is pure SMP lock. */
50 static DEFINE_RWLOCK(cls_mod_lock);
51 
52 static struct xarray tcf_exts_miss_cookies_xa;
53 struct tcf_exts_miss_cookie_node {
54 	const struct tcf_chain *chain;
55 	const struct tcf_proto *tp;
56 	const struct tcf_exts *exts;
57 	u32 chain_index;
58 	u32 tp_prio;
59 	u32 handle;
60 	u32 miss_cookie_base;
61 	struct rcu_head rcu;
62 };
63 
64 /* Each tc action entry cookie will be comprised of 32bit miss_cookie_base +
65  * action index in the exts tc actions array.
66  */
67 union tcf_exts_miss_cookie {
68 	struct {
69 		u32 miss_cookie_base;
70 		u32 act_index;
71 	};
72 	u64 miss_cookie;
73 };
74 
75 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
76 static int
77 tcf_exts_miss_cookie_base_alloc(struct tcf_exts *exts, struct tcf_proto *tp,
78 				u32 handle)
79 {
80 	struct tcf_exts_miss_cookie_node *n;
81 	static u32 next;
82 	int err;
83 
84 	if (WARN_ON(!handle || !tp->ops->get_exts))
85 		return -EINVAL;
86 
87 	n = kzalloc_obj(*n);
88 	if (!n)
89 		return -ENOMEM;
90 
91 	n->chain_index = tp->chain->index;
92 	n->chain = tp->chain;
93 	n->tp_prio = tp->prio;
94 	n->tp = tp;
95 	n->exts = exts;
96 	n->handle = handle;
97 
98 	err = xa_alloc_cyclic(&tcf_exts_miss_cookies_xa, &n->miss_cookie_base,
99 			      n, xa_limit_32b, &next, GFP_KERNEL);
100 	if (err < 0)
101 		goto err_xa_alloc;
102 
103 	exts->miss_cookie_node = n;
104 	return 0;
105 
106 err_xa_alloc:
107 	kfree(n);
108 	return err;
109 }
110 
111 static void tcf_exts_miss_cookie_base_destroy(struct tcf_exts *exts)
112 {
113 	struct tcf_exts_miss_cookie_node *n;
114 
115 	if (!exts->miss_cookie_node)
116 		return;
117 
118 	n = exts->miss_cookie_node;
119 	xa_erase(&tcf_exts_miss_cookies_xa, n->miss_cookie_base);
120 	kfree_rcu(n, rcu);
121 }
122 
123 static struct tcf_exts_miss_cookie_node *
124 tcf_exts_miss_cookie_lookup(u64 miss_cookie, int *act_index)
125 {
126 	union tcf_exts_miss_cookie mc = { .miss_cookie = miss_cookie, };
127 
128 	*act_index = mc.act_index;
129 	return xa_load(&tcf_exts_miss_cookies_xa, mc.miss_cookie_base);
130 }
131 #else /* IS_ENABLED(CONFIG_NET_TC_SKB_EXT) */
132 static int
133 tcf_exts_miss_cookie_base_alloc(struct tcf_exts *exts, struct tcf_proto *tp,
134 				u32 handle)
135 {
136 	return 0;
137 }
138 
139 static void tcf_exts_miss_cookie_base_destroy(struct tcf_exts *exts)
140 {
141 }
142 #endif /* IS_ENABLED(CONFIG_NET_TC_SKB_EXT) */
143 
144 static u64 tcf_exts_miss_cookie_get(u32 miss_cookie_base, int act_index)
145 {
146 	union tcf_exts_miss_cookie mc = { .act_index = act_index, };
147 
148 	if (!miss_cookie_base)
149 		return 0;
150 
151 	mc.miss_cookie_base = miss_cookie_base;
152 	return mc.miss_cookie;
153 }
154 
155 #ifdef CONFIG_NET_CLS_ACT
156 DEFINE_STATIC_KEY_FALSE(tc_skb_ext_tc);
157 EXPORT_SYMBOL(tc_skb_ext_tc);
158 
159 void tc_skb_ext_tc_enable(void)
160 {
161 	static_branch_inc(&tc_skb_ext_tc);
162 }
163 EXPORT_SYMBOL(tc_skb_ext_tc_enable);
164 
165 void tc_skb_ext_tc_disable(void)
166 {
167 	static_branch_dec(&tc_skb_ext_tc);
168 }
169 EXPORT_SYMBOL(tc_skb_ext_tc_disable);
170 #endif
171 
172 static u32 destroy_obj_hashfn(const struct tcf_proto *tp)
173 {
174 	return jhash_3words(tp->chain->index, tp->prio,
175 			    (__force __u32)tp->protocol, 0);
176 }
177 
178 static void tcf_proto_signal_destroying(struct tcf_chain *chain,
179 					struct tcf_proto *tp)
180 {
181 	struct tcf_block *block = chain->block;
182 
183 	mutex_lock(&block->proto_destroy_lock);
184 	hash_add_rcu(block->proto_destroy_ht, &tp->destroy_ht_node,
185 		     destroy_obj_hashfn(tp));
186 	mutex_unlock(&block->proto_destroy_lock);
187 }
188 
189 static bool tcf_proto_cmp(const struct tcf_proto *tp1,
190 			  const struct tcf_proto *tp2)
191 {
192 	return tp1->chain->index == tp2->chain->index &&
193 	       tp1->prio == tp2->prio &&
194 	       tp1->protocol == tp2->protocol;
195 }
196 
197 static bool tcf_proto_exists_destroying(struct tcf_chain *chain,
198 					struct tcf_proto *tp)
199 {
200 	u32 hash = destroy_obj_hashfn(tp);
201 	struct tcf_proto *iter;
202 	bool found = false;
203 
204 	rcu_read_lock();
205 	hash_for_each_possible_rcu(chain->block->proto_destroy_ht, iter,
206 				   destroy_ht_node, hash) {
207 		if (tcf_proto_cmp(tp, iter)) {
208 			found = true;
209 			break;
210 		}
211 	}
212 	rcu_read_unlock();
213 
214 	return found;
215 }
216 
217 static void
218 tcf_proto_signal_destroyed(struct tcf_chain *chain, struct tcf_proto *tp)
219 {
220 	struct tcf_block *block = chain->block;
221 
222 	mutex_lock(&block->proto_destroy_lock);
223 	if (hash_hashed(&tp->destroy_ht_node))
224 		hash_del_rcu(&tp->destroy_ht_node);
225 	mutex_unlock(&block->proto_destroy_lock);
226 }
227 
228 /* Find classifier type by string name */
229 
230 static const struct tcf_proto_ops *__tcf_proto_lookup_ops(const char *kind)
231 {
232 	const struct tcf_proto_ops *t, *res = NULL;
233 
234 	if (kind) {
235 		read_lock(&cls_mod_lock);
236 		list_for_each_entry(t, &tcf_proto_base, head) {
237 			if (strcmp(kind, t->kind) == 0) {
238 				if (try_module_get(t->owner))
239 					res = t;
240 				break;
241 			}
242 		}
243 		read_unlock(&cls_mod_lock);
244 	}
245 	return res;
246 }
247 
248 static const struct tcf_proto_ops *
249 tcf_proto_lookup_ops(const char *kind, bool rtnl_held,
250 		     struct netlink_ext_ack *extack)
251 {
252 	const struct tcf_proto_ops *ops;
253 
254 	ops = __tcf_proto_lookup_ops(kind);
255 	if (ops)
256 		return ops;
257 #ifdef CONFIG_MODULES
258 	if (rtnl_held)
259 		rtnl_unlock();
260 	request_module(NET_CLS_ALIAS_PREFIX "%s", kind);
261 	if (rtnl_held)
262 		rtnl_lock();
263 	ops = __tcf_proto_lookup_ops(kind);
264 	/* We dropped the RTNL semaphore in order to perform
265 	 * the module load. So, even if we succeeded in loading
266 	 * the module we have to replay the request. We indicate
267 	 * this using -EAGAIN.
268 	 */
269 	if (ops) {
270 		module_put(ops->owner);
271 		return ERR_PTR(-EAGAIN);
272 	}
273 #endif
274 	NL_SET_ERR_MSG(extack, "TC classifier not found");
275 	return ERR_PTR(-ENOENT);
276 }
277 
278 /* Register(unregister) new classifier type */
279 
280 int register_tcf_proto_ops(struct tcf_proto_ops *ops)
281 {
282 	struct tcf_proto_ops *t;
283 	int rc = -EEXIST;
284 
285 	write_lock(&cls_mod_lock);
286 	list_for_each_entry(t, &tcf_proto_base, head)
287 		if (!strcmp(ops->kind, t->kind))
288 			goto out;
289 
290 	list_add_tail(&ops->head, &tcf_proto_base);
291 	rc = 0;
292 out:
293 	write_unlock(&cls_mod_lock);
294 	return rc;
295 }
296 EXPORT_SYMBOL(register_tcf_proto_ops);
297 
298 static struct workqueue_struct *tc_filter_wq;
299 
300 void unregister_tcf_proto_ops(struct tcf_proto_ops *ops)
301 {
302 	struct tcf_proto_ops *t;
303 	int rc = -ENOENT;
304 
305 	/* Wait for outstanding call_rcu()s, if any, from a
306 	 * tcf_proto_ops's destroy() handler.
307 	 */
308 	rcu_barrier();
309 	flush_workqueue(tc_filter_wq);
310 
311 	write_lock(&cls_mod_lock);
312 	list_for_each_entry(t, &tcf_proto_base, head) {
313 		if (t == ops) {
314 			list_del(&t->head);
315 			rc = 0;
316 			break;
317 		}
318 	}
319 	write_unlock(&cls_mod_lock);
320 
321 	WARN(rc, "unregister tc filter kind(%s) failed %d\n", ops->kind, rc);
322 }
323 EXPORT_SYMBOL(unregister_tcf_proto_ops);
324 
325 bool tcf_queue_work(struct rcu_work *rwork, work_func_t func)
326 {
327 	INIT_RCU_WORK(rwork, func);
328 	return queue_rcu_work(tc_filter_wq, rwork);
329 }
330 EXPORT_SYMBOL(tcf_queue_work);
331 
332 /* Select new prio value from the range, managed by kernel. */
333 
334 static inline u32 tcf_auto_prio(struct tcf_proto *tp)
335 {
336 	u32 first = TC_H_MAKE(0xC0000000U, 0U);
337 
338 	if (tp)
339 		first = tp->prio - 1;
340 
341 	return TC_H_MAJ(first);
342 }
343 
344 static bool tcf_proto_check_kind(struct nlattr *kind, char *name)
345 {
346 	if (kind)
347 		return nla_strscpy(name, kind, IFNAMSIZ) < 0;
348 	memset(name, 0, IFNAMSIZ);
349 	return false;
350 }
351 
352 static bool tcf_proto_is_unlocked(const char *kind)
353 {
354 	const struct tcf_proto_ops *ops;
355 	bool ret;
356 
357 	if (strlen(kind) == 0)
358 		return false;
359 
360 	ops = tcf_proto_lookup_ops(kind, false, NULL);
361 	/* On error return false to take rtnl lock. Proto lookup/create
362 	 * functions will perform lookup again and properly handle errors.
363 	 */
364 	if (IS_ERR(ops))
365 		return false;
366 
367 	ret = !!(ops->flags & TCF_PROTO_OPS_DOIT_UNLOCKED);
368 	module_put(ops->owner);
369 	return ret;
370 }
371 
372 static struct tcf_proto *tcf_proto_create(const char *kind, u32 protocol,
373 					  u32 prio, struct tcf_chain *chain,
374 					  bool rtnl_held,
375 					  struct netlink_ext_ack *extack)
376 {
377 	struct tcf_proto *tp;
378 	int err;
379 
380 	tp = kzalloc_obj(*tp);
381 	if (!tp)
382 		return ERR_PTR(-ENOBUFS);
383 
384 	tp->ops = tcf_proto_lookup_ops(kind, rtnl_held, extack);
385 	if (IS_ERR(tp->ops)) {
386 		err = PTR_ERR(tp->ops);
387 		goto errout;
388 	}
389 	tp->classify = tp->ops->classify;
390 	tp->protocol = protocol;
391 	tp->prio = prio;
392 	tp->chain = chain;
393 	tp->usesw = !tp->ops->reoffload;
394 	spin_lock_init(&tp->lock);
395 	refcount_set(&tp->refcnt, 1);
396 
397 	err = tp->ops->init(tp);
398 	if (err) {
399 		module_put(tp->ops->owner);
400 		goto errout;
401 	}
402 	return tp;
403 
404 errout:
405 	kfree(tp);
406 	return ERR_PTR(err);
407 }
408 
409 static void tcf_proto_get(struct tcf_proto *tp)
410 {
411 	refcount_inc(&tp->refcnt);
412 }
413 
414 static void tcf_proto_count_usesw(struct tcf_proto *tp, bool add)
415 {
416 #ifdef CONFIG_NET_CLS_ACT
417 	struct tcf_block *block = tp->chain->block;
418 	bool counted = false;
419 
420 	if (!add) {
421 		if (tp->usesw && tp->counted) {
422 			if (!atomic_dec_return(&block->useswcnt))
423 				static_branch_dec(&tcf_sw_enabled_key);
424 			tp->counted = false;
425 		}
426 		return;
427 	}
428 
429 	spin_lock(&tp->lock);
430 	if (tp->usesw && !tp->counted) {
431 		counted = true;
432 		tp->counted = true;
433 	}
434 	spin_unlock(&tp->lock);
435 
436 	if (counted && atomic_inc_return(&block->useswcnt) == 1)
437 		static_branch_inc(&tcf_sw_enabled_key);
438 #endif
439 }
440 
441 static void tcf_chain_put(struct tcf_chain *chain);
442 
443 static void tcf_proto_destroy(struct tcf_proto *tp, bool rtnl_held,
444 			      bool sig_destroy, struct netlink_ext_ack *extack)
445 {
446 	/* A locked classifier's destroy callback (e.g. u32_destroy) uses
447 	 * rtnl_dereference() and mutates shared structures (e.g. the
448 	 * tc_u_common hash list) that are only safe under rtnl_lock. When an
449 	 * unlocked classifier's request (e.g. flower on ingress) loses the
450 	 * tcf_chain_tp_insert_unique() race and ends up dropping the last
451 	 * reference on a locked classifier's proto, destroy() would run
452 	 * without rtnl held. Take it here in that case.
453 	 */
454 	bool not_lockless = !rtnl_held &&
455 		!(tp->ops->flags & TCF_PROTO_OPS_DOIT_UNLOCKED);
456 
457 	if (not_lockless)
458 		rtnl_lock();
459 	tp->ops->destroy(tp, rtnl_held || not_lockless, extack);
460 	if (not_lockless)
461 		rtnl_unlock();
462 	tcf_proto_count_usesw(tp, false);
463 	if (sig_destroy)
464 		tcf_proto_signal_destroyed(tp->chain, tp);
465 	tcf_chain_put(tp->chain);
466 	module_put(tp->ops->owner);
467 	kfree_rcu(tp, rcu);
468 }
469 
470 static void tcf_proto_put(struct tcf_proto *tp, bool rtnl_held,
471 			  struct netlink_ext_ack *extack)
472 {
473 	if (refcount_dec_and_test(&tp->refcnt))
474 		tcf_proto_destroy(tp, rtnl_held, true, extack);
475 }
476 
477 static bool tcf_proto_check_delete(struct tcf_proto *tp)
478 {
479 	if (tp->ops->delete_empty)
480 		return tp->ops->delete_empty(tp);
481 
482 	tp->deleting = true;
483 	return tp->deleting;
484 }
485 
486 static void tcf_proto_mark_delete(struct tcf_proto *tp)
487 {
488 	spin_lock(&tp->lock);
489 	tp->deleting = true;
490 	spin_unlock(&tp->lock);
491 }
492 
493 static bool tcf_proto_is_deleting(struct tcf_proto *tp)
494 {
495 	bool deleting;
496 
497 	spin_lock(&tp->lock);
498 	deleting = tp->deleting;
499 	spin_unlock(&tp->lock);
500 
501 	return deleting;
502 }
503 
504 #define ASSERT_BLOCK_LOCKED(block)					\
505 	lockdep_assert_held(&(block)->lock)
506 
507 struct tcf_filter_chain_list_item {
508 	struct list_head list;
509 	tcf_chain_head_change_t *chain_head_change;
510 	void *chain_head_change_priv;
511 };
512 
513 static struct tcf_chain *tcf_chain_create(struct tcf_block *block,
514 					  u32 chain_index)
515 {
516 	struct tcf_chain *chain;
517 
518 	ASSERT_BLOCK_LOCKED(block);
519 
520 	chain = kzalloc_obj(*chain);
521 	if (!chain)
522 		return NULL;
523 	list_add_tail_rcu(&chain->list, &block->chain_list);
524 	mutex_init(&chain->filter_chain_lock);
525 	chain->block = block;
526 	chain->index = chain_index;
527 	chain->refcnt = 1;
528 	if (!chain->index)
529 		block->chain0.chain = chain;
530 	return chain;
531 }
532 
533 static void tcf_chain_head_change_item(struct tcf_filter_chain_list_item *item,
534 				       struct tcf_proto *tp_head)
535 {
536 	if (item->chain_head_change)
537 		item->chain_head_change(tp_head, item->chain_head_change_priv);
538 }
539 
540 static void tcf_chain0_head_change(struct tcf_chain *chain,
541 				   struct tcf_proto *tp_head)
542 {
543 	struct tcf_filter_chain_list_item *item;
544 	struct tcf_block *block = chain->block;
545 
546 	if (chain->index)
547 		return;
548 
549 	mutex_lock(&block->lock);
550 	list_for_each_entry(item, &block->chain0.filter_chain_list, list)
551 		tcf_chain_head_change_item(item, tp_head);
552 	mutex_unlock(&block->lock);
553 }
554 
555 /* Returns true if block can be safely freed. */
556 
557 static bool tcf_chain_detach(struct tcf_chain *chain)
558 {
559 	struct tcf_block *block = chain->block;
560 
561 	ASSERT_BLOCK_LOCKED(block);
562 
563 	list_del_rcu(&chain->list);
564 	if (!chain->index)
565 		block->chain0.chain = NULL;
566 
567 	if (list_empty(&block->chain_list) &&
568 	    refcount_read(&block->refcnt) == 0)
569 		return true;
570 
571 	return false;
572 }
573 
574 static void tcf_block_destroy(struct tcf_block *block)
575 {
576 	mutex_destroy(&block->lock);
577 	mutex_destroy(&block->proto_destroy_lock);
578 	xa_destroy(&block->ports);
579 	kfree_rcu(block, rcu);
580 }
581 
582 static void tcf_chain_destroy(struct tcf_chain *chain, bool free_block)
583 {
584 	struct tcf_block *block = chain->block;
585 
586 	mutex_destroy(&chain->filter_chain_lock);
587 	kfree_rcu(chain, rcu);
588 	if (free_block)
589 		tcf_block_destroy(block);
590 }
591 
592 static void tcf_chain_hold(struct tcf_chain *chain)
593 {
594 	ASSERT_BLOCK_LOCKED(chain->block);
595 
596 	++chain->refcnt;
597 }
598 
599 static bool tcf_chain_held_by_acts_only(struct tcf_chain *chain)
600 {
601 	ASSERT_BLOCK_LOCKED(chain->block);
602 
603 	/* In case all the references are action references, this
604 	 * chain should not be shown to the user.
605 	 */
606 	return chain->refcnt == chain->action_refcnt;
607 }
608 
609 static struct tcf_chain *tcf_chain_lookup(struct tcf_block *block,
610 					  u32 chain_index)
611 {
612 	struct tcf_chain *chain;
613 
614 	ASSERT_BLOCK_LOCKED(block);
615 
616 	list_for_each_entry(chain, &block->chain_list, list) {
617 		if (chain->index == chain_index)
618 			return chain;
619 	}
620 	return NULL;
621 }
622 
623 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
624 static struct tcf_chain *tcf_chain_lookup_rcu(const struct tcf_block *block,
625 					      u32 chain_index)
626 {
627 	struct tcf_chain *chain;
628 
629 	list_for_each_entry_rcu(chain, &block->chain_list, list) {
630 		if (chain->index == chain_index)
631 			return chain;
632 	}
633 	return NULL;
634 }
635 #endif
636 
637 static int tc_chain_notify(struct tcf_chain *chain, struct sk_buff *oskb,
638 			   u32 seq, u16 flags, int event, bool unicast,
639 			   struct netlink_ext_ack *extack);
640 
641 static struct tcf_chain *__tcf_chain_get(struct tcf_block *block,
642 					 u32 chain_index, bool create,
643 					 bool by_act)
644 {
645 	struct tcf_chain *chain = NULL;
646 	bool is_first_reference;
647 
648 	mutex_lock(&block->lock);
649 	chain = tcf_chain_lookup(block, chain_index);
650 	if (chain) {
651 		tcf_chain_hold(chain);
652 	} else {
653 		if (!create)
654 			goto errout;
655 		chain = tcf_chain_create(block, chain_index);
656 		if (!chain)
657 			goto errout;
658 	}
659 
660 	if (by_act)
661 		++chain->action_refcnt;
662 	is_first_reference = chain->refcnt - chain->action_refcnt == 1;
663 	mutex_unlock(&block->lock);
664 
665 	/* Send notification only in case we got the first
666 	 * non-action reference. Until then, the chain acts only as
667 	 * a placeholder for actions pointing to it and user ought
668 	 * not know about them.
669 	 */
670 	if (is_first_reference && !by_act)
671 		tc_chain_notify(chain, NULL, 0, NLM_F_CREATE | NLM_F_EXCL,
672 				RTM_NEWCHAIN, false, NULL);
673 
674 	return chain;
675 
676 errout:
677 	mutex_unlock(&block->lock);
678 	return chain;
679 }
680 
681 static struct tcf_chain *tcf_chain_get(struct tcf_block *block, u32 chain_index,
682 				       bool create)
683 {
684 	return __tcf_chain_get(block, chain_index, create, false);
685 }
686 
687 struct tcf_chain *tcf_chain_get_by_act(struct tcf_block *block, u32 chain_index)
688 {
689 	return __tcf_chain_get(block, chain_index, true, true);
690 }
691 EXPORT_SYMBOL(tcf_chain_get_by_act);
692 
693 static void tc_chain_tmplt_del(const struct tcf_proto_ops *tmplt_ops,
694 			       void *tmplt_priv);
695 static int tc_chain_notify_delete(const struct tcf_proto_ops *tmplt_ops,
696 				  void *tmplt_priv, u32 chain_index,
697 				  struct tcf_block *block, struct sk_buff *oskb,
698 				  u32 seq, u16 flags);
699 
700 static void __tcf_chain_put(struct tcf_chain *chain, bool by_act,
701 			    bool explicitly_created)
702 {
703 	struct tcf_block *block = chain->block;
704 	const struct tcf_proto_ops *tmplt_ops;
705 	unsigned int refcnt, non_act_refcnt;
706 	bool free_block = false;
707 	void *tmplt_priv;
708 
709 	mutex_lock(&block->lock);
710 	if (explicitly_created) {
711 		if (!chain->explicitly_created) {
712 			mutex_unlock(&block->lock);
713 			return;
714 		}
715 		chain->explicitly_created = false;
716 	}
717 
718 	if (by_act)
719 		chain->action_refcnt--;
720 
721 	/* tc_chain_notify_delete can't be called while holding block lock.
722 	 * However, when block is unlocked chain can be changed concurrently, so
723 	 * save these to temporary variables.
724 	 */
725 	refcnt = --chain->refcnt;
726 	non_act_refcnt = refcnt - chain->action_refcnt;
727 	tmplt_ops = chain->tmplt_ops;
728 	tmplt_priv = chain->tmplt_priv;
729 
730 	if (non_act_refcnt == chain->explicitly_created && !by_act) {
731 		if (non_act_refcnt == 0)
732 			tc_chain_notify_delete(tmplt_ops, tmplt_priv,
733 					       chain->index, block, NULL, 0, 0);
734 		/* Last reference to chain, no need to lock. */
735 		chain->flushing = false;
736 	}
737 
738 	if (refcnt == 0)
739 		free_block = tcf_chain_detach(chain);
740 	mutex_unlock(&block->lock);
741 
742 	if (refcnt == 0) {
743 		tc_chain_tmplt_del(tmplt_ops, tmplt_priv);
744 		tcf_chain_destroy(chain, free_block);
745 	}
746 }
747 
748 static void tcf_chain_put(struct tcf_chain *chain)
749 {
750 	__tcf_chain_put(chain, false, false);
751 }
752 
753 void tcf_chain_put_by_act(struct tcf_chain *chain)
754 {
755 	__tcf_chain_put(chain, true, false);
756 }
757 EXPORT_SYMBOL(tcf_chain_put_by_act);
758 
759 static void tcf_chain_put_explicitly_created(struct tcf_chain *chain)
760 {
761 	__tcf_chain_put(chain, false, true);
762 }
763 
764 static void tcf_chain_flush(struct tcf_chain *chain, bool rtnl_held)
765 {
766 	struct tcf_proto *tp, *tp_next;
767 
768 	mutex_lock(&chain->filter_chain_lock);
769 	tp = tcf_chain_dereference(chain->filter_chain, chain);
770 	while (tp) {
771 		tp_next = rcu_dereference_protected(tp->next, 1);
772 		tcf_proto_signal_destroying(chain, tp);
773 		tp = tp_next;
774 	}
775 	tp = tcf_chain_dereference(chain->filter_chain, chain);
776 	RCU_INIT_POINTER(chain->filter_chain, NULL);
777 	tcf_chain0_head_change(chain, NULL);
778 	chain->flushing = true;
779 	mutex_unlock(&chain->filter_chain_lock);
780 
781 	while (tp) {
782 		tp_next = rcu_dereference_protected(tp->next, 1);
783 		tcf_proto_put(tp, rtnl_held, NULL);
784 		tp = tp_next;
785 	}
786 }
787 
788 static int tcf_block_setup(struct tcf_block *block,
789 			   struct flow_block_offload *bo);
790 
791 static void tcf_block_offload_init(struct flow_block_offload *bo,
792 				   struct net_device *dev, struct Qdisc *sch,
793 				   enum flow_block_command command,
794 				   enum flow_block_binder_type binder_type,
795 				   struct flow_block *flow_block,
796 				   bool shared, struct netlink_ext_ack *extack)
797 {
798 	bo->net = dev_net(dev);
799 	bo->command = command;
800 	bo->binder_type = binder_type;
801 	bo->block = flow_block;
802 	bo->block_shared = shared;
803 	bo->extack = extack;
804 	bo->sch = sch;
805 	bo->cb_list_head = &flow_block->cb_list;
806 	INIT_LIST_HEAD(&bo->cb_list);
807 }
808 
809 static void tcf_block_unbind(struct tcf_block *block,
810 			     struct flow_block_offload *bo);
811 
812 static void tc_block_indr_cleanup(struct flow_block_cb *block_cb)
813 {
814 	struct tcf_block *block = block_cb->indr.data;
815 	struct net_device *dev = block_cb->indr.dev;
816 	struct Qdisc *sch = block_cb->indr.sch;
817 	struct netlink_ext_ack extack = {};
818 	struct flow_block_offload bo = {};
819 
820 	tcf_block_offload_init(&bo, dev, sch, FLOW_BLOCK_UNBIND,
821 			       block_cb->indr.binder_type,
822 			       &block->flow_block, tcf_block_shared(block),
823 			       &extack);
824 	rtnl_lock();
825 	down_write(&block->cb_lock);
826 	list_del(&block_cb->driver_list);
827 	list_move(&block_cb->list, &bo.cb_list);
828 	tcf_block_unbind(block, &bo);
829 	up_write(&block->cb_lock);
830 	rtnl_unlock();
831 }
832 
833 static bool tcf_block_offload_in_use(struct tcf_block *block)
834 {
835 	return atomic_read(&block->offloadcnt);
836 }
837 
838 static int tcf_block_offload_cmd(struct tcf_block *block,
839 				 struct net_device *dev, struct Qdisc *sch,
840 				 struct tcf_block_ext_info *ei,
841 				 enum flow_block_command command,
842 				 struct netlink_ext_ack *extack)
843 {
844 	struct flow_block_offload bo = {};
845 
846 	tcf_block_offload_init(&bo, dev, sch, command, ei->binder_type,
847 			       &block->flow_block, tcf_block_shared(block),
848 			       extack);
849 
850 	if (dev->netdev_ops->ndo_setup_tc) {
851 		int err;
852 
853 		err = dev->netdev_ops->ndo_setup_tc(dev, TC_SETUP_BLOCK, &bo);
854 		if (err < 0) {
855 			if (err != -EOPNOTSUPP)
856 				NL_SET_ERR_MSG(extack, "Driver ndo_setup_tc failed");
857 			return err;
858 		}
859 
860 		return tcf_block_setup(block, &bo);
861 	}
862 
863 	flow_indr_dev_setup_offload(dev, sch, TC_SETUP_BLOCK, block, &bo,
864 				    tc_block_indr_cleanup);
865 	tcf_block_setup(block, &bo);
866 
867 	return -EOPNOTSUPP;
868 }
869 
870 static int tcf_block_offload_bind(struct tcf_block *block, struct Qdisc *q,
871 				  struct tcf_block_ext_info *ei,
872 				  struct netlink_ext_ack *extack)
873 {
874 	struct net_device *dev = q->dev_queue->dev;
875 	int err;
876 
877 	down_write(&block->cb_lock);
878 
879 	/* If tc offload feature is disabled and the block we try to bind
880 	 * to already has some offloaded filters, forbid to bind.
881 	 */
882 	if (dev->netdev_ops->ndo_setup_tc &&
883 	    !tc_can_offload(dev) &&
884 	    tcf_block_offload_in_use(block)) {
885 		NL_SET_ERR_MSG(extack, "Bind to offloaded block failed as dev has offload disabled");
886 		err = -EOPNOTSUPP;
887 		goto err_unlock;
888 	}
889 
890 	err = tcf_block_offload_cmd(block, dev, q, ei, FLOW_BLOCK_BIND, extack);
891 	if (err == -EOPNOTSUPP)
892 		goto no_offload_dev_inc;
893 	if (err)
894 		goto err_unlock;
895 
896 	up_write(&block->cb_lock);
897 	return 0;
898 
899 no_offload_dev_inc:
900 	if (tcf_block_offload_in_use(block))
901 		goto err_unlock;
902 
903 	err = 0;
904 	block->nooffloaddevcnt++;
905 err_unlock:
906 	up_write(&block->cb_lock);
907 	return err;
908 }
909 
910 static void tcf_block_offload_unbind(struct tcf_block *block, struct Qdisc *q,
911 				     struct tcf_block_ext_info *ei)
912 {
913 	struct net_device *dev = q->dev_queue->dev;
914 	int err;
915 
916 	down_write(&block->cb_lock);
917 	err = tcf_block_offload_cmd(block, dev, q, ei, FLOW_BLOCK_UNBIND, NULL);
918 	if (err == -EOPNOTSUPP)
919 		goto no_offload_dev_dec;
920 	up_write(&block->cb_lock);
921 	return;
922 
923 no_offload_dev_dec:
924 	WARN_ON(block->nooffloaddevcnt-- == 0);
925 	up_write(&block->cb_lock);
926 }
927 
928 static int
929 tcf_chain0_head_change_cb_add(struct tcf_block *block,
930 			      struct tcf_block_ext_info *ei,
931 			      struct netlink_ext_ack *extack)
932 {
933 	struct tcf_filter_chain_list_item *item;
934 	struct tcf_chain *chain0;
935 
936 	item = kmalloc_obj(*item);
937 	if (!item) {
938 		NL_SET_ERR_MSG(extack, "Memory allocation for head change callback item failed");
939 		return -ENOMEM;
940 	}
941 	item->chain_head_change = ei->chain_head_change;
942 	item->chain_head_change_priv = ei->chain_head_change_priv;
943 
944 	mutex_lock(&block->lock);
945 	chain0 = block->chain0.chain;
946 	if (chain0)
947 		tcf_chain_hold(chain0);
948 	else
949 		list_add(&item->list, &block->chain0.filter_chain_list);
950 	mutex_unlock(&block->lock);
951 
952 	if (chain0) {
953 		struct tcf_proto *tp_head;
954 
955 		mutex_lock(&chain0->filter_chain_lock);
956 
957 		tp_head = tcf_chain_dereference(chain0->filter_chain, chain0);
958 		if (tp_head)
959 			tcf_chain_head_change_item(item, tp_head);
960 
961 		mutex_lock(&block->lock);
962 		list_add(&item->list, &block->chain0.filter_chain_list);
963 		mutex_unlock(&block->lock);
964 
965 		mutex_unlock(&chain0->filter_chain_lock);
966 		tcf_chain_put(chain0);
967 	}
968 
969 	return 0;
970 }
971 
972 static void
973 tcf_chain0_head_change_cb_del(struct tcf_block *block,
974 			      struct tcf_block_ext_info *ei)
975 {
976 	struct tcf_filter_chain_list_item *item;
977 
978 	mutex_lock(&block->lock);
979 	list_for_each_entry(item, &block->chain0.filter_chain_list, list) {
980 		if ((!ei->chain_head_change && !ei->chain_head_change_priv) ||
981 		    (item->chain_head_change == ei->chain_head_change &&
982 		     item->chain_head_change_priv == ei->chain_head_change_priv)) {
983 			if (block->chain0.chain)
984 				tcf_chain_head_change_item(item, NULL);
985 			list_del(&item->list);
986 			mutex_unlock(&block->lock);
987 
988 			kfree(item);
989 			return;
990 		}
991 	}
992 	mutex_unlock(&block->lock);
993 	WARN_ON(1);
994 }
995 
996 struct tcf_net {
997 	spinlock_t idr_lock; /* Protects idr */
998 	struct idr idr;
999 };
1000 
1001 static unsigned int tcf_net_id;
1002 
1003 static int tcf_block_insert(struct tcf_block *block, struct net *net,
1004 			    struct netlink_ext_ack *extack)
1005 {
1006 	struct tcf_net *tn = net_generic(net, tcf_net_id);
1007 	int err;
1008 
1009 	idr_preload(GFP_KERNEL);
1010 	spin_lock(&tn->idr_lock);
1011 	err = idr_alloc_u32(&tn->idr, block, &block->index, block->index,
1012 			    GFP_NOWAIT);
1013 	spin_unlock(&tn->idr_lock);
1014 	idr_preload_end();
1015 
1016 	return err;
1017 }
1018 
1019 static void tcf_block_remove(struct tcf_block *block, struct net *net)
1020 {
1021 	struct tcf_net *tn = net_generic(net, tcf_net_id);
1022 
1023 	spin_lock(&tn->idr_lock);
1024 	idr_remove(&tn->idr, block->index);
1025 	spin_unlock(&tn->idr_lock);
1026 }
1027 
1028 static struct tcf_block *tcf_block_create(struct net *net, struct Qdisc *q,
1029 					  u32 block_index,
1030 					  struct netlink_ext_ack *extack)
1031 {
1032 	struct tcf_block *block;
1033 
1034 	block = kzalloc_obj(*block);
1035 	if (!block) {
1036 		NL_SET_ERR_MSG(extack, "Memory allocation for block failed");
1037 		return ERR_PTR(-ENOMEM);
1038 	}
1039 	mutex_init(&block->lock);
1040 	mutex_init(&block->proto_destroy_lock);
1041 	init_rwsem(&block->cb_lock);
1042 	flow_block_init(&block->flow_block);
1043 	INIT_LIST_HEAD(&block->chain_list);
1044 	INIT_LIST_HEAD(&block->owner_list);
1045 	INIT_LIST_HEAD(&block->chain0.filter_chain_list);
1046 
1047 	refcount_set(&block->refcnt, 1);
1048 	block->net = net;
1049 	block->index = block_index;
1050 	xa_init(&block->ports);
1051 
1052 	/* Don't store q pointer for blocks which are shared */
1053 	if (!tcf_block_shared(block))
1054 		block->q = q;
1055 	return block;
1056 }
1057 
1058 struct tcf_block *tcf_block_lookup(struct net *net, u32 block_index)
1059 {
1060 	struct tcf_net *tn = net_generic(net, tcf_net_id);
1061 
1062 	return idr_find(&tn->idr, block_index);
1063 }
1064 EXPORT_SYMBOL(tcf_block_lookup);
1065 
1066 static struct tcf_block *tcf_block_refcnt_get(struct net *net, u32 block_index)
1067 {
1068 	struct tcf_block *block;
1069 
1070 	rcu_read_lock();
1071 	block = tcf_block_lookup(net, block_index);
1072 	if (block && !refcount_inc_not_zero(&block->refcnt))
1073 		block = NULL;
1074 	rcu_read_unlock();
1075 
1076 	return block;
1077 }
1078 
1079 static struct tcf_chain *
1080 __tcf_get_next_chain(struct tcf_block *block, struct tcf_chain *chain)
1081 {
1082 	mutex_lock(&block->lock);
1083 	if (chain)
1084 		chain = list_is_last(&chain->list, &block->chain_list) ?
1085 			NULL : list_next_entry(chain, list);
1086 	else
1087 		chain = list_first_entry_or_null(&block->chain_list,
1088 						 struct tcf_chain, list);
1089 
1090 	/* skip all action-only chains */
1091 	while (chain && tcf_chain_held_by_acts_only(chain))
1092 		chain = list_is_last(&chain->list, &block->chain_list) ?
1093 			NULL : list_next_entry(chain, list);
1094 
1095 	if (chain)
1096 		tcf_chain_hold(chain);
1097 	mutex_unlock(&block->lock);
1098 
1099 	return chain;
1100 }
1101 
1102 /* Function to be used by all clients that want to iterate over all chains on
1103  * block. It properly obtains block->lock and takes reference to chain before
1104  * returning it. Users of this function must be tolerant to concurrent chain
1105  * insertion/deletion or ensure that no concurrent chain modification is
1106  * possible. Note that all netlink dump callbacks cannot guarantee to provide
1107  * consistent dump because rtnl lock is released each time skb is filled with
1108  * data and sent to user-space.
1109  */
1110 
1111 struct tcf_chain *
1112 tcf_get_next_chain(struct tcf_block *block, struct tcf_chain *chain)
1113 {
1114 	struct tcf_chain *chain_next = __tcf_get_next_chain(block, chain);
1115 
1116 	if (chain)
1117 		tcf_chain_put(chain);
1118 
1119 	return chain_next;
1120 }
1121 EXPORT_SYMBOL(tcf_get_next_chain);
1122 
1123 static struct tcf_proto *
1124 __tcf_get_next_proto(struct tcf_chain *chain, struct tcf_proto *tp)
1125 {
1126 	u32 prio = 0;
1127 
1128 	ASSERT_RTNL();
1129 	mutex_lock(&chain->filter_chain_lock);
1130 
1131 	if (!tp) {
1132 		tp = tcf_chain_dereference(chain->filter_chain, chain);
1133 	} else if (tcf_proto_is_deleting(tp)) {
1134 		/* 'deleting' flag is set and chain->filter_chain_lock was
1135 		 * unlocked, which means next pointer could be invalid. Restart
1136 		 * search.
1137 		 */
1138 		prio = tp->prio + 1;
1139 		tp = tcf_chain_dereference(chain->filter_chain, chain);
1140 
1141 		for (; tp; tp = tcf_chain_dereference(tp->next, chain))
1142 			if (!tp->deleting && tp->prio >= prio)
1143 				break;
1144 	} else {
1145 		tp = tcf_chain_dereference(tp->next, chain);
1146 	}
1147 
1148 	if (tp)
1149 		tcf_proto_get(tp);
1150 
1151 	mutex_unlock(&chain->filter_chain_lock);
1152 
1153 	return tp;
1154 }
1155 
1156 /* Function to be used by all clients that want to iterate over all tp's on
1157  * chain. Users of this function must be tolerant to concurrent tp
1158  * insertion/deletion or ensure that no concurrent chain modification is
1159  * possible. Note that all netlink dump callbacks cannot guarantee to provide
1160  * consistent dump because rtnl lock is released each time skb is filled with
1161  * data and sent to user-space.
1162  */
1163 
1164 struct tcf_proto *
1165 tcf_get_next_proto(struct tcf_chain *chain, struct tcf_proto *tp)
1166 {
1167 	struct tcf_proto *tp_next = __tcf_get_next_proto(chain, tp);
1168 
1169 	if (tp)
1170 		tcf_proto_put(tp, true, NULL);
1171 
1172 	return tp_next;
1173 }
1174 EXPORT_SYMBOL(tcf_get_next_proto);
1175 
1176 static void tcf_block_flush_all_chains(struct tcf_block *block, bool rtnl_held)
1177 {
1178 	struct tcf_chain *chain;
1179 
1180 	/* Last reference to block. At this point chains cannot be added or
1181 	 * removed concurrently.
1182 	 */
1183 	for (chain = tcf_get_next_chain(block, NULL);
1184 	     chain;
1185 	     chain = tcf_get_next_chain(block, chain)) {
1186 		tcf_chain_put_explicitly_created(chain);
1187 		tcf_chain_flush(chain, rtnl_held);
1188 	}
1189 }
1190 
1191 /* Lookup Qdisc and increments its reference counter.
1192  * Set parent, if necessary.
1193  */
1194 
1195 static int __tcf_qdisc_find(struct net *net, struct Qdisc **q,
1196 			    u32 *parent, int ifindex, bool rtnl_held,
1197 			    struct netlink_ext_ack *extack)
1198 {
1199 	const struct Qdisc_class_ops *cops;
1200 	struct net_device *dev;
1201 	int err = 0;
1202 
1203 	if (ifindex == TCM_IFINDEX_MAGIC_BLOCK)
1204 		return 0;
1205 
1206 	rcu_read_lock();
1207 
1208 	/* Find link */
1209 	dev = dev_get_by_index_rcu(net, ifindex);
1210 	if (!dev) {
1211 		rcu_read_unlock();
1212 		return -ENODEV;
1213 	}
1214 
1215 	/* Find qdisc */
1216 	if (!*parent) {
1217 		*q = rcu_dereference(dev->qdisc);
1218 		*parent = (*q)->handle;
1219 	} else {
1220 		*q = qdisc_lookup_rcu(dev, TC_H_MAJ(*parent));
1221 		if (!*q) {
1222 			NL_SET_ERR_MSG(extack, "Parent Qdisc doesn't exists");
1223 			err = -EINVAL;
1224 			goto errout_rcu;
1225 		}
1226 	}
1227 
1228 	*q = qdisc_refcount_inc_nz(*q);
1229 	if (!*q) {
1230 		NL_SET_ERR_MSG(extack, "Parent Qdisc doesn't exists");
1231 		err = -EINVAL;
1232 		goto errout_rcu;
1233 	}
1234 
1235 	/* Is it classful? */
1236 	cops = (*q)->ops->cl_ops;
1237 	if (!cops) {
1238 		NL_SET_ERR_MSG(extack, "Qdisc not classful");
1239 		err = -EINVAL;
1240 		goto errout_qdisc;
1241 	}
1242 
1243 	if (!cops->tcf_block) {
1244 		NL_SET_ERR_MSG(extack, "Class doesn't support blocks");
1245 		err = -EOPNOTSUPP;
1246 		goto errout_qdisc;
1247 	}
1248 
1249 errout_rcu:
1250 	/* At this point we know that qdisc is not noop_qdisc,
1251 	 * which means that qdisc holds a reference to net_device
1252 	 * and we hold a reference to qdisc, so it is safe to release
1253 	 * rcu read lock.
1254 	 */
1255 	rcu_read_unlock();
1256 	return err;
1257 
1258 errout_qdisc:
1259 	rcu_read_unlock();
1260 
1261 	if (rtnl_held)
1262 		qdisc_put(*q);
1263 	else
1264 		qdisc_put_unlocked(*q);
1265 	*q = NULL;
1266 
1267 	return err;
1268 }
1269 
1270 static int __tcf_qdisc_cl_find(struct Qdisc *q, u32 parent, unsigned long *cl,
1271 			       int ifindex, struct netlink_ext_ack *extack)
1272 {
1273 	if (ifindex == TCM_IFINDEX_MAGIC_BLOCK)
1274 		return 0;
1275 
1276 	/* Do we search for filter, attached to class? */
1277 	if (TC_H_MIN(parent)) {
1278 		const struct Qdisc_class_ops *cops = q->ops->cl_ops;
1279 
1280 		*cl = cops->find(q, parent);
1281 		if (*cl == 0) {
1282 			NL_SET_ERR_MSG(extack, "Specified class doesn't exist");
1283 			return -ENOENT;
1284 		}
1285 	}
1286 
1287 	return 0;
1288 }
1289 
1290 static struct tcf_block *__tcf_block_find(struct net *net, struct Qdisc *q,
1291 					  unsigned long cl, int ifindex,
1292 					  u32 block_index,
1293 					  struct netlink_ext_ack *extack)
1294 {
1295 	struct tcf_block *block;
1296 
1297 	if (ifindex == TCM_IFINDEX_MAGIC_BLOCK) {
1298 		block = tcf_block_refcnt_get(net, block_index);
1299 		if (!block) {
1300 			NL_SET_ERR_MSG(extack, "Block of given index was not found");
1301 			return ERR_PTR(-EINVAL);
1302 		}
1303 	} else {
1304 		const struct Qdisc_class_ops *cops = q->ops->cl_ops;
1305 
1306 		block = cops->tcf_block(q, cl, extack);
1307 		if (!block)
1308 			return ERR_PTR(-EINVAL);
1309 
1310 		if (tcf_block_shared(block)) {
1311 			NL_SET_ERR_MSG(extack, "This filter block is shared. Please use the block index to manipulate the filters");
1312 			return ERR_PTR(-EOPNOTSUPP);
1313 		}
1314 
1315 		/* Always take reference to block in order to support execution
1316 		 * of rules update path of cls API without rtnl lock. Caller
1317 		 * must release block when it is finished using it. 'if' block
1318 		 * of this conditional obtain reference to block by calling
1319 		 * tcf_block_refcnt_get().
1320 		 */
1321 		refcount_inc(&block->refcnt);
1322 	}
1323 
1324 	return block;
1325 }
1326 
1327 static void __tcf_block_put(struct tcf_block *block, struct Qdisc *q,
1328 			    struct tcf_block_ext_info *ei, bool rtnl_held)
1329 {
1330 	if (refcount_dec_and_mutex_lock(&block->refcnt, &block->lock)) {
1331 		/* Flushing/putting all chains will cause the block to be
1332 		 * deallocated when last chain is freed. However, if chain_list
1333 		 * is empty, block has to be manually deallocated. After block
1334 		 * reference counter reached 0, it is no longer possible to
1335 		 * increment it or add new chains to block.
1336 		 */
1337 		bool free_block = list_empty(&block->chain_list);
1338 
1339 		mutex_unlock(&block->lock);
1340 		if (tcf_block_shared(block))
1341 			tcf_block_remove(block, block->net);
1342 
1343 		if (q)
1344 			tcf_block_offload_unbind(block, q, ei);
1345 
1346 		if (free_block)
1347 			tcf_block_destroy(block);
1348 		else
1349 			tcf_block_flush_all_chains(block, rtnl_held);
1350 	} else if (q) {
1351 		tcf_block_offload_unbind(block, q, ei);
1352 	}
1353 }
1354 
1355 static void tcf_block_refcnt_put(struct tcf_block *block, bool rtnl_held)
1356 {
1357 	__tcf_block_put(block, NULL, NULL, rtnl_held);
1358 }
1359 
1360 /* Find tcf block.
1361  * Set q, parent, cl when appropriate.
1362  */
1363 
1364 static struct tcf_block *tcf_block_find(struct net *net, struct Qdisc **q,
1365 					u32 *parent, unsigned long *cl,
1366 					int ifindex, u32 block_index,
1367 					struct netlink_ext_ack *extack)
1368 {
1369 	struct tcf_block *block;
1370 	int err = 0;
1371 
1372 	ASSERT_RTNL();
1373 
1374 	err = __tcf_qdisc_find(net, q, parent, ifindex, true, extack);
1375 	if (err)
1376 		goto errout;
1377 
1378 	err = __tcf_qdisc_cl_find(*q, *parent, cl, ifindex, extack);
1379 	if (err)
1380 		goto errout_qdisc;
1381 
1382 	block = __tcf_block_find(net, *q, *cl, ifindex, block_index, extack);
1383 	if (IS_ERR(block)) {
1384 		err = PTR_ERR(block);
1385 		goto errout_qdisc;
1386 	}
1387 
1388 	return block;
1389 
1390 errout_qdisc:
1391 	if (*q)
1392 		qdisc_put(*q);
1393 errout:
1394 	*q = NULL;
1395 	return ERR_PTR(err);
1396 }
1397 
1398 static void tcf_block_release(struct Qdisc *q, struct tcf_block *block,
1399 			      bool rtnl_held)
1400 {
1401 	if (!IS_ERR_OR_NULL(block))
1402 		tcf_block_refcnt_put(block, rtnl_held);
1403 
1404 	if (q) {
1405 		if (rtnl_held)
1406 			qdisc_put(q);
1407 		else
1408 			qdisc_put_unlocked(q);
1409 	}
1410 }
1411 
1412 struct tcf_block_owner_item {
1413 	struct list_head list;
1414 	struct Qdisc *q;
1415 	enum flow_block_binder_type binder_type;
1416 };
1417 
1418 static void
1419 tcf_block_owner_netif_keep_dst(struct tcf_block *block,
1420 			       struct Qdisc *q,
1421 			       enum flow_block_binder_type binder_type)
1422 {
1423 	if (block->keep_dst &&
1424 	    binder_type != FLOW_BLOCK_BINDER_TYPE_CLSACT_INGRESS &&
1425 	    binder_type != FLOW_BLOCK_BINDER_TYPE_CLSACT_EGRESS)
1426 		netif_keep_dst(qdisc_dev(q));
1427 }
1428 
1429 void tcf_block_netif_keep_dst(struct tcf_block *block)
1430 {
1431 	struct tcf_block_owner_item *item;
1432 
1433 	block->keep_dst = true;
1434 	list_for_each_entry(item, &block->owner_list, list)
1435 		tcf_block_owner_netif_keep_dst(block, item->q,
1436 					       item->binder_type);
1437 }
1438 EXPORT_SYMBOL(tcf_block_netif_keep_dst);
1439 
1440 static int tcf_block_owner_add(struct tcf_block *block,
1441 			       struct Qdisc *q,
1442 			       enum flow_block_binder_type binder_type)
1443 {
1444 	struct tcf_block_owner_item *item;
1445 
1446 	item = kmalloc_obj(*item);
1447 	if (!item)
1448 		return -ENOMEM;
1449 	item->q = q;
1450 	item->binder_type = binder_type;
1451 	list_add(&item->list, &block->owner_list);
1452 	return 0;
1453 }
1454 
1455 static void tcf_block_owner_del(struct tcf_block *block,
1456 				struct Qdisc *q,
1457 				enum flow_block_binder_type binder_type)
1458 {
1459 	struct tcf_block_owner_item *item;
1460 
1461 	list_for_each_entry(item, &block->owner_list, list) {
1462 		if (item->q == q && item->binder_type == binder_type) {
1463 			list_del(&item->list);
1464 			kfree(item);
1465 			return;
1466 		}
1467 	}
1468 	WARN_ON(1);
1469 }
1470 
1471 static bool tcf_block_tracks_dev(struct tcf_block *block,
1472 				 struct tcf_block_ext_info *ei)
1473 {
1474 	return tcf_block_shared(block) &&
1475 	       (ei->binder_type == FLOW_BLOCK_BINDER_TYPE_CLSACT_INGRESS ||
1476 		ei->binder_type == FLOW_BLOCK_BINDER_TYPE_CLSACT_EGRESS);
1477 }
1478 
1479 int tcf_block_get_ext(struct tcf_block **p_block, struct Qdisc *q,
1480 		      struct tcf_block_ext_info *ei,
1481 		      struct netlink_ext_ack *extack)
1482 {
1483 	struct net_device *dev = qdisc_dev(q);
1484 	struct net *net = qdisc_net(q);
1485 	struct tcf_block *block = NULL;
1486 	int err;
1487 
1488 	if (ei->block_index)
1489 		/* block_index not 0 means the shared block is requested */
1490 		block = tcf_block_refcnt_get(net, ei->block_index);
1491 
1492 	if (!block) {
1493 		block = tcf_block_create(net, q, ei->block_index, extack);
1494 		if (IS_ERR(block))
1495 			return PTR_ERR(block);
1496 		if (tcf_block_shared(block)) {
1497 			err = tcf_block_insert(block, net, extack);
1498 			if (err)
1499 				goto err_block_insert;
1500 		}
1501 	}
1502 
1503 	err = tcf_block_owner_add(block, q, ei->binder_type);
1504 	if (err)
1505 		goto err_block_owner_add;
1506 
1507 	tcf_block_owner_netif_keep_dst(block, q, ei->binder_type);
1508 
1509 	err = tcf_chain0_head_change_cb_add(block, ei, extack);
1510 	if (err)
1511 		goto err_chain0_head_change_cb_add;
1512 
1513 	err = tcf_block_offload_bind(block, q, ei, extack);
1514 	if (err)
1515 		goto err_block_offload_bind;
1516 
1517 	if (tcf_block_tracks_dev(block, ei)) {
1518 		err = xa_insert(&block->ports, dev->ifindex, dev, GFP_KERNEL);
1519 		if (err) {
1520 			NL_SET_ERR_MSG(extack, "block dev insert failed");
1521 			goto err_dev_insert;
1522 		}
1523 	}
1524 
1525 	*p_block = block;
1526 	return 0;
1527 
1528 err_dev_insert:
1529 	tcf_block_offload_unbind(block, q, ei);
1530 err_block_offload_bind:
1531 	tcf_chain0_head_change_cb_del(block, ei);
1532 err_chain0_head_change_cb_add:
1533 	tcf_block_owner_del(block, q, ei->binder_type);
1534 err_block_owner_add:
1535 err_block_insert:
1536 	tcf_block_refcnt_put(block, true);
1537 	return err;
1538 }
1539 EXPORT_SYMBOL(tcf_block_get_ext);
1540 
1541 static void tcf_chain_head_change_dflt(struct tcf_proto *tp_head, void *priv)
1542 {
1543 	struct tcf_proto __rcu **p_filter_chain = priv;
1544 
1545 	rcu_assign_pointer(*p_filter_chain, tp_head);
1546 }
1547 
1548 int tcf_block_get(struct tcf_block **p_block,
1549 		  struct tcf_proto __rcu **p_filter_chain, struct Qdisc *q,
1550 		  struct netlink_ext_ack *extack)
1551 {
1552 	struct tcf_block_ext_info ei = {
1553 		.chain_head_change = tcf_chain_head_change_dflt,
1554 		.chain_head_change_priv = p_filter_chain,
1555 	};
1556 
1557 	WARN_ON(!p_filter_chain);
1558 	return tcf_block_get_ext(p_block, q, &ei, extack);
1559 }
1560 EXPORT_SYMBOL(tcf_block_get);
1561 
1562 /* XXX: Standalone actions are not allowed to jump to any chain, and bound
1563  * actions should be all removed after flushing.
1564  */
1565 void tcf_block_put_ext(struct tcf_block *block, struct Qdisc *q,
1566 		       struct tcf_block_ext_info *ei)
1567 {
1568 	struct net_device *dev = qdisc_dev(q);
1569 
1570 	if (!block)
1571 		return;
1572 	if (tcf_block_tracks_dev(block, ei))
1573 		xa_erase(&block->ports, dev->ifindex);
1574 	tcf_chain0_head_change_cb_del(block, ei);
1575 	tcf_block_owner_del(block, q, ei->binder_type);
1576 
1577 	__tcf_block_put(block, q, ei, true);
1578 }
1579 EXPORT_SYMBOL(tcf_block_put_ext);
1580 
1581 void tcf_block_put(struct tcf_block *block)
1582 {
1583 	struct tcf_block_ext_info ei = {0, };
1584 
1585 	if (!block)
1586 		return;
1587 	tcf_block_put_ext(block, block->q, &ei);
1588 }
1589 
1590 EXPORT_SYMBOL(tcf_block_put);
1591 
1592 static int
1593 tcf_block_playback_offloads(struct tcf_block *block, flow_setup_cb_t *cb,
1594 			    void *cb_priv, bool add, bool offload_in_use,
1595 			    struct netlink_ext_ack *extack)
1596 {
1597 	struct tcf_chain *chain, *chain_prev;
1598 	struct tcf_proto *tp, *tp_prev;
1599 	int err;
1600 
1601 	lockdep_assert_held(&block->cb_lock);
1602 
1603 	for (chain = __tcf_get_next_chain(block, NULL);
1604 	     chain;
1605 	     chain_prev = chain,
1606 		     chain = __tcf_get_next_chain(block, chain),
1607 		     tcf_chain_put(chain_prev)) {
1608 		if (chain->tmplt_ops && add)
1609 			chain->tmplt_ops->tmplt_reoffload(chain, true, cb,
1610 							  cb_priv);
1611 		for (tp = __tcf_get_next_proto(chain, NULL); tp;
1612 		     tp_prev = tp,
1613 			     tp = __tcf_get_next_proto(chain, tp),
1614 			     tcf_proto_put(tp_prev, true, NULL)) {
1615 			if (tp->ops->reoffload) {
1616 				err = tp->ops->reoffload(tp, add, cb, cb_priv,
1617 							 extack);
1618 				if (err && add)
1619 					goto err_playback_remove;
1620 			} else if (add && offload_in_use) {
1621 				err = -EOPNOTSUPP;
1622 				NL_SET_ERR_MSG(extack, "Filter HW offload failed - classifier without re-offloading support");
1623 				goto err_playback_remove;
1624 			}
1625 		}
1626 		if (chain->tmplt_ops && !add)
1627 			chain->tmplt_ops->tmplt_reoffload(chain, false, cb,
1628 							  cb_priv);
1629 	}
1630 
1631 	return 0;
1632 
1633 err_playback_remove:
1634 	tcf_proto_put(tp, true, NULL);
1635 	tcf_chain_put(chain);
1636 	tcf_block_playback_offloads(block, cb, cb_priv, false, offload_in_use,
1637 				    extack);
1638 	return err;
1639 }
1640 
1641 static int tcf_block_bind(struct tcf_block *block,
1642 			  struct flow_block_offload *bo)
1643 {
1644 	struct flow_block_cb *block_cb, *next;
1645 	int err, i = 0;
1646 
1647 	lockdep_assert_held(&block->cb_lock);
1648 
1649 	list_for_each_entry(block_cb, &bo->cb_list, list) {
1650 		err = tcf_block_playback_offloads(block, block_cb->cb,
1651 						  block_cb->cb_priv, true,
1652 						  tcf_block_offload_in_use(block),
1653 						  bo->extack);
1654 		if (err)
1655 			goto err_unroll;
1656 		if (!bo->unlocked_driver_cb)
1657 			block->lockeddevcnt++;
1658 
1659 		i++;
1660 	}
1661 	list_splice(&bo->cb_list, &block->flow_block.cb_list);
1662 
1663 	return 0;
1664 
1665 err_unroll:
1666 	list_for_each_entry_safe(block_cb, next, &bo->cb_list, list) {
1667 		list_del(&block_cb->driver_list);
1668 		if (i-- > 0) {
1669 			list_del(&block_cb->list);
1670 			tcf_block_playback_offloads(block, block_cb->cb,
1671 						    block_cb->cb_priv, false,
1672 						    tcf_block_offload_in_use(block),
1673 						    NULL);
1674 			if (!bo->unlocked_driver_cb)
1675 				block->lockeddevcnt--;
1676 		}
1677 		flow_block_cb_free(block_cb);
1678 	}
1679 
1680 	return err;
1681 }
1682 
1683 static void tcf_block_unbind(struct tcf_block *block,
1684 			     struct flow_block_offload *bo)
1685 {
1686 	struct flow_block_cb *block_cb, *next;
1687 
1688 	lockdep_assert_held(&block->cb_lock);
1689 
1690 	list_for_each_entry_safe(block_cb, next, &bo->cb_list, list) {
1691 		tcf_block_playback_offloads(block, block_cb->cb,
1692 					    block_cb->cb_priv, false,
1693 					    tcf_block_offload_in_use(block),
1694 					    NULL);
1695 		list_del(&block_cb->list);
1696 		flow_block_cb_free(block_cb);
1697 		if (!bo->unlocked_driver_cb)
1698 			block->lockeddevcnt--;
1699 	}
1700 }
1701 
1702 static int tcf_block_setup(struct tcf_block *block,
1703 			   struct flow_block_offload *bo)
1704 {
1705 	int err;
1706 
1707 	switch (bo->command) {
1708 	case FLOW_BLOCK_BIND:
1709 		err = tcf_block_bind(block, bo);
1710 		break;
1711 	case FLOW_BLOCK_UNBIND:
1712 		err = 0;
1713 		tcf_block_unbind(block, bo);
1714 		break;
1715 	default:
1716 		WARN_ON_ONCE(1);
1717 		err = -EOPNOTSUPP;
1718 	}
1719 
1720 	return err;
1721 }
1722 
1723 /* Main classifier routine: scans classifier chain attached
1724  * to this qdisc, (optionally) tests for protocol and asks
1725  * specific classifiers.
1726  */
1727 static inline int __tcf_classify(struct sk_buff *skb,
1728 				 const struct tcf_proto *tp,
1729 				 const struct tcf_proto *orig_tp,
1730 				 struct tcf_result *res,
1731 				 bool compat_mode,
1732 				 struct tcf_exts_miss_cookie_node *n,
1733 				 int act_index,
1734 				 u32 *last_executed_chain)
1735 {
1736 #ifdef CONFIG_NET_CLS_ACT
1737 	const int max_reclassify_loop = 16;
1738 	const struct tcf_proto *first_tp;
1739 	int limit = 0;
1740 
1741 reclassify:
1742 #endif
1743 	for (; tp; tp = rcu_dereference_bh(tp->next)) {
1744 		__be16 protocol = skb_protocol(skb, false);
1745 		int err = 0;
1746 
1747 		if (n) {
1748 			struct tcf_exts *exts;
1749 
1750 			if (n->tp_prio != tp->prio)
1751 				continue;
1752 
1753 			/* We re-lookup the tp and chain based on index instead
1754 			 * of having hard refs and locks to them, so do a sanity
1755 			 * check if any of tp,chain,exts was replaced by the
1756 			 * time we got here with a cookie from hardware.
1757 			 */
1758 			if (unlikely(n->tp != tp || n->tp->chain != n->chain ||
1759 				     !tp->ops->get_exts)) {
1760 				tcf_set_drop_reason(skb,
1761 						    SKB_DROP_REASON_TC_COOKIE_ERROR);
1762 				return TC_ACT_SHOT;
1763 			}
1764 
1765 			exts = tp->ops->get_exts(tp, n->handle);
1766 			if (unlikely(!exts || n->exts != exts)) {
1767 				tcf_set_drop_reason(skb,
1768 						    SKB_DROP_REASON_TC_COOKIE_ERROR);
1769 				return TC_ACT_SHOT;
1770 			}
1771 
1772 			n = NULL;
1773 			err = tcf_exts_exec_ex(skb, exts, act_index, res);
1774 		} else {
1775 			if (tp->protocol != protocol &&
1776 			    tp->protocol != htons(ETH_P_ALL))
1777 				continue;
1778 
1779 			err = tc_classify(skb, tp, res);
1780 		}
1781 #ifdef CONFIG_NET_CLS_ACT
1782 		if (unlikely(err == TC_ACT_RECLASSIFY && !compat_mode)) {
1783 			first_tp = orig_tp;
1784 			*last_executed_chain = first_tp->chain->index;
1785 			goto reset;
1786 		} else if (unlikely(TC_ACT_EXT_CMP(err, TC_ACT_GOTO_CHAIN))) {
1787 			first_tp = res->goto_tp;
1788 			*last_executed_chain = err & TC_ACT_EXT_VAL_MASK;
1789 			goto reset;
1790 		}
1791 #endif
1792 		if (err >= 0)
1793 			return err;
1794 	}
1795 
1796 	if (unlikely(n)) {
1797 		tcf_set_drop_reason(skb,
1798 				    SKB_DROP_REASON_TC_COOKIE_ERROR);
1799 		return TC_ACT_SHOT;
1800 	}
1801 
1802 	return TC_ACT_UNSPEC; /* signal: continue lookup */
1803 #ifdef CONFIG_NET_CLS_ACT
1804 reset:
1805 	if (unlikely(limit++ >= max_reclassify_loop)) {
1806 		net_notice_ratelimited("%u: reclassify loop, rule prio %u, protocol %02x\n",
1807 				       tp->chain->block->index,
1808 				       tp->prio & 0xffff,
1809 				       ntohs(tp->protocol));
1810 		tcf_set_drop_reason(skb,
1811 				    SKB_DROP_REASON_TC_RECLASSIFY_LOOP);
1812 		return TC_ACT_SHOT;
1813 	}
1814 
1815 	tp = first_tp;
1816 	goto reclassify;
1817 #endif
1818 }
1819 
1820 int tcf_classify(struct sk_buff *skb,
1821 		 const struct tcf_block *block,
1822 		 const struct tcf_proto *tp,
1823 		 struct tcf_result *res, bool compat_mode)
1824 {
1825 #if !IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
1826 	u32 last_executed_chain = 0;
1827 
1828 	return __tcf_classify(skb, tp, tp, res, compat_mode, NULL, 0,
1829 			      &last_executed_chain);
1830 #else
1831 	u32 last_executed_chain = tp ? tp->chain->index : 0;
1832 	struct tcf_exts_miss_cookie_node *n = NULL;
1833 	const struct tcf_proto *orig_tp = tp;
1834 	struct tc_skb_ext *ext;
1835 	int act_index = 0;
1836 	int ret;
1837 
1838 	if (block) {
1839 		ext = skb_ext_find(skb, TC_SKB_EXT);
1840 
1841 		if (ext && (ext->chain || ext->act_miss)) {
1842 			struct tcf_chain *fchain;
1843 			u32 chain;
1844 
1845 			if (ext->act_miss) {
1846 				n = tcf_exts_miss_cookie_lookup(ext->act_miss_cookie,
1847 								&act_index);
1848 				if (!n) {
1849 					tcf_set_drop_reason(skb,
1850 							    SKB_DROP_REASON_TC_COOKIE_ERROR);
1851 					return TC_ACT_SHOT;
1852 				}
1853 
1854 				chain = n->chain_index;
1855 			} else {
1856 				chain = ext->chain;
1857 			}
1858 
1859 			fchain = tcf_chain_lookup_rcu(block, chain);
1860 			if (!fchain) {
1861 				tcf_set_drop_reason(skb,
1862 						    SKB_DROP_REASON_TC_CHAIN_NOTFOUND);
1863 
1864 				return TC_ACT_SHOT;
1865 			}
1866 
1867 			/* Consume, so cloned/redirect skbs won't inherit ext */
1868 			skb_ext_del(skb, TC_SKB_EXT);
1869 
1870 			tp = rcu_dereference_bh(fchain->filter_chain);
1871 			last_executed_chain = fchain->index;
1872 		}
1873 	}
1874 
1875 	ret = __tcf_classify(skb, tp, orig_tp, res, compat_mode, n, act_index,
1876 			     &last_executed_chain);
1877 
1878 	if (tc_skb_ext_tc_enabled()) {
1879 		/* If we missed on some chain */
1880 		if (ret == TC_ACT_UNSPEC && last_executed_chain) {
1881 			struct tc_skb_cb *cb = tc_skb_cb(skb);
1882 
1883 			ext = tc_skb_ext_alloc(skb);
1884 			if (!ext) {
1885 				tcf_set_drop_reason(skb, SKB_DROP_REASON_NOMEM);
1886 				return TC_ACT_SHOT;
1887 			}
1888 			ext->chain = last_executed_chain;
1889 			ext->mru = cb->mru;
1890 			ext->post_ct = qdisc_skb_cb(skb)->post_ct;
1891 			ext->post_ct_snat = qdisc_skb_cb(skb)->post_ct_snat;
1892 			ext->post_ct_dnat = qdisc_skb_cb(skb)->post_ct_dnat;
1893 			ext->zone = cb->zone;
1894 		}
1895 	}
1896 
1897 	return ret;
1898 #endif
1899 }
1900 EXPORT_SYMBOL(tcf_classify);
1901 
1902 struct tcf_chain_info {
1903 	struct tcf_proto __rcu **pprev;
1904 	struct tcf_proto __rcu *next;
1905 };
1906 
1907 static struct tcf_proto *tcf_chain_tp_prev(struct tcf_chain *chain,
1908 					   struct tcf_chain_info *chain_info)
1909 {
1910 	return tcf_chain_dereference(*chain_info->pprev, chain);
1911 }
1912 
1913 static int tcf_chain_tp_insert(struct tcf_chain *chain,
1914 			       struct tcf_chain_info *chain_info,
1915 			       struct tcf_proto *tp)
1916 {
1917 	if (chain->flushing)
1918 		return -EAGAIN;
1919 
1920 	RCU_INIT_POINTER(tp->next, tcf_chain_tp_prev(chain, chain_info));
1921 	if (*chain_info->pprev == chain->filter_chain)
1922 		tcf_chain0_head_change(chain, tp);
1923 	tcf_proto_get(tp);
1924 	rcu_assign_pointer(*chain_info->pprev, tp);
1925 
1926 	return 0;
1927 }
1928 
1929 static void tcf_chain_tp_remove(struct tcf_chain *chain,
1930 				struct tcf_chain_info *chain_info,
1931 				struct tcf_proto *tp)
1932 {
1933 	struct tcf_proto *next = tcf_chain_dereference(chain_info->next, chain);
1934 
1935 	tcf_proto_mark_delete(tp);
1936 	if (tp == chain->filter_chain)
1937 		tcf_chain0_head_change(chain, next);
1938 	RCU_INIT_POINTER(*chain_info->pprev, next);
1939 }
1940 
1941 static struct tcf_proto *tcf_chain_tp_find(struct tcf_chain *chain,
1942 					   struct tcf_chain_info *chain_info,
1943 					   u32 protocol, u32 prio,
1944 					   bool prio_allocate,
1945 					   struct netlink_ext_ack *extack);
1946 
1947 /* Try to insert new proto.
1948  * If proto with specified priority already exists, free new proto
1949  * and return existing one.
1950  */
1951 
1952 static struct tcf_proto *tcf_chain_tp_insert_unique(struct tcf_chain *chain,
1953 						    struct tcf_proto *tp_new,
1954 						    u32 protocol, u32 prio,
1955 						    bool rtnl_held)
1956 {
1957 	struct tcf_chain_info chain_info;
1958 	struct tcf_proto *tp;
1959 	int err = 0;
1960 
1961 	mutex_lock(&chain->filter_chain_lock);
1962 
1963 	if (tcf_proto_exists_destroying(chain, tp_new)) {
1964 		mutex_unlock(&chain->filter_chain_lock);
1965 		tcf_proto_destroy(tp_new, rtnl_held, false, NULL);
1966 		return ERR_PTR(-EAGAIN);
1967 	}
1968 
1969 	tp = tcf_chain_tp_find(chain, &chain_info, protocol, prio, false, NULL);
1970 	if (!tp)
1971 		err = tcf_chain_tp_insert(chain, &chain_info, tp_new);
1972 	mutex_unlock(&chain->filter_chain_lock);
1973 
1974 	if (tp) {
1975 		tcf_proto_destroy(tp_new, rtnl_held, false, NULL);
1976 		tp_new = tp;
1977 	} else if (err) {
1978 		tcf_proto_destroy(tp_new, rtnl_held, false, NULL);
1979 		tp_new = ERR_PTR(err);
1980 	}
1981 
1982 	return tp_new;
1983 }
1984 
1985 static void tcf_chain_tp_delete_empty(struct tcf_chain *chain,
1986 				      struct tcf_proto *tp, bool rtnl_held,
1987 				      struct netlink_ext_ack *extack)
1988 {
1989 	struct tcf_chain_info chain_info;
1990 	struct tcf_proto *tp_iter;
1991 	struct tcf_proto **pprev;
1992 	struct tcf_proto *next;
1993 
1994 	mutex_lock(&chain->filter_chain_lock);
1995 
1996 	/* Atomically find and remove tp from chain. */
1997 	for (pprev = &chain->filter_chain;
1998 	     (tp_iter = tcf_chain_dereference(*pprev, chain));
1999 	     pprev = &tp_iter->next) {
2000 		if (tp_iter == tp) {
2001 			chain_info.pprev = pprev;
2002 			chain_info.next = tp_iter->next;
2003 			WARN_ON(tp_iter->deleting);
2004 			break;
2005 		}
2006 	}
2007 	/* Verify that tp still exists and no new filters were inserted
2008 	 * concurrently.
2009 	 * Mark tp for deletion if it is empty.
2010 	 */
2011 	if (!tp_iter || !tcf_proto_check_delete(tp)) {
2012 		mutex_unlock(&chain->filter_chain_lock);
2013 		return;
2014 	}
2015 
2016 	tcf_proto_signal_destroying(chain, tp);
2017 	next = tcf_chain_dereference(chain_info.next, chain);
2018 	if (tp == chain->filter_chain)
2019 		tcf_chain0_head_change(chain, next);
2020 	RCU_INIT_POINTER(*chain_info.pprev, next);
2021 	mutex_unlock(&chain->filter_chain_lock);
2022 
2023 	tcf_proto_put(tp, rtnl_held, extack);
2024 }
2025 
2026 static struct tcf_proto *tcf_chain_tp_find(struct tcf_chain *chain,
2027 					   struct tcf_chain_info *chain_info,
2028 					   u32 protocol, u32 prio,
2029 					   bool prio_allocate,
2030 					   struct netlink_ext_ack *extack)
2031 {
2032 	struct tcf_proto **pprev;
2033 	struct tcf_proto *tp;
2034 
2035 	/* Check the chain for existence of proto-tcf with this priority */
2036 	for (pprev = &chain->filter_chain;
2037 	     (tp = tcf_chain_dereference(*pprev, chain));
2038 	     pprev = &tp->next) {
2039 		if (tp->prio >= prio) {
2040 			if (tp->prio == prio) {
2041 				if (prio_allocate) {
2042 					NL_SET_ERR_MSG(extack, "Lowest ID from auto-alloc range already in use");
2043 					return ERR_PTR(-ENOSPC);
2044 				}
2045 				if (tp->protocol != protocol && protocol) {
2046 					NL_SET_ERR_MSG(extack, "Protocol mismatch for filter with specified priority");
2047 					return ERR_PTR(-EINVAL);
2048 				}
2049 			} else {
2050 				tp = NULL;
2051 			}
2052 			break;
2053 		}
2054 	}
2055 	chain_info->pprev = pprev;
2056 	if (tp) {
2057 		chain_info->next = tp->next;
2058 		tcf_proto_get(tp);
2059 	} else {
2060 		chain_info->next = NULL;
2061 	}
2062 	return tp;
2063 }
2064 
2065 static int tcf_fill_node(struct net *net, struct sk_buff *skb,
2066 			 struct tcf_proto *tp, struct tcf_block *block,
2067 			 struct Qdisc *q, u32 parent, void *fh,
2068 			 u32 portid, u32 seq, u16 flags, int event,
2069 			 bool terse_dump, bool rtnl_held,
2070 			 struct netlink_ext_ack *extack)
2071 {
2072 	struct tcmsg *tcm;
2073 	struct nlmsghdr  *nlh;
2074 	unsigned char *b = skb_tail_pointer(skb);
2075 	int ret = -EMSGSIZE;
2076 
2077 	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*tcm), flags);
2078 	if (!nlh)
2079 		goto out_nlmsg_trim;
2080 	tcm = nlmsg_data(nlh);
2081 	tcm->tcm_family = AF_UNSPEC;
2082 	tcm->tcm__pad1 = 0;
2083 	tcm->tcm__pad2 = 0;
2084 	if (q) {
2085 		tcm->tcm_ifindex = qdisc_dev(q)->ifindex;
2086 		tcm->tcm_parent = parent;
2087 	} else {
2088 		tcm->tcm_ifindex = TCM_IFINDEX_MAGIC_BLOCK;
2089 		tcm->tcm_block_index = block->index;
2090 	}
2091 	tcm->tcm_info = TC_H_MAKE(tp->prio, tp->protocol);
2092 	if (nla_put_string(skb, TCA_KIND, tp->ops->kind))
2093 		goto nla_put_failure;
2094 	if (nla_put_u32(skb, TCA_CHAIN, tp->chain->index))
2095 		goto nla_put_failure;
2096 	if (!fh) {
2097 		tcm->tcm_handle = 0;
2098 	} else if (terse_dump) {
2099 		if (tp->ops->terse_dump) {
2100 			if (tp->ops->terse_dump(net, tp, fh, skb, tcm,
2101 						rtnl_held) < 0)
2102 				goto nla_put_failure;
2103 		} else {
2104 			goto cls_op_not_supp;
2105 		}
2106 	} else {
2107 		if (tp->ops->dump &&
2108 		    tp->ops->dump(net, tp, fh, skb, tcm, rtnl_held) < 0)
2109 			goto nla_put_failure;
2110 	}
2111 
2112 	if (extack && extack->_msg &&
2113 	    nla_put_string(skb, TCA_EXT_WARN_MSG, extack->_msg))
2114 		goto nla_put_failure;
2115 
2116 	nlh->nlmsg_len = skb_tail_pointer(skb) - b;
2117 
2118 	return skb->len;
2119 
2120 cls_op_not_supp:
2121 	ret = -EOPNOTSUPP;
2122 out_nlmsg_trim:
2123 nla_put_failure:
2124 	nlmsg_trim(skb, b);
2125 	return ret;
2126 }
2127 
2128 static struct sk_buff *tfilter_notify_prep(struct net *net,
2129 					   struct sk_buff *oskb,
2130 					   struct nlmsghdr *n,
2131 					   struct tcf_proto *tp,
2132 					   struct tcf_block *block,
2133 					   struct Qdisc *q, u32 parent,
2134 					   void *fh, int event,
2135 					   u32 portid, bool rtnl_held,
2136 					   struct netlink_ext_ack *extack)
2137 {
2138 	unsigned int size = oskb ? max(NLMSG_GOODSIZE, oskb->len) : NLMSG_GOODSIZE;
2139 	struct sk_buff *skb;
2140 	int ret;
2141 
2142 retry:
2143 	skb = alloc_skb(size, GFP_KERNEL);
2144 	if (!skb)
2145 		return ERR_PTR(-ENOBUFS);
2146 
2147 	ret = tcf_fill_node(net, skb, tp, block, q, parent, fh, portid,
2148 			    n->nlmsg_seq, n->nlmsg_flags, event, false,
2149 			    rtnl_held, extack);
2150 	if (ret <= 0) {
2151 		kfree_skb(skb);
2152 		if (ret == -EMSGSIZE) {
2153 			size += NLMSG_GOODSIZE;
2154 			goto retry;
2155 		}
2156 		return ERR_PTR(-EINVAL);
2157 	}
2158 	return skb;
2159 }
2160 
2161 static int tfilter_notify(struct net *net, struct sk_buff *oskb,
2162 			  struct nlmsghdr *n, struct tcf_proto *tp,
2163 			  struct tcf_block *block, struct Qdisc *q,
2164 			  u32 parent, void *fh, int event, bool unicast,
2165 			  bool rtnl_held, struct netlink_ext_ack *extack)
2166 {
2167 	struct sk_buff *skb;
2168 	u32 portid = oskb ? NETLINK_CB(oskb).portid : 0;
2169 	int err = 0;
2170 
2171 	if (!unicast && !rtnl_notify_needed(net, n->nlmsg_flags, RTNLGRP_TC))
2172 		return 0;
2173 
2174 	skb = tfilter_notify_prep(net, oskb, n, tp, block, q, parent, fh, event,
2175 				  portid, rtnl_held, extack);
2176 	if (IS_ERR(skb))
2177 		return PTR_ERR(skb);
2178 
2179 	if (unicast)
2180 		err = rtnl_unicast(skb, net, portid);
2181 	else
2182 		err = rtnetlink_send(skb, net, portid, RTNLGRP_TC,
2183 				     n->nlmsg_flags & NLM_F_ECHO);
2184 	return err;
2185 }
2186 
2187 static int tfilter_del_notify(struct net *net, struct sk_buff *oskb,
2188 			      struct nlmsghdr *n, struct tcf_proto *tp,
2189 			      struct tcf_block *block, struct Qdisc *q,
2190 			      u32 parent, void *fh, bool *last, bool rtnl_held,
2191 			      struct netlink_ext_ack *extack)
2192 {
2193 	struct sk_buff *skb;
2194 	u32 portid = oskb ? NETLINK_CB(oskb).portid : 0;
2195 	int err;
2196 
2197 	if (!rtnl_notify_needed(net, n->nlmsg_flags, RTNLGRP_TC))
2198 		return tp->ops->delete(tp, fh, last, rtnl_held, extack);
2199 
2200 	skb = tfilter_notify_prep(net, oskb, n, tp, block, q, parent, fh,
2201 				  RTM_DELTFILTER, portid, rtnl_held, extack);
2202 	if (IS_ERR(skb)) {
2203 		NL_SET_ERR_MSG(extack, "Failed to build del event notification");
2204 		return PTR_ERR(skb);
2205 	}
2206 
2207 	err = tp->ops->delete(tp, fh, last, rtnl_held, extack);
2208 	if (err) {
2209 		kfree_skb(skb);
2210 		return err;
2211 	}
2212 
2213 	err = rtnetlink_send(skb, net, portid, RTNLGRP_TC,
2214 			     n->nlmsg_flags & NLM_F_ECHO);
2215 	if (err < 0)
2216 		NL_SET_ERR_MSG(extack, "Failed to send filter delete notification");
2217 
2218 	return err;
2219 }
2220 
2221 static void tfilter_notify_chain(struct net *net, struct sk_buff *oskb,
2222 				 struct tcf_block *block, struct Qdisc *q,
2223 				 u32 parent, struct nlmsghdr *n,
2224 				 struct tcf_chain *chain, int event,
2225 				 struct netlink_ext_ack *extack)
2226 {
2227 	struct tcf_proto *tp;
2228 
2229 	for (tp = tcf_get_next_proto(chain, NULL);
2230 	     tp; tp = tcf_get_next_proto(chain, tp))
2231 		tfilter_notify(net, oskb, n, tp, block, q, parent, NULL,
2232 			       event, false, true, extack);
2233 }
2234 
2235 static void tfilter_put(struct tcf_proto *tp, void *fh)
2236 {
2237 	if (tp->ops->put && fh)
2238 		tp->ops->put(tp, fh);
2239 }
2240 
2241 static bool is_qdisc_ingress(__u32 classid)
2242 {
2243 	return (TC_H_MIN(classid) == TC_H_MIN(TC_H_MIN_INGRESS));
2244 }
2245 
2246 static bool is_ingress_or_clsact(struct tcf_block *block, struct Qdisc *q)
2247 {
2248 	return tcf_block_shared(block) || (q && !!(q->flags & TCQ_F_INGRESS));
2249 }
2250 
2251 static int tc_new_tfilter(struct sk_buff *skb, struct nlmsghdr *n,
2252 			  struct netlink_ext_ack *extack)
2253 {
2254 	struct net *net = sock_net(skb->sk);
2255 	struct nlattr *tca[TCA_MAX + 1];
2256 	char name[IFNAMSIZ];
2257 	struct tcmsg *t;
2258 	u32 protocol;
2259 	u32 prio;
2260 	bool prio_allocate;
2261 	u32 parent;
2262 	u32 chain_index;
2263 	struct Qdisc *q;
2264 	struct tcf_chain_info chain_info;
2265 	struct tcf_chain *chain;
2266 	struct tcf_block *block;
2267 	struct tcf_proto *tp;
2268 	unsigned long cl;
2269 	void *fh;
2270 	int err;
2271 	int tp_created;
2272 	bool rtnl_held = false;
2273 	u32 flags;
2274 
2275 replay:
2276 	tp_created = 0;
2277 
2278 	err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,
2279 				     rtm_tca_policy, extack);
2280 	if (err < 0)
2281 		return err;
2282 
2283 	t = nlmsg_data(n);
2284 	protocol = TC_H_MIN(t->tcm_info);
2285 	prio = TC_H_MAJ(t->tcm_info);
2286 	prio_allocate = false;
2287 	parent = t->tcm_parent;
2288 	tp = NULL;
2289 	cl = 0;
2290 	block = NULL;
2291 	q = NULL;
2292 	chain = NULL;
2293 	flags = 0;
2294 
2295 	if (prio == 0) {
2296 		/* If no priority is provided by the user,
2297 		 * we allocate one.
2298 		 */
2299 		if (n->nlmsg_flags & NLM_F_CREATE) {
2300 			prio = TC_H_MAKE(0x80000000U, 0U);
2301 			prio_allocate = true;
2302 		} else {
2303 			NL_SET_ERR_MSG(extack, "Invalid filter command with priority of zero");
2304 			return -ENOENT;
2305 		}
2306 	}
2307 
2308 	/* Find head of filter chain. */
2309 
2310 	err = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack);
2311 	if (err)
2312 		return err;
2313 
2314 	if (tcf_proto_check_kind(tca[TCA_KIND], name)) {
2315 		NL_SET_ERR_MSG(extack, "Specified TC filter name too long");
2316 		err = -EINVAL;
2317 		goto errout;
2318 	}
2319 
2320 	/* Take rtnl mutex if rtnl_held was set to true on previous iteration,
2321 	 * block is shared (no qdisc found), qdisc is not unlocked, classifier
2322 	 * type is not specified, classifier is not unlocked.
2323 	 */
2324 	if (rtnl_held ||
2325 	    (q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) ||
2326 	    !tcf_proto_is_unlocked(name)) {
2327 		rtnl_held = true;
2328 		rtnl_lock();
2329 	}
2330 
2331 	err = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack);
2332 	if (err)
2333 		goto errout;
2334 
2335 	block = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index,
2336 				 extack);
2337 	if (IS_ERR(block)) {
2338 		err = PTR_ERR(block);
2339 		goto errout;
2340 	}
2341 	block->classid = parent;
2342 
2343 	chain_index = nla_get_u32_default(tca[TCA_CHAIN], 0);
2344 	if (chain_index > TC_ACT_EXT_VAL_MASK) {
2345 		NL_SET_ERR_MSG(extack, "Specified chain index exceeds upper limit");
2346 		err = -EINVAL;
2347 		goto errout;
2348 	}
2349 	chain = tcf_chain_get(block, chain_index, true);
2350 	if (!chain) {
2351 		NL_SET_ERR_MSG(extack, "Cannot create specified filter chain");
2352 		err = -ENOMEM;
2353 		goto errout;
2354 	}
2355 
2356 	mutex_lock(&chain->filter_chain_lock);
2357 	tp = tcf_chain_tp_find(chain, &chain_info, protocol,
2358 			       prio, prio_allocate, extack);
2359 	if (IS_ERR(tp)) {
2360 		err = PTR_ERR(tp);
2361 		goto errout_locked;
2362 	}
2363 
2364 	if (tp == NULL) {
2365 		struct tcf_proto *tp_new = NULL;
2366 
2367 		if (chain->flushing) {
2368 			err = -EAGAIN;
2369 			goto errout_locked;
2370 		}
2371 
2372 		/* Proto-tcf does not exist, create new one */
2373 
2374 		if (tca[TCA_KIND] == NULL || !protocol) {
2375 			NL_SET_ERR_MSG(extack, "Filter kind and protocol must be specified");
2376 			err = -EINVAL;
2377 			goto errout_locked;
2378 		}
2379 
2380 		if (!(n->nlmsg_flags & NLM_F_CREATE)) {
2381 			NL_SET_ERR_MSG(extack, "Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter");
2382 			err = -ENOENT;
2383 			goto errout_locked;
2384 		}
2385 
2386 		if (prio_allocate)
2387 			prio = tcf_auto_prio(tcf_chain_tp_prev(chain,
2388 							       &chain_info));
2389 
2390 		mutex_unlock(&chain->filter_chain_lock);
2391 		tp_new = tcf_proto_create(name, protocol, prio, chain,
2392 					  rtnl_held, extack);
2393 		if (IS_ERR(tp_new)) {
2394 			err = PTR_ERR(tp_new);
2395 			goto errout_tp;
2396 		}
2397 
2398 		tp_created = 1;
2399 		tp = tcf_chain_tp_insert_unique(chain, tp_new, protocol, prio,
2400 						rtnl_held);
2401 		if (IS_ERR(tp)) {
2402 			err = PTR_ERR(tp);
2403 			goto errout_tp;
2404 		}
2405 	} else {
2406 		mutex_unlock(&chain->filter_chain_lock);
2407 	}
2408 
2409 	if (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) {
2410 		NL_SET_ERR_MSG(extack, "Specified filter kind does not match existing one");
2411 		err = -EINVAL;
2412 		goto errout;
2413 	}
2414 
2415 	fh = tp->ops->get(tp, t->tcm_handle);
2416 
2417 	if (!fh) {
2418 		if (!(n->nlmsg_flags & NLM_F_CREATE)) {
2419 			NL_SET_ERR_MSG(extack, "Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter");
2420 			err = -ENOENT;
2421 			goto errout;
2422 		}
2423 	} else if (n->nlmsg_flags & NLM_F_EXCL) {
2424 		tfilter_put(tp, fh);
2425 		NL_SET_ERR_MSG(extack, "Filter already exists");
2426 		err = -EEXIST;
2427 		goto errout;
2428 	}
2429 
2430 	if (chain->tmplt_ops && chain->tmplt_ops != tp->ops) {
2431 		tfilter_put(tp, fh);
2432 		NL_SET_ERR_MSG(extack, "Chain template is set to a different filter kind");
2433 		err = -EINVAL;
2434 		goto errout;
2435 	}
2436 
2437 	if (!(n->nlmsg_flags & NLM_F_CREATE))
2438 		flags |= TCA_ACT_FLAGS_REPLACE;
2439 	if (!rtnl_held)
2440 		flags |= TCA_ACT_FLAGS_NO_RTNL;
2441 	if (is_qdisc_ingress(parent))
2442 		flags |= TCA_ACT_FLAGS_AT_INGRESS;
2443 	if (is_ingress_or_clsact(block, q))
2444 		flags |= TCA_ACT_FLAGS_AT_INGRESS_OR_CLSACT;
2445 	err = tp->ops->change(net, skb, tp, cl, t->tcm_handle, tca, &fh,
2446 			      flags, extack);
2447 	if (err == 0) {
2448 		tfilter_notify(net, skb, n, tp, block, q, parent, fh,
2449 			       RTM_NEWTFILTER, false, rtnl_held, extack);
2450 		tfilter_put(tp, fh);
2451 		tcf_proto_count_usesw(tp, true);
2452 		/* q pointer is NULL for shared blocks */
2453 		if (q)
2454 			q->flags &= ~TCQ_F_CAN_BYPASS;
2455 	}
2456 
2457 errout:
2458 	if (err && tp_created)
2459 		tcf_chain_tp_delete_empty(chain, tp, rtnl_held, NULL);
2460 errout_tp:
2461 	if (chain) {
2462 		if (tp && !IS_ERR(tp))
2463 			tcf_proto_put(tp, rtnl_held, NULL);
2464 		if (!tp_created)
2465 			tcf_chain_put(chain);
2466 	}
2467 	tcf_block_release(q, block, rtnl_held);
2468 
2469 	if (rtnl_held)
2470 		rtnl_unlock();
2471 
2472 	if (err == -EAGAIN) {
2473 		/* Take rtnl lock in case EAGAIN is caused by concurrent flush
2474 		 * of target chain.
2475 		 */
2476 		rtnl_held = true;
2477 		/* Replay the request. */
2478 		goto replay;
2479 	}
2480 	return err;
2481 
2482 errout_locked:
2483 	mutex_unlock(&chain->filter_chain_lock);
2484 	goto errout;
2485 }
2486 
2487 static int tc_del_tfilter(struct sk_buff *skb, struct nlmsghdr *n,
2488 			  struct netlink_ext_ack *extack)
2489 {
2490 	struct net *net = sock_net(skb->sk);
2491 	struct nlattr *tca[TCA_MAX + 1];
2492 	char name[IFNAMSIZ];
2493 	struct tcmsg *t;
2494 	u32 protocol;
2495 	u32 prio;
2496 	u32 parent;
2497 	u32 chain_index;
2498 	struct Qdisc *q = NULL;
2499 	struct tcf_chain_info chain_info;
2500 	struct tcf_chain *chain = NULL;
2501 	struct tcf_block *block = NULL;
2502 	struct tcf_proto *tp = NULL;
2503 	unsigned long cl = 0;
2504 	void *fh = NULL;
2505 	int err;
2506 	bool rtnl_held = false;
2507 
2508 	err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,
2509 				     rtm_tca_policy, extack);
2510 	if (err < 0)
2511 		return err;
2512 
2513 	t = nlmsg_data(n);
2514 	protocol = TC_H_MIN(t->tcm_info);
2515 	prio = TC_H_MAJ(t->tcm_info);
2516 	parent = t->tcm_parent;
2517 
2518 	if (prio == 0 && (protocol || t->tcm_handle || tca[TCA_KIND])) {
2519 		NL_SET_ERR_MSG(extack, "Cannot flush filters with protocol, handle or kind set");
2520 		return -ENOENT;
2521 	}
2522 
2523 	/* Find head of filter chain. */
2524 
2525 	err = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack);
2526 	if (err)
2527 		return err;
2528 
2529 	if (tcf_proto_check_kind(tca[TCA_KIND], name)) {
2530 		NL_SET_ERR_MSG(extack, "Specified TC filter name too long");
2531 		err = -EINVAL;
2532 		goto errout;
2533 	}
2534 	/* Take rtnl mutex if flushing whole chain, block is shared (no qdisc
2535 	 * found), qdisc is not unlocked, classifier type is not specified,
2536 	 * classifier is not unlocked.
2537 	 */
2538 	if (!prio ||
2539 	    (q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) ||
2540 	    !tcf_proto_is_unlocked(name)) {
2541 		rtnl_held = true;
2542 		rtnl_lock();
2543 	}
2544 
2545 	err = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack);
2546 	if (err)
2547 		goto errout;
2548 
2549 	block = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index,
2550 				 extack);
2551 	if (IS_ERR(block)) {
2552 		err = PTR_ERR(block);
2553 		goto errout;
2554 	}
2555 
2556 	chain_index = nla_get_u32_default(tca[TCA_CHAIN], 0);
2557 	if (chain_index > TC_ACT_EXT_VAL_MASK) {
2558 		NL_SET_ERR_MSG(extack, "Specified chain index exceeds upper limit");
2559 		err = -EINVAL;
2560 		goto errout;
2561 	}
2562 	chain = tcf_chain_get(block, chain_index, false);
2563 	if (!chain) {
2564 		/* User requested flush on non-existent chain. Nothing to do,
2565 		 * so just return success.
2566 		 */
2567 		if (prio == 0) {
2568 			err = 0;
2569 			goto errout;
2570 		}
2571 		NL_SET_ERR_MSG(extack, "Cannot find specified filter chain");
2572 		err = -ENOENT;
2573 		goto errout;
2574 	}
2575 
2576 	if (prio == 0) {
2577 		tfilter_notify_chain(net, skb, block, q, parent, n,
2578 				     chain, RTM_DELTFILTER, extack);
2579 		tcf_chain_flush(chain, rtnl_held);
2580 		err = 0;
2581 		goto errout;
2582 	}
2583 
2584 	mutex_lock(&chain->filter_chain_lock);
2585 	tp = tcf_chain_tp_find(chain, &chain_info, protocol,
2586 			       prio, false, extack);
2587 	if (!tp) {
2588 		err = -ENOENT;
2589 		NL_SET_ERR_MSG(extack, "Filter with specified priority/protocol not found");
2590 		goto errout_locked;
2591 	} else if (IS_ERR(tp)) {
2592 		err = PTR_ERR(tp);
2593 		goto errout_locked;
2594 	} else if (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) {
2595 		NL_SET_ERR_MSG(extack, "Specified filter kind does not match existing one");
2596 		err = -EINVAL;
2597 		goto errout_locked;
2598 	} else if (t->tcm_handle == 0) {
2599 		tcf_proto_signal_destroying(chain, tp);
2600 		tcf_chain_tp_remove(chain, &chain_info, tp);
2601 		mutex_unlock(&chain->filter_chain_lock);
2602 
2603 		tcf_proto_put(tp, rtnl_held, NULL);
2604 		tfilter_notify(net, skb, n, tp, block, q, parent, fh,
2605 			       RTM_DELTFILTER, false, rtnl_held, extack);
2606 		err = 0;
2607 		goto errout;
2608 	}
2609 	mutex_unlock(&chain->filter_chain_lock);
2610 
2611 	fh = tp->ops->get(tp, t->tcm_handle);
2612 
2613 	if (!fh) {
2614 		NL_SET_ERR_MSG(extack, "Specified filter handle not found");
2615 		err = -ENOENT;
2616 	} else {
2617 		bool last;
2618 
2619 		err = tfilter_del_notify(net, skb, n, tp, block, q, parent, fh,
2620 					 &last, rtnl_held, extack);
2621 
2622 		if (err)
2623 			goto errout;
2624 		if (last)
2625 			tcf_chain_tp_delete_empty(chain, tp, rtnl_held, extack);
2626 	}
2627 
2628 errout:
2629 	if (chain) {
2630 		if (tp && !IS_ERR(tp))
2631 			tcf_proto_put(tp, rtnl_held, NULL);
2632 		tcf_chain_put(chain);
2633 	}
2634 	tcf_block_release(q, block, rtnl_held);
2635 
2636 	if (rtnl_held)
2637 		rtnl_unlock();
2638 
2639 	return err;
2640 
2641 errout_locked:
2642 	mutex_unlock(&chain->filter_chain_lock);
2643 	goto errout;
2644 }
2645 
2646 static int tc_get_tfilter(struct sk_buff *skb, struct nlmsghdr *n,
2647 			  struct netlink_ext_ack *extack)
2648 {
2649 	struct net *net = sock_net(skb->sk);
2650 	struct nlattr *tca[TCA_MAX + 1];
2651 	char name[IFNAMSIZ];
2652 	struct tcmsg *t;
2653 	u32 protocol;
2654 	u32 prio;
2655 	u32 parent;
2656 	u32 chain_index;
2657 	struct Qdisc *q = NULL;
2658 	struct tcf_chain_info chain_info;
2659 	struct tcf_chain *chain = NULL;
2660 	struct tcf_block *block = NULL;
2661 	struct tcf_proto *tp = NULL;
2662 	unsigned long cl = 0;
2663 	void *fh = NULL;
2664 	int err;
2665 	bool rtnl_held = false;
2666 
2667 	err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,
2668 				     rtm_tca_policy, extack);
2669 	if (err < 0)
2670 		return err;
2671 
2672 	t = nlmsg_data(n);
2673 	protocol = TC_H_MIN(t->tcm_info);
2674 	prio = TC_H_MAJ(t->tcm_info);
2675 	parent = t->tcm_parent;
2676 
2677 	if (prio == 0) {
2678 		NL_SET_ERR_MSG(extack, "Invalid filter command with priority of zero");
2679 		return -ENOENT;
2680 	}
2681 
2682 	/* Find head of filter chain. */
2683 
2684 	err = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack);
2685 	if (err)
2686 		return err;
2687 
2688 	if (tcf_proto_check_kind(tca[TCA_KIND], name)) {
2689 		NL_SET_ERR_MSG(extack, "Specified TC filter name too long");
2690 		err = -EINVAL;
2691 		goto errout;
2692 	}
2693 	/* Take rtnl mutex if block is shared (no qdisc found), qdisc is not
2694 	 * unlocked, classifier type is not specified, classifier is not
2695 	 * unlocked.
2696 	 */
2697 	if ((q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) ||
2698 	    !tcf_proto_is_unlocked(name)) {
2699 		rtnl_held = true;
2700 		rtnl_lock();
2701 	}
2702 
2703 	err = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack);
2704 	if (err)
2705 		goto errout;
2706 
2707 	block = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index,
2708 				 extack);
2709 	if (IS_ERR(block)) {
2710 		err = PTR_ERR(block);
2711 		goto errout;
2712 	}
2713 
2714 	chain_index = nla_get_u32_default(tca[TCA_CHAIN], 0);
2715 	if (chain_index > TC_ACT_EXT_VAL_MASK) {
2716 		NL_SET_ERR_MSG(extack, "Specified chain index exceeds upper limit");
2717 		err = -EINVAL;
2718 		goto errout;
2719 	}
2720 	chain = tcf_chain_get(block, chain_index, false);
2721 	if (!chain) {
2722 		NL_SET_ERR_MSG(extack, "Cannot find specified filter chain");
2723 		err = -EINVAL;
2724 		goto errout;
2725 	}
2726 
2727 	mutex_lock(&chain->filter_chain_lock);
2728 	tp = tcf_chain_tp_find(chain, &chain_info, protocol,
2729 			       prio, false, extack);
2730 	mutex_unlock(&chain->filter_chain_lock);
2731 	if (!tp) {
2732 		err = -ENOENT;
2733 		NL_SET_ERR_MSG(extack, "Filter with specified priority/protocol not found");
2734 		goto errout;
2735 	} else if (IS_ERR(tp)) {
2736 		err = PTR_ERR(tp);
2737 		goto errout;
2738 	} else if (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) {
2739 		NL_SET_ERR_MSG(extack, "Specified filter kind does not match existing one");
2740 		err = -EINVAL;
2741 		goto errout;
2742 	}
2743 
2744 	fh = tp->ops->get(tp, t->tcm_handle);
2745 
2746 	if (!fh) {
2747 		NL_SET_ERR_MSG(extack, "Specified filter handle not found");
2748 		err = -ENOENT;
2749 	} else {
2750 		err = tfilter_notify(net, skb, n, tp, block, q, parent,
2751 				     fh, RTM_NEWTFILTER, true, rtnl_held, NULL);
2752 		if (err < 0)
2753 			NL_SET_ERR_MSG(extack, "Failed to send filter notify message");
2754 	}
2755 
2756 	tfilter_put(tp, fh);
2757 errout:
2758 	if (chain) {
2759 		if (tp && !IS_ERR(tp))
2760 			tcf_proto_put(tp, rtnl_held, NULL);
2761 		tcf_chain_put(chain);
2762 	}
2763 	tcf_block_release(q, block, rtnl_held);
2764 
2765 	if (rtnl_held)
2766 		rtnl_unlock();
2767 
2768 	return err;
2769 }
2770 
2771 struct tcf_dump_args {
2772 	struct tcf_walker w;
2773 	struct sk_buff *skb;
2774 	struct netlink_callback *cb;
2775 	struct tcf_block *block;
2776 	struct Qdisc *q;
2777 	u32 parent;
2778 	bool terse_dump;
2779 };
2780 
2781 static int tcf_node_dump(struct tcf_proto *tp, void *n, struct tcf_walker *arg)
2782 {
2783 	struct tcf_dump_args *a = (void *)arg;
2784 	struct net *net = sock_net(a->skb->sk);
2785 
2786 	return tcf_fill_node(net, a->skb, tp, a->block, a->q, a->parent,
2787 			     n, NETLINK_CB(a->cb->skb).portid,
2788 			     a->cb->nlh->nlmsg_seq, NLM_F_MULTI,
2789 			     RTM_NEWTFILTER, a->terse_dump, true, NULL);
2790 }
2791 
2792 static bool tcf_chain_dump(struct tcf_chain *chain, struct Qdisc *q, u32 parent,
2793 			   struct sk_buff *skb, struct netlink_callback *cb,
2794 			   long index_start, long *p_index, bool terse)
2795 {
2796 	struct net *net = sock_net(skb->sk);
2797 	struct tcf_block *block = chain->block;
2798 	struct tcmsg *tcm = nlmsg_data(cb->nlh);
2799 	struct tcf_proto *tp, *tp_prev;
2800 	struct tcf_dump_args arg;
2801 
2802 	for (tp = __tcf_get_next_proto(chain, NULL);
2803 	     tp;
2804 	     tp_prev = tp,
2805 		     tp = __tcf_get_next_proto(chain, tp),
2806 		     tcf_proto_put(tp_prev, true, NULL),
2807 		     (*p_index)++) {
2808 		if (*p_index < index_start)
2809 			continue;
2810 		if (TC_H_MAJ(tcm->tcm_info) &&
2811 		    TC_H_MAJ(tcm->tcm_info) != tp->prio)
2812 			continue;
2813 		if (TC_H_MIN(tcm->tcm_info) &&
2814 		    TC_H_MIN(tcm->tcm_info) != tp->protocol)
2815 			continue;
2816 		if (*p_index > index_start)
2817 			memset(&cb->args[1], 0,
2818 			       sizeof(cb->args) - sizeof(cb->args[0]));
2819 		if (cb->args[1] == 0) {
2820 			if (tcf_fill_node(net, skb, tp, block, q, parent, NULL,
2821 					  NETLINK_CB(cb->skb).portid,
2822 					  cb->nlh->nlmsg_seq, NLM_F_MULTI,
2823 					  RTM_NEWTFILTER, false, true, NULL) <= 0)
2824 				goto errout;
2825 			cb->args[1] = 1;
2826 		}
2827 		if (!tp->ops->walk)
2828 			continue;
2829 		arg.w.fn = tcf_node_dump;
2830 		arg.skb = skb;
2831 		arg.cb = cb;
2832 		arg.block = block;
2833 		arg.q = q;
2834 		arg.parent = parent;
2835 		arg.w.stop = 0;
2836 		arg.w.skip = cb->args[1] - 1;
2837 		arg.w.count = 0;
2838 		arg.w.cookie = cb->args[2];
2839 		arg.terse_dump = terse;
2840 		tp->ops->walk(tp, &arg.w, true);
2841 		cb->args[2] = arg.w.cookie;
2842 		cb->args[1] = arg.w.count + 1;
2843 		if (arg.w.stop)
2844 			goto errout;
2845 	}
2846 	return true;
2847 
2848 errout:
2849 	tcf_proto_put(tp, true, NULL);
2850 	return false;
2851 }
2852 
2853 static const struct nla_policy tcf_tfilter_dump_policy[TCA_MAX + 1] = {
2854 	[TCA_CHAIN]      = { .type = NLA_U32 },
2855 	[TCA_DUMP_FLAGS] = NLA_POLICY_BITFIELD32(TCA_DUMP_FLAGS_TERSE),
2856 };
2857 
2858 /* called with RTNL */
2859 static int tc_dump_tfilter(struct sk_buff *skb, struct netlink_callback *cb)
2860 {
2861 	struct tcf_chain *chain, *chain_prev;
2862 	struct net *net = sock_net(skb->sk);
2863 	struct nlattr *tca[TCA_MAX + 1];
2864 	struct Qdisc *q = NULL;
2865 	struct tcf_block *block;
2866 	struct tcmsg *tcm = nlmsg_data(cb->nlh);
2867 	bool terse_dump = false;
2868 	long index_start;
2869 	long index;
2870 	u32 parent;
2871 	int err;
2872 
2873 	if (nlmsg_len(cb->nlh) < sizeof(*tcm))
2874 		return skb->len;
2875 
2876 	err = nlmsg_parse_deprecated(cb->nlh, sizeof(*tcm), tca, TCA_MAX,
2877 				     tcf_tfilter_dump_policy, cb->extack);
2878 	if (err)
2879 		return err;
2880 
2881 	if (tca[TCA_DUMP_FLAGS]) {
2882 		struct nla_bitfield32 flags =
2883 			nla_get_bitfield32(tca[TCA_DUMP_FLAGS]);
2884 
2885 		terse_dump = flags.value & TCA_DUMP_FLAGS_TERSE;
2886 	}
2887 
2888 	if (tcm->tcm_ifindex == TCM_IFINDEX_MAGIC_BLOCK) {
2889 		block = tcf_block_refcnt_get(net, tcm->tcm_block_index);
2890 		if (!block)
2891 			goto out;
2892 		/* If we work with block index, q is NULL and parent value
2893 		 * will never be used in the following code. The check
2894 		 * in tcf_fill_node prevents it. However, compiler does not
2895 		 * see that far, so set parent to zero to silence the warning
2896 		 * about parent being uninitialized.
2897 		 */
2898 		parent = 0;
2899 	} else {
2900 		const struct Qdisc_class_ops *cops;
2901 		struct net_device *dev;
2902 		unsigned long cl = 0;
2903 
2904 		dev = __dev_get_by_index(net, tcm->tcm_ifindex);
2905 		if (!dev)
2906 			return skb->len;
2907 
2908 		parent = tcm->tcm_parent;
2909 		if (!parent)
2910 			q = rtnl_dereference(dev->qdisc);
2911 		else
2912 			q = qdisc_lookup(dev, TC_H_MAJ(tcm->tcm_parent));
2913 		if (!q)
2914 			goto out;
2915 		cops = q->ops->cl_ops;
2916 		if (!cops)
2917 			goto out;
2918 		if (!cops->tcf_block)
2919 			goto out;
2920 		if (TC_H_MIN(tcm->tcm_parent)) {
2921 			cl = cops->find(q, tcm->tcm_parent);
2922 			if (cl == 0)
2923 				goto out;
2924 		}
2925 		block = cops->tcf_block(q, cl, NULL);
2926 		if (!block)
2927 			goto out;
2928 		parent = block->classid;
2929 		if (tcf_block_shared(block))
2930 			q = NULL;
2931 	}
2932 
2933 	index_start = cb->args[0];
2934 	index = 0;
2935 
2936 	for (chain = __tcf_get_next_chain(block, NULL);
2937 	     chain;
2938 	     chain_prev = chain,
2939 		     chain = __tcf_get_next_chain(block, chain),
2940 		     tcf_chain_put(chain_prev)) {
2941 		if (tca[TCA_CHAIN] &&
2942 		    nla_get_u32(tca[TCA_CHAIN]) != chain->index)
2943 			continue;
2944 		if (!tcf_chain_dump(chain, q, parent, skb, cb,
2945 				    index_start, &index, terse_dump)) {
2946 			tcf_chain_put(chain);
2947 			err = -EMSGSIZE;
2948 			break;
2949 		}
2950 	}
2951 
2952 	if (tcm->tcm_ifindex == TCM_IFINDEX_MAGIC_BLOCK)
2953 		tcf_block_refcnt_put(block, true);
2954 	cb->args[0] = index;
2955 
2956 out:
2957 	/* If we did no progress, the error (EMSGSIZE) is real */
2958 	if (skb->len == 0 && err)
2959 		return err;
2960 	return skb->len;
2961 }
2962 
2963 static int tc_chain_fill_node(const struct tcf_proto_ops *tmplt_ops,
2964 			      void *tmplt_priv, u32 chain_index,
2965 			      struct net *net, struct sk_buff *skb,
2966 			      struct tcf_block *block,
2967 			      u32 portid, u32 seq, u16 flags, int event,
2968 			      struct netlink_ext_ack *extack)
2969 {
2970 	unsigned char *b = skb_tail_pointer(skb);
2971 	const struct tcf_proto_ops *ops;
2972 	struct nlmsghdr *nlh;
2973 	struct tcmsg *tcm;
2974 	void *priv;
2975 
2976 	ops = tmplt_ops;
2977 	priv = tmplt_priv;
2978 
2979 	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*tcm), flags);
2980 	if (!nlh)
2981 		goto out_nlmsg_trim;
2982 	tcm = nlmsg_data(nlh);
2983 	tcm->tcm_family = AF_UNSPEC;
2984 	tcm->tcm__pad1 = 0;
2985 	tcm->tcm__pad2 = 0;
2986 	tcm->tcm_handle = 0;
2987 	tcm->tcm_info = 0;
2988 	if (block->q) {
2989 		tcm->tcm_ifindex = qdisc_dev(block->q)->ifindex;
2990 		tcm->tcm_parent = block->q->handle;
2991 	} else {
2992 		tcm->tcm_ifindex = TCM_IFINDEX_MAGIC_BLOCK;
2993 		tcm->tcm_block_index = block->index;
2994 	}
2995 
2996 	if (nla_put_u32(skb, TCA_CHAIN, chain_index))
2997 		goto nla_put_failure;
2998 
2999 	if (ops) {
3000 		if (nla_put_string(skb, TCA_KIND, ops->kind))
3001 			goto nla_put_failure;
3002 		if (ops->tmplt_dump(skb, net, priv) < 0)
3003 			goto nla_put_failure;
3004 	}
3005 
3006 	if (extack && extack->_msg &&
3007 	    nla_put_string(skb, TCA_EXT_WARN_MSG, extack->_msg))
3008 		goto out_nlmsg_trim;
3009 
3010 	nlh->nlmsg_len = skb_tail_pointer(skb) - b;
3011 
3012 	return skb->len;
3013 
3014 out_nlmsg_trim:
3015 nla_put_failure:
3016 	nlmsg_trim(skb, b);
3017 	return -EMSGSIZE;
3018 }
3019 
3020 static int tc_chain_notify(struct tcf_chain *chain, struct sk_buff *oskb,
3021 			   u32 seq, u16 flags, int event, bool unicast,
3022 			   struct netlink_ext_ack *extack)
3023 {
3024 	u32 portid = oskb ? NETLINK_CB(oskb).portid : 0;
3025 	struct tcf_block *block = chain->block;
3026 	struct net *net = block->net;
3027 	struct sk_buff *skb;
3028 	int err = 0;
3029 
3030 	if (!unicast && !rtnl_notify_needed(net, flags, RTNLGRP_TC))
3031 		return 0;
3032 
3033 	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
3034 	if (!skb)
3035 		return -ENOBUFS;
3036 
3037 	if (tc_chain_fill_node(chain->tmplt_ops, chain->tmplt_priv,
3038 			       chain->index, net, skb, block, portid,
3039 			       seq, flags, event, extack) <= 0) {
3040 		kfree_skb(skb);
3041 		return -EINVAL;
3042 	}
3043 
3044 	if (unicast)
3045 		err = rtnl_unicast(skb, net, portid);
3046 	else
3047 		err = rtnetlink_send(skb, net, portid, RTNLGRP_TC,
3048 				     flags & NLM_F_ECHO);
3049 
3050 	return err;
3051 }
3052 
3053 static int tc_chain_notify_delete(const struct tcf_proto_ops *tmplt_ops,
3054 				  void *tmplt_priv, u32 chain_index,
3055 				  struct tcf_block *block, struct sk_buff *oskb,
3056 				  u32 seq, u16 flags)
3057 {
3058 	u32 portid = oskb ? NETLINK_CB(oskb).portid : 0;
3059 	struct net *net = block->net;
3060 	struct sk_buff *skb;
3061 
3062 	if (!rtnl_notify_needed(net, flags, RTNLGRP_TC))
3063 		return 0;
3064 
3065 	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
3066 	if (!skb)
3067 		return -ENOBUFS;
3068 
3069 	if (tc_chain_fill_node(tmplt_ops, tmplt_priv, chain_index, net, skb,
3070 			       block, portid, seq, flags, RTM_DELCHAIN, NULL) <= 0) {
3071 		kfree_skb(skb);
3072 		return -EINVAL;
3073 	}
3074 
3075 	return rtnetlink_send(skb, net, portid, RTNLGRP_TC, flags & NLM_F_ECHO);
3076 }
3077 
3078 static int tc_chain_tmplt_add(struct tcf_chain *chain, struct net *net,
3079 			      struct nlattr **tca,
3080 			      struct netlink_ext_ack *extack)
3081 {
3082 	const struct tcf_proto_ops *ops;
3083 	char name[IFNAMSIZ];
3084 	void *tmplt_priv;
3085 
3086 	/* If kind is not set, user did not specify template. */
3087 	if (!tca[TCA_KIND])
3088 		return 0;
3089 
3090 	if (tcf_proto_check_kind(tca[TCA_KIND], name)) {
3091 		NL_SET_ERR_MSG(extack, "Specified TC chain template name too long");
3092 		return -EINVAL;
3093 	}
3094 
3095 	ops = tcf_proto_lookup_ops(name, true, extack);
3096 	if (IS_ERR(ops))
3097 		return PTR_ERR(ops);
3098 	if (!ops->tmplt_create || !ops->tmplt_destroy || !ops->tmplt_dump ||
3099 	    !ops->tmplt_reoffload) {
3100 		NL_SET_ERR_MSG(extack, "Chain templates are not supported with specified classifier");
3101 		module_put(ops->owner);
3102 		return -EOPNOTSUPP;
3103 	}
3104 
3105 	tmplt_priv = ops->tmplt_create(net, chain, tca, extack);
3106 	if (IS_ERR(tmplt_priv)) {
3107 		module_put(ops->owner);
3108 		return PTR_ERR(tmplt_priv);
3109 	}
3110 	chain->tmplt_ops = ops;
3111 	chain->tmplt_priv = tmplt_priv;
3112 	return 0;
3113 }
3114 
3115 static void tc_chain_tmplt_del(const struct tcf_proto_ops *tmplt_ops,
3116 			       void *tmplt_priv)
3117 {
3118 	/* If template ops are set, no work to do for us. */
3119 	if (!tmplt_ops)
3120 		return;
3121 
3122 	tmplt_ops->tmplt_destroy(tmplt_priv);
3123 	module_put(tmplt_ops->owner);
3124 }
3125 
3126 /* Add/delete/get a chain */
3127 
3128 static int tc_ctl_chain(struct sk_buff *skb, struct nlmsghdr *n,
3129 			struct netlink_ext_ack *extack)
3130 {
3131 	struct net *net = sock_net(skb->sk);
3132 	struct nlattr *tca[TCA_MAX + 1];
3133 	struct tcmsg *t;
3134 	u32 parent;
3135 	u32 chain_index;
3136 	struct Qdisc *q;
3137 	struct tcf_chain *chain;
3138 	struct tcf_block *block;
3139 	unsigned long cl;
3140 	int err;
3141 
3142 replay:
3143 	q = NULL;
3144 	err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,
3145 				     rtm_tca_policy, extack);
3146 	if (err < 0)
3147 		return err;
3148 
3149 	t = nlmsg_data(n);
3150 	parent = t->tcm_parent;
3151 	cl = 0;
3152 
3153 	block = tcf_block_find(net, &q, &parent, &cl,
3154 			       t->tcm_ifindex, t->tcm_block_index, extack);
3155 	if (IS_ERR(block))
3156 		return PTR_ERR(block);
3157 
3158 	chain_index = nla_get_u32_default(tca[TCA_CHAIN], 0);
3159 	if (chain_index > TC_ACT_EXT_VAL_MASK) {
3160 		NL_SET_ERR_MSG(extack, "Specified chain index exceeds upper limit");
3161 		err = -EINVAL;
3162 		goto errout_block;
3163 	}
3164 
3165 	mutex_lock(&block->lock);
3166 	chain = tcf_chain_lookup(block, chain_index);
3167 	if (n->nlmsg_type == RTM_NEWCHAIN) {
3168 		if (chain) {
3169 			if (tcf_chain_held_by_acts_only(chain)) {
3170 				/* The chain exists only because there is
3171 				 * some action referencing it.
3172 				 */
3173 				tcf_chain_hold(chain);
3174 			} else {
3175 				NL_SET_ERR_MSG(extack, "Filter chain already exists");
3176 				err = -EEXIST;
3177 				goto errout_block_locked;
3178 			}
3179 		} else {
3180 			if (!(n->nlmsg_flags & NLM_F_CREATE)) {
3181 				NL_SET_ERR_MSG(extack, "Need both RTM_NEWCHAIN and NLM_F_CREATE to create a new chain");
3182 				err = -ENOENT;
3183 				goto errout_block_locked;
3184 			}
3185 			chain = tcf_chain_create(block, chain_index);
3186 			if (!chain) {
3187 				NL_SET_ERR_MSG(extack, "Failed to create filter chain");
3188 				err = -ENOMEM;
3189 				goto errout_block_locked;
3190 			}
3191 		}
3192 	} else {
3193 		if (!chain || tcf_chain_held_by_acts_only(chain)) {
3194 			NL_SET_ERR_MSG(extack, "Cannot find specified filter chain");
3195 			err = -EINVAL;
3196 			goto errout_block_locked;
3197 		}
3198 		tcf_chain_hold(chain);
3199 	}
3200 
3201 	if (n->nlmsg_type == RTM_NEWCHAIN) {
3202 		/* Modifying chain requires holding parent block lock. In case
3203 		 * the chain was successfully added, take a reference to the
3204 		 * chain. This ensures that an empty chain does not disappear at
3205 		 * the end of this function.
3206 		 */
3207 		tcf_chain_hold(chain);
3208 		chain->explicitly_created = true;
3209 	}
3210 	mutex_unlock(&block->lock);
3211 
3212 	switch (n->nlmsg_type) {
3213 	case RTM_NEWCHAIN:
3214 		err = tc_chain_tmplt_add(chain, net, tca, extack);
3215 		if (err) {
3216 			tcf_chain_put_explicitly_created(chain);
3217 			goto errout;
3218 		}
3219 
3220 		tc_chain_notify(chain, NULL, 0, NLM_F_CREATE | NLM_F_EXCL,
3221 				RTM_NEWCHAIN, false, extack);
3222 		break;
3223 	case RTM_DELCHAIN:
3224 		tfilter_notify_chain(net, skb, block, q, parent, n,
3225 				     chain, RTM_DELTFILTER, extack);
3226 		/* Flush the chain first as the user requested chain removal. */
3227 		tcf_chain_flush(chain, true);
3228 		/* In case the chain was successfully deleted, put a reference
3229 		 * to the chain previously taken during addition.
3230 		 */
3231 		tcf_chain_put_explicitly_created(chain);
3232 		break;
3233 	case RTM_GETCHAIN:
3234 		err = tc_chain_notify(chain, skb, n->nlmsg_seq,
3235 				      n->nlmsg_flags, n->nlmsg_type, true, extack);
3236 		if (err < 0)
3237 			NL_SET_ERR_MSG(extack, "Failed to send chain notify message");
3238 		break;
3239 	default:
3240 		err = -EOPNOTSUPP;
3241 		NL_SET_ERR_MSG(extack, "Unsupported message type");
3242 		goto errout;
3243 	}
3244 
3245 errout:
3246 	tcf_chain_put(chain);
3247 errout_block:
3248 	tcf_block_release(q, block, true);
3249 	if (err == -EAGAIN)
3250 		/* Replay the request. */
3251 		goto replay;
3252 	return err;
3253 
3254 errout_block_locked:
3255 	mutex_unlock(&block->lock);
3256 	goto errout_block;
3257 }
3258 
3259 /* called with RTNL */
3260 static int tc_dump_chain(struct sk_buff *skb, struct netlink_callback *cb)
3261 {
3262 	struct net *net = sock_net(skb->sk);
3263 	struct nlattr *tca[TCA_MAX + 1];
3264 	struct Qdisc *q = NULL;
3265 	struct tcf_block *block;
3266 	struct tcmsg *tcm = nlmsg_data(cb->nlh);
3267 	struct tcf_chain *chain;
3268 	long index_start;
3269 	long index;
3270 	int err;
3271 
3272 	if (nlmsg_len(cb->nlh) < sizeof(*tcm))
3273 		return skb->len;
3274 
3275 	err = nlmsg_parse_deprecated(cb->nlh, sizeof(*tcm), tca, TCA_MAX,
3276 				     rtm_tca_policy, cb->extack);
3277 	if (err)
3278 		return err;
3279 
3280 	if (tcm->tcm_ifindex == TCM_IFINDEX_MAGIC_BLOCK) {
3281 		block = tcf_block_refcnt_get(net, tcm->tcm_block_index);
3282 		if (!block)
3283 			goto out;
3284 	} else {
3285 		const struct Qdisc_class_ops *cops;
3286 		struct net_device *dev;
3287 		unsigned long cl = 0;
3288 
3289 		dev = __dev_get_by_index(net, tcm->tcm_ifindex);
3290 		if (!dev)
3291 			return skb->len;
3292 
3293 		if (!tcm->tcm_parent)
3294 			q = rtnl_dereference(dev->qdisc);
3295 		else
3296 			q = qdisc_lookup(dev, TC_H_MAJ(tcm->tcm_parent));
3297 
3298 		if (!q)
3299 			goto out;
3300 		cops = q->ops->cl_ops;
3301 		if (!cops)
3302 			goto out;
3303 		if (!cops->tcf_block)
3304 			goto out;
3305 		if (TC_H_MIN(tcm->tcm_parent)) {
3306 			cl = cops->find(q, tcm->tcm_parent);
3307 			if (cl == 0)
3308 				goto out;
3309 		}
3310 		block = cops->tcf_block(q, cl, NULL);
3311 		if (!block)
3312 			goto out;
3313 		if (tcf_block_shared(block))
3314 			q = NULL;
3315 	}
3316 
3317 	index_start = cb->args[0];
3318 	index = 0;
3319 
3320 	mutex_lock(&block->lock);
3321 	list_for_each_entry(chain, &block->chain_list, list) {
3322 		if ((tca[TCA_CHAIN] &&
3323 		     nla_get_u32(tca[TCA_CHAIN]) != chain->index))
3324 			continue;
3325 		if (index < index_start) {
3326 			index++;
3327 			continue;
3328 		}
3329 		if (tcf_chain_held_by_acts_only(chain))
3330 			continue;
3331 		err = tc_chain_fill_node(chain->tmplt_ops, chain->tmplt_priv,
3332 					 chain->index, net, skb, block,
3333 					 NETLINK_CB(cb->skb).portid,
3334 					 cb->nlh->nlmsg_seq, NLM_F_MULTI,
3335 					 RTM_NEWCHAIN, NULL);
3336 		if (err <= 0)
3337 			break;
3338 		index++;
3339 	}
3340 	mutex_unlock(&block->lock);
3341 
3342 	if (tcm->tcm_ifindex == TCM_IFINDEX_MAGIC_BLOCK)
3343 		tcf_block_refcnt_put(block, true);
3344 	cb->args[0] = index;
3345 
3346 out:
3347 	/* If we did no progress, the error (EMSGSIZE) is real */
3348 	if (skb->len == 0 && err)
3349 		return err;
3350 	return skb->len;
3351 }
3352 
3353 int tcf_exts_init_ex(struct tcf_exts *exts, struct net *net, int action,
3354 		     int police, struct tcf_proto *tp, u32 handle,
3355 		     bool use_action_miss)
3356 {
3357 	int err = 0;
3358 
3359 #ifdef CONFIG_NET_CLS_ACT
3360 	exts->type = 0;
3361 	exts->nr_actions = 0;
3362 	exts->miss_cookie_node = NULL;
3363 	/* Note: we do not own yet a reference on net.
3364 	 * This reference might be taken later from tcf_exts_get_net().
3365 	 */
3366 	exts->net = net;
3367 	exts->actions = kzalloc_objs(struct tc_action *, TCA_ACT_MAX_PRIO);
3368 	if (!exts->actions)
3369 		return -ENOMEM;
3370 #endif
3371 
3372 	exts->action = action;
3373 	exts->police = police;
3374 
3375 	if (!use_action_miss)
3376 		return 0;
3377 
3378 	err = tcf_exts_miss_cookie_base_alloc(exts, tp, handle);
3379 	if (err)
3380 		goto err_miss_alloc;
3381 
3382 	return 0;
3383 
3384 err_miss_alloc:
3385 	tcf_exts_destroy(exts);
3386 #ifdef CONFIG_NET_CLS_ACT
3387 	exts->actions = NULL;
3388 #endif
3389 	return err;
3390 }
3391 EXPORT_SYMBOL(tcf_exts_init_ex);
3392 
3393 void tcf_exts_destroy(struct tcf_exts *exts)
3394 {
3395 	tcf_exts_miss_cookie_base_destroy(exts);
3396 
3397 #ifdef CONFIG_NET_CLS_ACT
3398 	if (exts->actions) {
3399 		tcf_action_destroy(exts->actions, TCA_ACT_UNBIND);
3400 		kfree(exts->actions);
3401 	}
3402 	exts->nr_actions = 0;
3403 #endif
3404 }
3405 EXPORT_SYMBOL(tcf_exts_destroy);
3406 
3407 int tcf_exts_validate_ex(struct net *net, struct tcf_proto *tp, struct nlattr **tb,
3408 			 struct nlattr *rate_tlv, struct tcf_exts *exts,
3409 			 u32 flags, u32 fl_flags, struct netlink_ext_ack *extack)
3410 {
3411 #ifdef CONFIG_NET_CLS_ACT
3412 	{
3413 		int init_res[TCA_ACT_MAX_PRIO] = {};
3414 		struct tc_action *act;
3415 		size_t attr_size = 0;
3416 
3417 		if (exts->police && tb[exts->police]) {
3418 			struct tc_action_ops *a_o;
3419 
3420 			flags |= TCA_ACT_FLAGS_POLICE | TCA_ACT_FLAGS_BIND;
3421 			a_o = tc_action_load_ops(tb[exts->police], flags,
3422 						 extack);
3423 			if (IS_ERR(a_o))
3424 				return PTR_ERR(a_o);
3425 			act = tcf_action_init_1(net, tp, tb[exts->police],
3426 						rate_tlv, a_o, init_res, flags,
3427 						extack);
3428 			module_put(a_o->owner);
3429 			if (IS_ERR(act))
3430 				return PTR_ERR(act);
3431 
3432 			act->type = exts->type = TCA_OLD_COMPAT;
3433 			exts->actions[0] = act;
3434 			exts->nr_actions = 1;
3435 			tcf_idr_insert_many(exts->actions, init_res);
3436 		} else if (exts->action && tb[exts->action]) {
3437 			int err;
3438 
3439 			flags |= TCA_ACT_FLAGS_BIND;
3440 			err = tcf_action_init(net, tp, tb[exts->action],
3441 					      rate_tlv, exts->actions, init_res,
3442 					      &attr_size, flags, fl_flags,
3443 					      extack);
3444 			if (err < 0)
3445 				return err;
3446 			exts->nr_actions = err;
3447 		}
3448 	}
3449 #else
3450 	if ((exts->action && tb[exts->action]) ||
3451 	    (exts->police && tb[exts->police])) {
3452 		NL_SET_ERR_MSG(extack, "Classifier actions are not supported per compile options (CONFIG_NET_CLS_ACT)");
3453 		return -EOPNOTSUPP;
3454 	}
3455 #endif
3456 
3457 	return 0;
3458 }
3459 EXPORT_SYMBOL(tcf_exts_validate_ex);
3460 
3461 int tcf_exts_validate(struct net *net, struct tcf_proto *tp, struct nlattr **tb,
3462 		      struct nlattr *rate_tlv, struct tcf_exts *exts,
3463 		      u32 flags, struct netlink_ext_ack *extack)
3464 {
3465 	return tcf_exts_validate_ex(net, tp, tb, rate_tlv, exts,
3466 				    flags, 0, extack);
3467 }
3468 EXPORT_SYMBOL(tcf_exts_validate);
3469 
3470 void tcf_exts_change(struct tcf_exts *dst, struct tcf_exts *src)
3471 {
3472 #ifdef CONFIG_NET_CLS_ACT
3473 	struct tcf_exts old = *dst;
3474 
3475 	*dst = *src;
3476 	tcf_exts_destroy(&old);
3477 #endif
3478 }
3479 EXPORT_SYMBOL(tcf_exts_change);
3480 
3481 #ifdef CONFIG_NET_CLS_ACT
3482 static struct tc_action *tcf_exts_first_act(struct tcf_exts *exts)
3483 {
3484 	if (exts->nr_actions == 0)
3485 		return NULL;
3486 	else
3487 		return exts->actions[0];
3488 }
3489 #endif
3490 
3491 int tcf_exts_dump(struct sk_buff *skb, struct tcf_exts *exts)
3492 {
3493 #ifdef CONFIG_NET_CLS_ACT
3494 	struct nlattr *nest;
3495 
3496 	if (exts->action && tcf_exts_has_actions(exts)) {
3497 		/*
3498 		 * again for backward compatible mode - we want
3499 		 * to work with both old and new modes of entering
3500 		 * tc data even if iproute2  was newer - jhs
3501 		 */
3502 		if (exts->type != TCA_OLD_COMPAT) {
3503 			nest = nla_nest_start_noflag(skb, exts->action);
3504 			if (nest == NULL)
3505 				goto nla_put_failure;
3506 
3507 			if (tcf_action_dump(skb, exts->actions, 0, 0, false)
3508 			    < 0)
3509 				goto nla_put_failure;
3510 			nla_nest_end(skb, nest);
3511 		} else if (exts->police) {
3512 			struct tc_action *act = tcf_exts_first_act(exts);
3513 			nest = nla_nest_start_noflag(skb, exts->police);
3514 			if (nest == NULL || !act)
3515 				goto nla_put_failure;
3516 			if (tcf_action_dump_old(skb, act, 0, 0) < 0)
3517 				goto nla_put_failure;
3518 			nla_nest_end(skb, nest);
3519 		}
3520 	}
3521 	return 0;
3522 
3523 nla_put_failure:
3524 	nla_nest_cancel(skb, nest);
3525 	return -1;
3526 #else
3527 	return 0;
3528 #endif
3529 }
3530 EXPORT_SYMBOL(tcf_exts_dump);
3531 
3532 int tcf_exts_terse_dump(struct sk_buff *skb, struct tcf_exts *exts)
3533 {
3534 #ifdef CONFIG_NET_CLS_ACT
3535 	struct nlattr *nest;
3536 
3537 	if (!exts->action || !tcf_exts_has_actions(exts))
3538 		return 0;
3539 
3540 	nest = nla_nest_start_noflag(skb, exts->action);
3541 	if (!nest)
3542 		goto nla_put_failure;
3543 
3544 	if (tcf_action_dump(skb, exts->actions, 0, 0, true) < 0)
3545 		goto nla_put_failure;
3546 	nla_nest_end(skb, nest);
3547 	return 0;
3548 
3549 nla_put_failure:
3550 	nla_nest_cancel(skb, nest);
3551 	return -1;
3552 #else
3553 	return 0;
3554 #endif
3555 }
3556 EXPORT_SYMBOL(tcf_exts_terse_dump);
3557 
3558 int tcf_exts_dump_stats(struct sk_buff *skb, struct tcf_exts *exts)
3559 {
3560 #ifdef CONFIG_NET_CLS_ACT
3561 	struct tc_action *a = tcf_exts_first_act(exts);
3562 	if (a != NULL && tcf_action_copy_stats(skb, a, 1) < 0)
3563 		return -1;
3564 #endif
3565 	return 0;
3566 }
3567 EXPORT_SYMBOL(tcf_exts_dump_stats);
3568 
3569 static void tcf_block_offload_inc(struct tcf_block *block, u32 *flags)
3570 {
3571 	if (*flags & TCA_CLS_FLAGS_IN_HW)
3572 		return;
3573 	*flags |= TCA_CLS_FLAGS_IN_HW;
3574 	atomic_inc(&block->offloadcnt);
3575 }
3576 
3577 static void tcf_block_offload_dec(struct tcf_block *block, u32 *flags)
3578 {
3579 	if (!(*flags & TCA_CLS_FLAGS_IN_HW))
3580 		return;
3581 	*flags &= ~TCA_CLS_FLAGS_IN_HW;
3582 	atomic_dec(&block->offloadcnt);
3583 }
3584 
3585 static void tc_cls_offload_cnt_update(struct tcf_block *block,
3586 				      struct tcf_proto *tp, u32 *cnt,
3587 				      u32 *flags, u32 diff, bool add)
3588 {
3589 	lockdep_assert_held(&block->cb_lock);
3590 
3591 	spin_lock(&tp->lock);
3592 	if (add) {
3593 		if (!*cnt)
3594 			tcf_block_offload_inc(block, flags);
3595 		*cnt += diff;
3596 	} else {
3597 		*cnt -= diff;
3598 		if (!*cnt)
3599 			tcf_block_offload_dec(block, flags);
3600 	}
3601 	spin_unlock(&tp->lock);
3602 }
3603 
3604 static void
3605 tc_cls_offload_cnt_reset(struct tcf_block *block, struct tcf_proto *tp,
3606 			 u32 *cnt, u32 *flags)
3607 {
3608 	lockdep_assert_held(&block->cb_lock);
3609 
3610 	spin_lock(&tp->lock);
3611 	tcf_block_offload_dec(block, flags);
3612 	*cnt = 0;
3613 	spin_unlock(&tp->lock);
3614 }
3615 
3616 static int
3617 __tc_setup_cb_call(struct tcf_block *block, enum tc_setup_type type,
3618 		   void *type_data, bool err_stop)
3619 {
3620 	struct flow_block_cb *block_cb;
3621 	int ok_count = 0;
3622 	int err;
3623 
3624 	list_for_each_entry(block_cb, &block->flow_block.cb_list, list) {
3625 		err = block_cb->cb(type, type_data, block_cb->cb_priv);
3626 		if (err) {
3627 			if (err_stop)
3628 				return err;
3629 		} else {
3630 			ok_count++;
3631 		}
3632 	}
3633 	return ok_count;
3634 }
3635 
3636 int tc_setup_cb_call(struct tcf_block *block, enum tc_setup_type type,
3637 		     void *type_data, bool err_stop, bool rtnl_held)
3638 {
3639 	bool take_rtnl = READ_ONCE(block->lockeddevcnt) && !rtnl_held;
3640 	int ok_count;
3641 
3642 retry:
3643 	if (take_rtnl)
3644 		rtnl_lock();
3645 	down_read(&block->cb_lock);
3646 	/* Need to obtain rtnl lock if block is bound to devs that require it.
3647 	 * In block bind code cb_lock is obtained while holding rtnl, so we must
3648 	 * obtain the locks in same order here.
3649 	 */
3650 	if (!rtnl_held && !take_rtnl && block->lockeddevcnt) {
3651 		up_read(&block->cb_lock);
3652 		take_rtnl = true;
3653 		goto retry;
3654 	}
3655 
3656 	ok_count = __tc_setup_cb_call(block, type, type_data, err_stop);
3657 
3658 	up_read(&block->cb_lock);
3659 	if (take_rtnl)
3660 		rtnl_unlock();
3661 	return ok_count;
3662 }
3663 EXPORT_SYMBOL(tc_setup_cb_call);
3664 
3665 /* Non-destructive filter add. If filter that wasn't already in hardware is
3666  * successfully offloaded, increment block offloads counter. On failure,
3667  * previously offloaded filter is considered to be intact and offloads counter
3668  * is not decremented.
3669  */
3670 
3671 int tc_setup_cb_add(struct tcf_block *block, struct tcf_proto *tp,
3672 		    enum tc_setup_type type, void *type_data, bool err_stop,
3673 		    u32 *flags, unsigned int *in_hw_count, bool rtnl_held)
3674 {
3675 	bool take_rtnl = READ_ONCE(block->lockeddevcnt) && !rtnl_held;
3676 	int ok_count;
3677 
3678 retry:
3679 	if (take_rtnl)
3680 		rtnl_lock();
3681 	down_read(&block->cb_lock);
3682 	/* Need to obtain rtnl lock if block is bound to devs that require it.
3683 	 * In block bind code cb_lock is obtained while holding rtnl, so we must
3684 	 * obtain the locks in same order here.
3685 	 */
3686 	if (!rtnl_held && !take_rtnl && block->lockeddevcnt) {
3687 		up_read(&block->cb_lock);
3688 		take_rtnl = true;
3689 		goto retry;
3690 	}
3691 
3692 	/* Make sure all netdevs sharing this block are offload-capable. */
3693 	if (block->nooffloaddevcnt && err_stop) {
3694 		ok_count = -EOPNOTSUPP;
3695 		goto err_unlock;
3696 	}
3697 
3698 	ok_count = __tc_setup_cb_call(block, type, type_data, err_stop);
3699 	if (ok_count < 0)
3700 		goto err_unlock;
3701 
3702 	if (tp->ops->hw_add)
3703 		tp->ops->hw_add(tp, type_data);
3704 	if (ok_count > 0)
3705 		tc_cls_offload_cnt_update(block, tp, in_hw_count, flags,
3706 					  ok_count, true);
3707 err_unlock:
3708 	up_read(&block->cb_lock);
3709 	if (take_rtnl)
3710 		rtnl_unlock();
3711 	return min(ok_count, 0);
3712 }
3713 EXPORT_SYMBOL(tc_setup_cb_add);
3714 
3715 /* Destructive filter replace. If filter that wasn't already in hardware is
3716  * successfully offloaded, increment block offload counter. On failure,
3717  * previously offloaded filter is considered to be destroyed and offload counter
3718  * is decremented.
3719  */
3720 
3721 int tc_setup_cb_replace(struct tcf_block *block, struct tcf_proto *tp,
3722 			enum tc_setup_type type, void *type_data, bool err_stop,
3723 			u32 *old_flags, unsigned int *old_in_hw_count,
3724 			u32 *new_flags, unsigned int *new_in_hw_count,
3725 			bool rtnl_held)
3726 {
3727 	bool take_rtnl = READ_ONCE(block->lockeddevcnt) && !rtnl_held;
3728 	int ok_count;
3729 
3730 retry:
3731 	if (take_rtnl)
3732 		rtnl_lock();
3733 	down_read(&block->cb_lock);
3734 	/* Need to obtain rtnl lock if block is bound to devs that require it.
3735 	 * In block bind code cb_lock is obtained while holding rtnl, so we must
3736 	 * obtain the locks in same order here.
3737 	 */
3738 	if (!rtnl_held && !take_rtnl && block->lockeddevcnt) {
3739 		up_read(&block->cb_lock);
3740 		take_rtnl = true;
3741 		goto retry;
3742 	}
3743 
3744 	/* Make sure all netdevs sharing this block are offload-capable. */
3745 	if (block->nooffloaddevcnt && err_stop) {
3746 		ok_count = -EOPNOTSUPP;
3747 		goto err_unlock;
3748 	}
3749 
3750 	tc_cls_offload_cnt_reset(block, tp, old_in_hw_count, old_flags);
3751 	if (tp->ops->hw_del)
3752 		tp->ops->hw_del(tp, type_data);
3753 
3754 	ok_count = __tc_setup_cb_call(block, type, type_data, err_stop);
3755 	if (ok_count < 0)
3756 		goto err_unlock;
3757 
3758 	if (tp->ops->hw_add)
3759 		tp->ops->hw_add(tp, type_data);
3760 	if (ok_count > 0)
3761 		tc_cls_offload_cnt_update(block, tp, new_in_hw_count,
3762 					  new_flags, ok_count, true);
3763 err_unlock:
3764 	up_read(&block->cb_lock);
3765 	if (take_rtnl)
3766 		rtnl_unlock();
3767 	return min(ok_count, 0);
3768 }
3769 EXPORT_SYMBOL(tc_setup_cb_replace);
3770 
3771 /* Destroy filter and decrement block offload counter, if filter was previously
3772  * offloaded.
3773  */
3774 
3775 int tc_setup_cb_destroy(struct tcf_block *block, struct tcf_proto *tp,
3776 			enum tc_setup_type type, void *type_data, bool err_stop,
3777 			u32 *flags, unsigned int *in_hw_count, bool rtnl_held)
3778 {
3779 	bool take_rtnl = READ_ONCE(block->lockeddevcnt) && !rtnl_held;
3780 	int ok_count;
3781 
3782 retry:
3783 	if (take_rtnl)
3784 		rtnl_lock();
3785 	down_read(&block->cb_lock);
3786 	/* Need to obtain rtnl lock if block is bound to devs that require it.
3787 	 * In block bind code cb_lock is obtained while holding rtnl, so we must
3788 	 * obtain the locks in same order here.
3789 	 */
3790 	if (!rtnl_held && !take_rtnl && block->lockeddevcnt) {
3791 		up_read(&block->cb_lock);
3792 		take_rtnl = true;
3793 		goto retry;
3794 	}
3795 
3796 	ok_count = __tc_setup_cb_call(block, type, type_data, err_stop);
3797 
3798 	tc_cls_offload_cnt_reset(block, tp, in_hw_count, flags);
3799 	if (tp->ops->hw_del)
3800 		tp->ops->hw_del(tp, type_data);
3801 
3802 	up_read(&block->cb_lock);
3803 	if (take_rtnl)
3804 		rtnl_unlock();
3805 	return min(ok_count, 0);
3806 }
3807 EXPORT_SYMBOL(tc_setup_cb_destroy);
3808 
3809 int tc_setup_cb_reoffload(struct tcf_block *block, struct tcf_proto *tp,
3810 			  bool add, flow_setup_cb_t *cb,
3811 			  enum tc_setup_type type, void *type_data,
3812 			  void *cb_priv, u32 *flags, unsigned int *in_hw_count)
3813 {
3814 	int err = cb(type, type_data, cb_priv);
3815 
3816 	if (err) {
3817 		if (add && tc_skip_sw(*flags))
3818 			return err;
3819 	} else {
3820 		tc_cls_offload_cnt_update(block, tp, in_hw_count, flags, 1,
3821 					  add);
3822 	}
3823 
3824 	return 0;
3825 }
3826 EXPORT_SYMBOL(tc_setup_cb_reoffload);
3827 
3828 static int tcf_act_get_user_cookie(struct flow_action_entry *entry,
3829 				   const struct tc_action *act)
3830 {
3831 	struct tc_cookie *user_cookie;
3832 	int err = 0;
3833 
3834 	rcu_read_lock();
3835 	user_cookie = rcu_dereference(act->user_cookie);
3836 	if (user_cookie) {
3837 		entry->user_cookie = flow_action_cookie_create(user_cookie->data,
3838 							       user_cookie->len,
3839 							       GFP_ATOMIC);
3840 		if (!entry->user_cookie)
3841 			err = -ENOMEM;
3842 	}
3843 	rcu_read_unlock();
3844 	return err;
3845 }
3846 
3847 static void tcf_act_put_user_cookie(struct flow_action_entry *entry)
3848 {
3849 	flow_action_cookie_destroy(entry->user_cookie);
3850 }
3851 
3852 void tc_cleanup_offload_action(struct flow_action *flow_action)
3853 {
3854 	struct flow_action_entry *entry;
3855 	int i;
3856 
3857 	flow_action_for_each(i, entry, flow_action) {
3858 		tcf_act_put_user_cookie(entry);
3859 		if (entry->destructor)
3860 			entry->destructor(entry->destructor_priv);
3861 	}
3862 }
3863 EXPORT_SYMBOL(tc_cleanup_offload_action);
3864 
3865 static int tc_setup_offload_act(struct tc_action *act,
3866 				struct flow_action_entry *entry,
3867 				u32 *index_inc,
3868 				struct netlink_ext_ack *extack)
3869 {
3870 #ifdef CONFIG_NET_CLS_ACT
3871 	if (act->ops->offload_act_setup) {
3872 		return act->ops->offload_act_setup(act, entry, index_inc, true,
3873 						   extack);
3874 	} else {
3875 		NL_SET_ERR_MSG(extack, "Action does not support offload");
3876 		return -EOPNOTSUPP;
3877 	}
3878 #else
3879 	return 0;
3880 #endif
3881 }
3882 
3883 int tc_setup_action(struct flow_action *flow_action,
3884 		    struct tc_action *actions[],
3885 		    u32 miss_cookie_base,
3886 		    struct netlink_ext_ack *extack)
3887 {
3888 	int i, j, k, index, err = 0;
3889 	struct tc_action *act;
3890 
3891 	BUILD_BUG_ON(TCA_ACT_HW_STATS_ANY != FLOW_ACTION_HW_STATS_ANY);
3892 	BUILD_BUG_ON(TCA_ACT_HW_STATS_IMMEDIATE != FLOW_ACTION_HW_STATS_IMMEDIATE);
3893 	BUILD_BUG_ON(TCA_ACT_HW_STATS_DELAYED != FLOW_ACTION_HW_STATS_DELAYED);
3894 
3895 	if (!actions)
3896 		return 0;
3897 
3898 	j = 0;
3899 	tcf_act_for_each_action(i, act, actions) {
3900 		struct flow_action_entry *entry;
3901 
3902 		entry = &flow_action->entries[j];
3903 		spin_lock_bh(&act->tcfa_lock);
3904 
3905 		/* Abort the offload if we have exhausted the allocated capacity */
3906 		if (j >= flow_action->num_entries) {
3907 			NL_SET_ERR_MSG_MOD(extack, "Flow action buffer overflow");
3908 			err = -ENOSPC;
3909 			goto err_out_locked;
3910 		}
3911 
3912 		err = tcf_act_get_user_cookie(entry, act);
3913 		if (err)
3914 			goto err_out_locked;
3915 
3916 		index = flow_action->num_entries - j;
3917 		err = tc_setup_offload_act(act, entry, &index,
3918 					   extack);
3919 		if (err)
3920 			goto err_out_locked;
3921 
3922 		for (k = 0; k < index ; k++) {
3923 			entry[k].hw_stats = tc_act_hw_stats(act->hw_stats);
3924 			entry[k].hw_index = act->tcfa_index;
3925 			entry[k].cookie = (unsigned long)act;
3926 			entry[k].miss_cookie =
3927 				tcf_exts_miss_cookie_get(miss_cookie_base, i);
3928 		}
3929 
3930 		j += index;
3931 
3932 		spin_unlock_bh(&act->tcfa_lock);
3933 	}
3934 
3935 err_out:
3936 	if (err)
3937 		tc_cleanup_offload_action(flow_action);
3938 
3939 	return err;
3940 err_out_locked:
3941 	spin_unlock_bh(&act->tcfa_lock);
3942 	goto err_out;
3943 }
3944 
3945 int tc_setup_offload_action(struct flow_action *flow_action,
3946 			    const struct tcf_exts *exts,
3947 			    struct netlink_ext_ack *extack)
3948 {
3949 #ifdef CONFIG_NET_CLS_ACT
3950 	u32 miss_cookie_base;
3951 
3952 	if (!exts)
3953 		return 0;
3954 
3955 	miss_cookie_base = exts->miss_cookie_node ?
3956 			   exts->miss_cookie_node->miss_cookie_base : 0;
3957 	return tc_setup_action(flow_action, exts->actions, miss_cookie_base,
3958 			       extack);
3959 #else
3960 	return 0;
3961 #endif
3962 }
3963 EXPORT_SYMBOL(tc_setup_offload_action);
3964 
3965 unsigned int tcf_exts_num_actions(struct tcf_exts *exts)
3966 {
3967 	unsigned int num_acts = 0;
3968 	struct tc_action *act;
3969 	int i;
3970 
3971 	tcf_exts_for_each_action(i, act, exts) {
3972 		if (is_tcf_pedit(act)) {
3973 			spin_lock_bh(&act->tcfa_lock);
3974 			num_acts += tcf_pedit_nkeys_locked(act);
3975 			spin_unlock_bh(&act->tcfa_lock);
3976 		} else {
3977 			num_acts++;
3978 		}
3979 	}
3980 	return num_acts;
3981 }
3982 EXPORT_SYMBOL(tcf_exts_num_actions);
3983 
3984 #ifdef CONFIG_NET_CLS_ACT
3985 static int tcf_qevent_parse_block_index(struct nlattr *block_index_attr,
3986 					u32 *p_block_index,
3987 					struct netlink_ext_ack *extack)
3988 {
3989 	*p_block_index = nla_get_u32(block_index_attr);
3990 	if (!*p_block_index) {
3991 		NL_SET_ERR_MSG(extack, "Block number may not be zero");
3992 		return -EINVAL;
3993 	}
3994 
3995 	return 0;
3996 }
3997 
3998 int tcf_qevent_init(struct tcf_qevent *qe, struct Qdisc *sch,
3999 		    enum flow_block_binder_type binder_type,
4000 		    struct nlattr *block_index_attr,
4001 		    struct netlink_ext_ack *extack)
4002 {
4003 	u32 block_index;
4004 	int err;
4005 
4006 	if (!block_index_attr)
4007 		return 0;
4008 
4009 	err = tcf_qevent_parse_block_index(block_index_attr, &block_index, extack);
4010 	if (err)
4011 		return err;
4012 
4013 	qe->info.binder_type = binder_type;
4014 	qe->info.chain_head_change = tcf_chain_head_change_dflt;
4015 	qe->info.chain_head_change_priv = &qe->filter_chain;
4016 	qe->info.block_index = block_index;
4017 
4018 	return tcf_block_get_ext(&qe->block, sch, &qe->info, extack);
4019 }
4020 EXPORT_SYMBOL(tcf_qevent_init);
4021 
4022 void tcf_qevent_destroy(struct tcf_qevent *qe, struct Qdisc *sch)
4023 {
4024 	if (qe->info.block_index)
4025 		tcf_block_put_ext(qe->block, sch, &qe->info);
4026 }
4027 EXPORT_SYMBOL(tcf_qevent_destroy);
4028 
4029 int tcf_qevent_validate_change(struct tcf_qevent *qe, struct nlattr *block_index_attr,
4030 			       struct netlink_ext_ack *extack)
4031 {
4032 	u32 block_index;
4033 	int err;
4034 
4035 	if (!block_index_attr)
4036 		return 0;
4037 
4038 	err = tcf_qevent_parse_block_index(block_index_attr, &block_index, extack);
4039 	if (err)
4040 		return err;
4041 
4042 	/* Bounce newly-configured block or change in block. */
4043 	if (block_index != qe->info.block_index) {
4044 		NL_SET_ERR_MSG(extack, "Change of blocks is not supported");
4045 		return -EINVAL;
4046 	}
4047 
4048 	return 0;
4049 }
4050 EXPORT_SYMBOL(tcf_qevent_validate_change);
4051 
4052 struct sk_buff *tcf_qevent_handle(struct tcf_qevent *qe, struct Qdisc *sch, struct sk_buff *skb,
4053 				  struct sk_buff **to_free, int *ret)
4054 {
4055 	struct tcf_result cl_res;
4056 	struct tcf_proto *fl;
4057 
4058 	if (!qe->info.block_index)
4059 		return skb;
4060 
4061 	fl = rcu_dereference_bh(qe->filter_chain);
4062 
4063 	switch (tcf_classify_qdisc(skb, fl, &cl_res, false)) {
4064 	case TC_ACT_SHOT:
4065 		qdisc_qstats_drop(sch);
4066 		__qdisc_drop(skb, to_free);
4067 		*ret = __NET_XMIT_BYPASS;
4068 		return NULL;
4069 	case TC_ACT_STOLEN:
4070 	case TC_ACT_QUEUED:
4071 	case TC_ACT_TRAP:
4072 		__qdisc_drop(skb, to_free);
4073 		*ret = __NET_XMIT_STOLEN;
4074 		return NULL;
4075 	case TC_ACT_CONSUMED:
4076 		*ret = __NET_XMIT_STOLEN;
4077 		return NULL;
4078 	}
4079 
4080 	return skb;
4081 }
4082 EXPORT_SYMBOL(tcf_qevent_handle);
4083 
4084 int tcf_qevent_dump(struct sk_buff *skb, int attr_name, struct tcf_qevent *qe)
4085 {
4086 	if (!qe->info.block_index)
4087 		return 0;
4088 	return nla_put_u32(skb, attr_name, qe->info.block_index);
4089 }
4090 EXPORT_SYMBOL(tcf_qevent_dump);
4091 #endif
4092 
4093 static __net_init int tcf_net_init(struct net *net)
4094 {
4095 	struct tcf_net *tn = net_generic(net, tcf_net_id);
4096 
4097 	spin_lock_init(&tn->idr_lock);
4098 	idr_init(&tn->idr);
4099 	return 0;
4100 }
4101 
4102 static void __net_exit tcf_net_exit(struct net *net)
4103 {
4104 	struct tcf_net *tn = net_generic(net, tcf_net_id);
4105 
4106 	idr_destroy(&tn->idr);
4107 }
4108 
4109 static struct pernet_operations tcf_net_ops = {
4110 	.init = tcf_net_init,
4111 	.exit = tcf_net_exit,
4112 	.id   = &tcf_net_id,
4113 	.size = sizeof(struct tcf_net),
4114 };
4115 
4116 static const struct rtnl_msg_handler tc_filter_rtnl_msg_handlers[] __initconst = {
4117 	{.msgtype = RTM_NEWTFILTER, .doit = tc_new_tfilter,
4118 	 .flags = RTNL_FLAG_DOIT_UNLOCKED},
4119 	{.msgtype = RTM_DELTFILTER, .doit = tc_del_tfilter,
4120 	 .flags = RTNL_FLAG_DOIT_UNLOCKED},
4121 	{.msgtype = RTM_GETTFILTER, .doit = tc_get_tfilter,
4122 	 .dumpit = tc_dump_tfilter, .flags = RTNL_FLAG_DOIT_UNLOCKED},
4123 	{.msgtype = RTM_NEWCHAIN, .doit = tc_ctl_chain},
4124 	{.msgtype = RTM_DELCHAIN, .doit = tc_ctl_chain},
4125 	{.msgtype = RTM_GETCHAIN, .doit = tc_ctl_chain,
4126 	 .dumpit = tc_dump_chain},
4127 };
4128 
4129 static int __init tc_filter_init(void)
4130 {
4131 	int err;
4132 
4133 	tc_filter_wq = alloc_ordered_workqueue("tc_filter_workqueue", 0);
4134 	if (!tc_filter_wq)
4135 		return -ENOMEM;
4136 
4137 	err = register_pernet_subsys(&tcf_net_ops);
4138 	if (err)
4139 		goto err_register_pernet_subsys;
4140 
4141 	xa_init_flags(&tcf_exts_miss_cookies_xa, XA_FLAGS_ALLOC1);
4142 	rtnl_register_many(tc_filter_rtnl_msg_handlers);
4143 
4144 	return 0;
4145 
4146 err_register_pernet_subsys:
4147 	destroy_workqueue(tc_filter_wq);
4148 	return err;
4149 }
4150 
4151 subsys_initcall(tc_filter_init);
4152