xref: /linux/net/sched/cls_api.c (revision ed9e404dcf9b7bd0bf319bccbdf7ddf90f96dbbb)
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 			return ERR_PTR(-EINVAL);
2154 		/* A u16 nest caps the dump, so once the skb is larger than
2155 		 * any valid message it can never serialize. Stop at the
2156 		 * bound instead of looping until alloc_skb() fails.
2157 		 */
2158 		if (size > U16_MAX + NLMSG_GOODSIZE)
2159 			return ERR_PTR(-EMSGSIZE);
2160 		size += NLMSG_GOODSIZE;
2161 		goto retry;
2162 	}
2163 	return skb;
2164 }
2165 
2166 static int tfilter_notify(struct net *net, struct sk_buff *oskb,
2167 			  struct nlmsghdr *n, struct tcf_proto *tp,
2168 			  struct tcf_block *block, struct Qdisc *q,
2169 			  u32 parent, void *fh, int event, bool unicast,
2170 			  bool rtnl_held, struct netlink_ext_ack *extack)
2171 {
2172 	struct sk_buff *skb;
2173 	u32 portid = oskb ? NETLINK_CB(oskb).portid : 0;
2174 	int err = 0;
2175 
2176 	if (!unicast && !rtnl_notify_needed(net, n->nlmsg_flags, RTNLGRP_TC))
2177 		return 0;
2178 
2179 	skb = tfilter_notify_prep(net, oskb, n, tp, block, q, parent, fh, event,
2180 				  portid, rtnl_held, extack);
2181 	if (IS_ERR(skb))
2182 		return PTR_ERR(skb);
2183 
2184 	if (unicast)
2185 		err = rtnl_unicast(skb, net, portid);
2186 	else
2187 		err = rtnetlink_send(skb, net, portid, RTNLGRP_TC,
2188 				     n->nlmsg_flags & NLM_F_ECHO);
2189 	return err;
2190 }
2191 
2192 static int tfilter_del_notify(struct net *net, struct sk_buff *oskb,
2193 			      struct nlmsghdr *n, struct tcf_proto *tp,
2194 			      struct tcf_block *block, struct Qdisc *q,
2195 			      u32 parent, void *fh, bool *last, bool rtnl_held,
2196 			      struct netlink_ext_ack *extack)
2197 {
2198 	struct sk_buff *skb;
2199 	u32 portid = oskb ? NETLINK_CB(oskb).portid : 0;
2200 	int err;
2201 
2202 	if (!rtnl_notify_needed(net, n->nlmsg_flags, RTNLGRP_TC))
2203 		return tp->ops->delete(tp, fh, last, rtnl_held, extack);
2204 
2205 	skb = tfilter_notify_prep(net, oskb, n, tp, block, q, parent, fh,
2206 				  RTM_DELTFILTER, portid, rtnl_held, extack);
2207 	if (IS_ERR(skb)) {
2208 		if (PTR_ERR(skb) != -EMSGSIZE) {
2209 			NL_SET_ERR_MSG(extack, "Failed to build del event notification");
2210 			return PTR_ERR(skb);
2211 		}
2212 		/* No notification can ever be built for this filter: drop
2213 		 * it rather than refuse the delete.
2214 		 */
2215 		err = tp->ops->delete(tp, fh, last, rtnl_held, extack);
2216 		if (!err)
2217 			NL_SET_ERR_MSG(extack,
2218 				       "Filter deleted; del event notification could not be built");
2219 		return err;
2220 	}
2221 
2222 	err = tp->ops->delete(tp, fh, last, rtnl_held, extack);
2223 	if (err) {
2224 		kfree_skb(skb);
2225 		return err;
2226 	}
2227 
2228 	err = rtnetlink_send(skb, net, portid, RTNLGRP_TC,
2229 			     n->nlmsg_flags & NLM_F_ECHO);
2230 	if (err < 0)
2231 		NL_SET_ERR_MSG(extack, "Failed to send filter delete notification");
2232 
2233 	return err;
2234 }
2235 
2236 static void tfilter_notify_chain(struct net *net, struct sk_buff *oskb,
2237 				 struct tcf_block *block, struct Qdisc *q,
2238 				 u32 parent, struct nlmsghdr *n,
2239 				 struct tcf_chain *chain, int event,
2240 				 struct netlink_ext_ack *extack)
2241 {
2242 	struct tcf_proto *tp;
2243 
2244 	for (tp = tcf_get_next_proto(chain, NULL);
2245 	     tp; tp = tcf_get_next_proto(chain, tp))
2246 		tfilter_notify(net, oskb, n, tp, block, q, parent, NULL,
2247 			       event, false, true, extack);
2248 }
2249 
2250 static void tfilter_put(struct tcf_proto *tp, void *fh)
2251 {
2252 	if (tp->ops->put && fh)
2253 		tp->ops->put(tp, fh);
2254 }
2255 
2256 static bool is_qdisc_ingress(__u32 classid)
2257 {
2258 	return (TC_H_MIN(classid) == TC_H_MIN(TC_H_MIN_INGRESS));
2259 }
2260 
2261 static bool is_ingress_or_clsact(struct tcf_block *block, struct Qdisc *q)
2262 {
2263 	return tcf_block_shared(block) || (q && !!(q->flags & TCQ_F_INGRESS));
2264 }
2265 
2266 enum tcf_tp_insert_state {
2267 	TP_NOT_CREATED = 0, /* did not create and insert a new tp */
2268 	TP_CREATED, /* created and inserted a new tp */
2269 	TP_NOT_OWNED, /* created a proto but failed to insert */
2270 };
2271 
2272 static int tc_new_tfilter(struct sk_buff *skb, struct nlmsghdr *n,
2273 			  struct netlink_ext_ack *extack)
2274 {
2275 	struct net *net = sock_net(skb->sk);
2276 	struct nlattr *tca[TCA_MAX + 1];
2277 	char name[IFNAMSIZ];
2278 	struct tcmsg *t;
2279 	u32 protocol;
2280 	u32 prio;
2281 	bool prio_allocate;
2282 	u32 parent;
2283 	u32 chain_index;
2284 	struct Qdisc *q;
2285 	struct tcf_chain_info chain_info;
2286 	struct tcf_chain *chain;
2287 	struct tcf_block *block;
2288 	struct tcf_proto *tp;
2289 	unsigned long cl;
2290 	void *fh;
2291 	int err;
2292 	enum tcf_tp_insert_state tp_state;
2293 	bool rtnl_held = false;
2294 	u32 flags;
2295 
2296 replay:
2297 	tp_state = TP_NOT_CREATED;
2298 
2299 	err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,
2300 				     rtm_tca_policy, extack);
2301 	if (err < 0)
2302 		return err;
2303 
2304 	t = nlmsg_data(n);
2305 	protocol = TC_H_MIN(t->tcm_info);
2306 	prio = TC_H_MAJ(t->tcm_info);
2307 	prio_allocate = false;
2308 	parent = t->tcm_parent;
2309 	tp = NULL;
2310 	cl = 0;
2311 	block = NULL;
2312 	q = NULL;
2313 	chain = NULL;
2314 	flags = 0;
2315 
2316 	if (prio == 0) {
2317 		/* If no priority is provided by the user,
2318 		 * we allocate one.
2319 		 */
2320 		if (n->nlmsg_flags & NLM_F_CREATE) {
2321 			prio = TC_H_MAKE(0x80000000U, 0U);
2322 			prio_allocate = true;
2323 		} else {
2324 			NL_SET_ERR_MSG(extack, "Invalid filter command with priority of zero");
2325 			return -ENOENT;
2326 		}
2327 	}
2328 
2329 	/* Find head of filter chain. */
2330 
2331 	err = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack);
2332 	if (err)
2333 		return err;
2334 
2335 	if (tcf_proto_check_kind(tca[TCA_KIND], name)) {
2336 		NL_SET_ERR_MSG(extack, "Specified TC filter name too long");
2337 		err = -EINVAL;
2338 		goto errout;
2339 	}
2340 
2341 	/* Take rtnl mutex if rtnl_held was set to true on previous iteration,
2342 	 * block is shared (no qdisc found), qdisc is not unlocked, classifier
2343 	 * type is not specified, classifier is not unlocked.
2344 	 */
2345 	if (rtnl_held ||
2346 	    (q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) ||
2347 	    !tcf_proto_is_unlocked(name)) {
2348 		rtnl_held = true;
2349 		rtnl_lock();
2350 	}
2351 
2352 	err = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack);
2353 	if (err)
2354 		goto errout;
2355 
2356 	block = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index,
2357 				 extack);
2358 	if (IS_ERR(block)) {
2359 		err = PTR_ERR(block);
2360 		goto errout;
2361 	}
2362 	block->classid = parent;
2363 
2364 	chain_index = nla_get_u32_default(tca[TCA_CHAIN], 0);
2365 	if (chain_index > TC_ACT_EXT_VAL_MASK) {
2366 		NL_SET_ERR_MSG(extack, "Specified chain index exceeds upper limit");
2367 		err = -EINVAL;
2368 		goto errout;
2369 	}
2370 	chain = tcf_chain_get(block, chain_index, true);
2371 	if (!chain) {
2372 		NL_SET_ERR_MSG(extack, "Cannot create specified filter chain");
2373 		err = -ENOMEM;
2374 		goto errout;
2375 	}
2376 
2377 	mutex_lock(&chain->filter_chain_lock);
2378 	tp = tcf_chain_tp_find(chain, &chain_info, protocol,
2379 			       prio, prio_allocate, extack);
2380 	if (IS_ERR(tp)) {
2381 		err = PTR_ERR(tp);
2382 		goto errout_locked;
2383 	}
2384 
2385 	if (tp == NULL) {
2386 		struct tcf_proto *tp_new = NULL;
2387 
2388 		if (chain->flushing) {
2389 			err = -EAGAIN;
2390 			goto errout_locked;
2391 		}
2392 
2393 		/* Proto-tcf does not exist, create new one */
2394 
2395 		if (tca[TCA_KIND] == NULL || !protocol) {
2396 			NL_SET_ERR_MSG(extack, "Filter kind and protocol must be specified");
2397 			err = -EINVAL;
2398 			goto errout_locked;
2399 		}
2400 
2401 		if (!(n->nlmsg_flags & NLM_F_CREATE)) {
2402 			NL_SET_ERR_MSG(extack, "Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter");
2403 			err = -ENOENT;
2404 			goto errout_locked;
2405 		}
2406 
2407 		if (prio_allocate)
2408 			prio = tcf_auto_prio(tcf_chain_tp_prev(chain,
2409 							       &chain_info));
2410 
2411 		mutex_unlock(&chain->filter_chain_lock);
2412 		tp_new = tcf_proto_create(name, protocol, prio, chain,
2413 					  rtnl_held, extack);
2414 		if (IS_ERR(tp_new)) {
2415 			err = PTR_ERR(tp_new);
2416 			goto errout_tp;
2417 		}
2418 
2419 		tp_state = TP_CREATED;
2420 		tp = tcf_chain_tp_insert_unique(chain, tp_new, protocol, prio,
2421 						rtnl_held);
2422 		if (IS_ERR(tp)) {
2423 			err = PTR_ERR(tp);
2424 			goto errout_tp;
2425 		}
2426 		if (tp != tp_new)
2427 			tp_state = TP_NOT_OWNED;
2428 	} else {
2429 		mutex_unlock(&chain->filter_chain_lock);
2430 	}
2431 
2432 	if (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) {
2433 		NL_SET_ERR_MSG(extack, "Specified filter kind does not match existing one");
2434 		err = -EINVAL;
2435 		goto errout;
2436 	}
2437 
2438 	fh = tp->ops->get(tp, t->tcm_handle);
2439 
2440 	if (!fh) {
2441 		if (!(n->nlmsg_flags & NLM_F_CREATE)) {
2442 			NL_SET_ERR_MSG(extack, "Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter");
2443 			err = -ENOENT;
2444 			goto errout;
2445 		}
2446 	} else if (n->nlmsg_flags & NLM_F_EXCL) {
2447 		tfilter_put(tp, fh);
2448 		NL_SET_ERR_MSG(extack, "Filter already exists");
2449 		err = -EEXIST;
2450 		goto errout;
2451 	}
2452 
2453 	if (chain->tmplt_ops && chain->tmplt_ops != tp->ops) {
2454 		tfilter_put(tp, fh);
2455 		NL_SET_ERR_MSG(extack, "Chain template is set to a different filter kind");
2456 		err = -EINVAL;
2457 		goto errout;
2458 	}
2459 
2460 	if (!(n->nlmsg_flags & NLM_F_CREATE))
2461 		flags |= TCA_ACT_FLAGS_REPLACE;
2462 	if (!rtnl_held)
2463 		flags |= TCA_ACT_FLAGS_NO_RTNL;
2464 	if (is_qdisc_ingress(parent))
2465 		flags |= TCA_ACT_FLAGS_AT_INGRESS;
2466 	if (is_ingress_or_clsact(block, q))
2467 		flags |= TCA_ACT_FLAGS_AT_INGRESS_OR_CLSACT;
2468 	err = tp->ops->change(net, skb, tp, cl, t->tcm_handle, tca, &fh,
2469 			      flags, extack);
2470 	if (err == 0) {
2471 		tfilter_notify(net, skb, n, tp, block, q, parent, fh,
2472 			       RTM_NEWTFILTER, false, rtnl_held, extack);
2473 		tfilter_put(tp, fh);
2474 		tcf_proto_count_usesw(tp, true);
2475 		/* q pointer is NULL for shared blocks */
2476 		if (q)
2477 			q->flags &= ~TCQ_F_CAN_BYPASS;
2478 	}
2479 
2480 errout:
2481 	if (err && !IS_ERR_OR_NULL(tp) &&
2482 	    (tp_state == TP_CREATED || tp->ops->delete_empty))
2483 		/*
2484 		 * The request is dropping its reference to tp. If it was
2485 		 * the last user (the idr is empty now), reclaim the proto.
2486 		 * A tp this request created is reclaimed unconditionally:
2487 		 * it is the only owner, so marking it for deletion is
2488 		 * safe. Otherwise only classifiers with a delete_empty
2489 		 * callback are reclaimed -- the callback admits an empty
2490 		 * proto only, so a live shared proto is never unlinked.
2491 		 * Classifiers without one (deleting is set
2492 		 * unconditionally) are rtnl-serialized, so the raced
2493 		 * window this guard closes cannot arise for them.
2494 		 */
2495 		tcf_chain_tp_delete_empty(chain, tp, rtnl_held, NULL);
2496 errout_tp:
2497 	if (chain) {
2498 		if (tp && !IS_ERR(tp))
2499 			tcf_proto_put(tp, rtnl_held, NULL);
2500 		if (tp_state == TP_NOT_CREATED)
2501 			tcf_chain_put(chain);
2502 	}
2503 	tcf_block_release(q, block, rtnl_held);
2504 
2505 	if (rtnl_held)
2506 		rtnl_unlock();
2507 
2508 	if (err == -EAGAIN) {
2509 		/* Take rtnl lock in case EAGAIN is caused by concurrent flush
2510 		 * of target chain.
2511 		 */
2512 		rtnl_held = true;
2513 		/* Replay the request. */
2514 		goto replay;
2515 	}
2516 	return err;
2517 
2518 errout_locked:
2519 	mutex_unlock(&chain->filter_chain_lock);
2520 	goto errout;
2521 }
2522 
2523 static int tc_del_tfilter(struct sk_buff *skb, struct nlmsghdr *n,
2524 			  struct netlink_ext_ack *extack)
2525 {
2526 	struct net *net = sock_net(skb->sk);
2527 	struct nlattr *tca[TCA_MAX + 1];
2528 	char name[IFNAMSIZ];
2529 	struct tcmsg *t;
2530 	u32 protocol;
2531 	u32 prio;
2532 	u32 parent;
2533 	u32 chain_index;
2534 	struct Qdisc *q = NULL;
2535 	struct tcf_chain_info chain_info;
2536 	struct tcf_chain *chain = NULL;
2537 	struct tcf_block *block = NULL;
2538 	struct tcf_proto *tp = NULL;
2539 	unsigned long cl = 0;
2540 	void *fh = NULL;
2541 	int err;
2542 	bool rtnl_held = false;
2543 
2544 	err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,
2545 				     rtm_tca_policy, extack);
2546 	if (err < 0)
2547 		return err;
2548 
2549 	t = nlmsg_data(n);
2550 	protocol = TC_H_MIN(t->tcm_info);
2551 	prio = TC_H_MAJ(t->tcm_info);
2552 	parent = t->tcm_parent;
2553 
2554 	if (prio == 0 && (protocol || t->tcm_handle || tca[TCA_KIND])) {
2555 		NL_SET_ERR_MSG(extack, "Cannot flush filters with protocol, handle or kind set");
2556 		return -ENOENT;
2557 	}
2558 
2559 	/* Find head of filter chain. */
2560 
2561 	err = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack);
2562 	if (err)
2563 		return err;
2564 
2565 	if (tcf_proto_check_kind(tca[TCA_KIND], name)) {
2566 		NL_SET_ERR_MSG(extack, "Specified TC filter name too long");
2567 		err = -EINVAL;
2568 		goto errout;
2569 	}
2570 	/* Take rtnl mutex if flushing whole chain, block is shared (no qdisc
2571 	 * found), qdisc is not unlocked, classifier type is not specified,
2572 	 * classifier is not unlocked.
2573 	 */
2574 	if (!prio ||
2575 	    (q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) ||
2576 	    !tcf_proto_is_unlocked(name)) {
2577 		rtnl_held = true;
2578 		rtnl_lock();
2579 	}
2580 
2581 	err = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack);
2582 	if (err)
2583 		goto errout;
2584 
2585 	block = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index,
2586 				 extack);
2587 	if (IS_ERR(block)) {
2588 		err = PTR_ERR(block);
2589 		goto errout;
2590 	}
2591 
2592 	chain_index = nla_get_u32_default(tca[TCA_CHAIN], 0);
2593 	if (chain_index > TC_ACT_EXT_VAL_MASK) {
2594 		NL_SET_ERR_MSG(extack, "Specified chain index exceeds upper limit");
2595 		err = -EINVAL;
2596 		goto errout;
2597 	}
2598 	chain = tcf_chain_get(block, chain_index, false);
2599 	if (!chain) {
2600 		/* User requested flush on non-existent chain. Nothing to do,
2601 		 * so just return success.
2602 		 */
2603 		if (prio == 0) {
2604 			err = 0;
2605 			goto errout;
2606 		}
2607 		NL_SET_ERR_MSG(extack, "Cannot find specified filter chain");
2608 		err = -ENOENT;
2609 		goto errout;
2610 	}
2611 
2612 	if (prio == 0) {
2613 		tfilter_notify_chain(net, skb, block, q, parent, n,
2614 				     chain, RTM_DELTFILTER, extack);
2615 		tcf_chain_flush(chain, rtnl_held);
2616 		err = 0;
2617 		goto errout;
2618 	}
2619 
2620 	mutex_lock(&chain->filter_chain_lock);
2621 	tp = tcf_chain_tp_find(chain, &chain_info, protocol,
2622 			       prio, false, extack);
2623 	if (!tp) {
2624 		err = -ENOENT;
2625 		NL_SET_ERR_MSG(extack, "Filter with specified priority/protocol not found");
2626 		goto errout_locked;
2627 	} else if (IS_ERR(tp)) {
2628 		err = PTR_ERR(tp);
2629 		goto errout_locked;
2630 	} else if (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) {
2631 		NL_SET_ERR_MSG(extack, "Specified filter kind does not match existing one");
2632 		err = -EINVAL;
2633 		goto errout_locked;
2634 	} else if (t->tcm_handle == 0) {
2635 		tcf_proto_signal_destroying(chain, tp);
2636 		tcf_chain_tp_remove(chain, &chain_info, tp);
2637 		mutex_unlock(&chain->filter_chain_lock);
2638 
2639 		tcf_proto_put(tp, rtnl_held, NULL);
2640 		tfilter_notify(net, skb, n, tp, block, q, parent, fh,
2641 			       RTM_DELTFILTER, false, rtnl_held, extack);
2642 		err = 0;
2643 		goto errout;
2644 	}
2645 	mutex_unlock(&chain->filter_chain_lock);
2646 
2647 	fh = tp->ops->get(tp, t->tcm_handle);
2648 
2649 	if (!fh) {
2650 		NL_SET_ERR_MSG(extack, "Specified filter handle not found");
2651 		err = -ENOENT;
2652 	} else {
2653 		bool last;
2654 
2655 		err = tfilter_del_notify(net, skb, n, tp, block, q, parent, fh,
2656 					 &last, rtnl_held, extack);
2657 
2658 		if (err)
2659 			goto errout;
2660 		if (last)
2661 			tcf_chain_tp_delete_empty(chain, tp, rtnl_held, extack);
2662 	}
2663 
2664 errout:
2665 	if (chain) {
2666 		if (tp && !IS_ERR(tp))
2667 			tcf_proto_put(tp, rtnl_held, NULL);
2668 		tcf_chain_put(chain);
2669 	}
2670 	tcf_block_release(q, block, rtnl_held);
2671 
2672 	if (rtnl_held)
2673 		rtnl_unlock();
2674 
2675 	return err;
2676 
2677 errout_locked:
2678 	mutex_unlock(&chain->filter_chain_lock);
2679 	goto errout;
2680 }
2681 
2682 static int tc_get_tfilter(struct sk_buff *skb, struct nlmsghdr *n,
2683 			  struct netlink_ext_ack *extack)
2684 {
2685 	struct net *net = sock_net(skb->sk);
2686 	struct nlattr *tca[TCA_MAX + 1];
2687 	char name[IFNAMSIZ];
2688 	struct tcmsg *t;
2689 	u32 protocol;
2690 	u32 prio;
2691 	u32 parent;
2692 	u32 chain_index;
2693 	struct Qdisc *q = NULL;
2694 	struct tcf_chain_info chain_info;
2695 	struct tcf_chain *chain = NULL;
2696 	struct tcf_block *block = NULL;
2697 	struct tcf_proto *tp = NULL;
2698 	unsigned long cl = 0;
2699 	void *fh = NULL;
2700 	int err;
2701 	bool rtnl_held = false;
2702 
2703 	err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,
2704 				     rtm_tca_policy, extack);
2705 	if (err < 0)
2706 		return err;
2707 
2708 	t = nlmsg_data(n);
2709 	protocol = TC_H_MIN(t->tcm_info);
2710 	prio = TC_H_MAJ(t->tcm_info);
2711 	parent = t->tcm_parent;
2712 
2713 	if (prio == 0) {
2714 		NL_SET_ERR_MSG(extack, "Invalid filter command with priority of zero");
2715 		return -ENOENT;
2716 	}
2717 
2718 	/* Find head of filter chain. */
2719 
2720 	err = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack);
2721 	if (err)
2722 		return err;
2723 
2724 	if (tcf_proto_check_kind(tca[TCA_KIND], name)) {
2725 		NL_SET_ERR_MSG(extack, "Specified TC filter name too long");
2726 		err = -EINVAL;
2727 		goto errout;
2728 	}
2729 	/* Take rtnl mutex if block is shared (no qdisc found), qdisc is not
2730 	 * unlocked, classifier type is not specified, classifier is not
2731 	 * unlocked.
2732 	 */
2733 	if ((q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) ||
2734 	    !tcf_proto_is_unlocked(name)) {
2735 		rtnl_held = true;
2736 		rtnl_lock();
2737 	}
2738 
2739 	err = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack);
2740 	if (err)
2741 		goto errout;
2742 
2743 	block = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index,
2744 				 extack);
2745 	if (IS_ERR(block)) {
2746 		err = PTR_ERR(block);
2747 		goto errout;
2748 	}
2749 
2750 	chain_index = nla_get_u32_default(tca[TCA_CHAIN], 0);
2751 	if (chain_index > TC_ACT_EXT_VAL_MASK) {
2752 		NL_SET_ERR_MSG(extack, "Specified chain index exceeds upper limit");
2753 		err = -EINVAL;
2754 		goto errout;
2755 	}
2756 	chain = tcf_chain_get(block, chain_index, false);
2757 	if (!chain) {
2758 		NL_SET_ERR_MSG(extack, "Cannot find specified filter chain");
2759 		err = -EINVAL;
2760 		goto errout;
2761 	}
2762 
2763 	mutex_lock(&chain->filter_chain_lock);
2764 	tp = tcf_chain_tp_find(chain, &chain_info, protocol,
2765 			       prio, false, extack);
2766 	mutex_unlock(&chain->filter_chain_lock);
2767 	if (!tp) {
2768 		err = -ENOENT;
2769 		NL_SET_ERR_MSG(extack, "Filter with specified priority/protocol not found");
2770 		goto errout;
2771 	} else if (IS_ERR(tp)) {
2772 		err = PTR_ERR(tp);
2773 		goto errout;
2774 	} else if (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) {
2775 		NL_SET_ERR_MSG(extack, "Specified filter kind does not match existing one");
2776 		err = -EINVAL;
2777 		goto errout;
2778 	}
2779 
2780 	fh = tp->ops->get(tp, t->tcm_handle);
2781 
2782 	if (!fh) {
2783 		NL_SET_ERR_MSG(extack, "Specified filter handle not found");
2784 		err = -ENOENT;
2785 	} else {
2786 		err = tfilter_notify(net, skb, n, tp, block, q, parent,
2787 				     fh, RTM_NEWTFILTER, true, rtnl_held, NULL);
2788 		if (err < 0)
2789 			NL_SET_ERR_MSG(extack, "Failed to send filter notify message");
2790 	}
2791 
2792 	tfilter_put(tp, fh);
2793 errout:
2794 	if (chain) {
2795 		if (tp && !IS_ERR(tp))
2796 			tcf_proto_put(tp, rtnl_held, NULL);
2797 		tcf_chain_put(chain);
2798 	}
2799 	tcf_block_release(q, block, rtnl_held);
2800 
2801 	if (rtnl_held)
2802 		rtnl_unlock();
2803 
2804 	return err;
2805 }
2806 
2807 struct tcf_dump_args {
2808 	struct tcf_walker w;
2809 	struct sk_buff *skb;
2810 	struct netlink_callback *cb;
2811 	struct tcf_block *block;
2812 	struct Qdisc *q;
2813 	u32 parent;
2814 	bool terse_dump;
2815 };
2816 
2817 static int tcf_node_dump(struct tcf_proto *tp, void *n, struct tcf_walker *arg)
2818 {
2819 	struct tcf_dump_args *a = (void *)arg;
2820 	struct net *net = sock_net(a->skb->sk);
2821 
2822 	return tcf_fill_node(net, a->skb, tp, a->block, a->q, a->parent,
2823 			     n, NETLINK_CB(a->cb->skb).portid,
2824 			     a->cb->nlh->nlmsg_seq, NLM_F_MULTI,
2825 			     RTM_NEWTFILTER, a->terse_dump, true, NULL);
2826 }
2827 
2828 static bool tcf_chain_dump(struct tcf_chain *chain, struct Qdisc *q, u32 parent,
2829 			   struct sk_buff *skb, struct netlink_callback *cb,
2830 			   long index_start, long *p_index, bool terse)
2831 {
2832 	struct net *net = sock_net(skb->sk);
2833 	struct tcf_block *block = chain->block;
2834 	struct tcmsg *tcm = nlmsg_data(cb->nlh);
2835 	struct tcf_proto *tp, *tp_prev;
2836 	struct tcf_dump_args arg;
2837 
2838 	for (tp = __tcf_get_next_proto(chain, NULL);
2839 	     tp;
2840 	     tp_prev = tp,
2841 		     tp = __tcf_get_next_proto(chain, tp),
2842 		     tcf_proto_put(tp_prev, true, NULL),
2843 		     (*p_index)++) {
2844 		if (*p_index < index_start)
2845 			continue;
2846 		if (TC_H_MAJ(tcm->tcm_info) &&
2847 		    TC_H_MAJ(tcm->tcm_info) != tp->prio)
2848 			continue;
2849 		if (TC_H_MIN(tcm->tcm_info) &&
2850 		    TC_H_MIN(tcm->tcm_info) != tp->protocol)
2851 			continue;
2852 		if (*p_index > index_start)
2853 			memset(&cb->args[1], 0,
2854 			       sizeof(cb->args) - sizeof(cb->args[0]));
2855 		if (cb->args[1] == 0) {
2856 			if (tcf_fill_node(net, skb, tp, block, q, parent, NULL,
2857 					  NETLINK_CB(cb->skb).portid,
2858 					  cb->nlh->nlmsg_seq, NLM_F_MULTI,
2859 					  RTM_NEWTFILTER, false, true, NULL) <= 0)
2860 				goto errout;
2861 			cb->args[1] = 1;
2862 		}
2863 		if (!tp->ops->walk)
2864 			continue;
2865 		arg.w.fn = tcf_node_dump;
2866 		arg.skb = skb;
2867 		arg.cb = cb;
2868 		arg.block = block;
2869 		arg.q = q;
2870 		arg.parent = parent;
2871 		arg.w.stop = 0;
2872 		arg.w.skip = cb->args[1] - 1;
2873 		arg.w.count = 0;
2874 		arg.w.cookie = cb->args[2];
2875 		arg.terse_dump = terse;
2876 		tp->ops->walk(tp, &arg.w, true);
2877 		cb->args[2] = arg.w.cookie;
2878 		cb->args[1] = arg.w.count + 1;
2879 		if (arg.w.stop)
2880 			goto errout;
2881 	}
2882 	return true;
2883 
2884 errout:
2885 	tcf_proto_put(tp, true, NULL);
2886 	return false;
2887 }
2888 
2889 static const struct nla_policy tcf_tfilter_dump_policy[TCA_MAX + 1] = {
2890 	[TCA_CHAIN]      = { .type = NLA_U32 },
2891 	[TCA_DUMP_FLAGS] = NLA_POLICY_BITFIELD32(TCA_DUMP_FLAGS_TERSE),
2892 };
2893 
2894 /* called with RTNL */
2895 static int tc_dump_tfilter(struct sk_buff *skb, struct netlink_callback *cb)
2896 {
2897 	struct tcf_chain *chain, *chain_prev;
2898 	struct net *net = sock_net(skb->sk);
2899 	struct nlattr *tca[TCA_MAX + 1];
2900 	struct Qdisc *q = NULL;
2901 	struct tcf_block *block;
2902 	struct tcmsg *tcm = nlmsg_data(cb->nlh);
2903 	bool terse_dump = false;
2904 	long index_start;
2905 	long index;
2906 	u32 parent;
2907 	int err;
2908 
2909 	if (nlmsg_len(cb->nlh) < sizeof(*tcm))
2910 		return skb->len;
2911 
2912 	err = nlmsg_parse_deprecated(cb->nlh, sizeof(*tcm), tca, TCA_MAX,
2913 				     tcf_tfilter_dump_policy, cb->extack);
2914 	if (err)
2915 		return err;
2916 
2917 	if (tca[TCA_DUMP_FLAGS]) {
2918 		struct nla_bitfield32 flags =
2919 			nla_get_bitfield32(tca[TCA_DUMP_FLAGS]);
2920 
2921 		terse_dump = flags.value & TCA_DUMP_FLAGS_TERSE;
2922 	}
2923 
2924 	if (tcm->tcm_ifindex == TCM_IFINDEX_MAGIC_BLOCK) {
2925 		block = tcf_block_refcnt_get(net, tcm->tcm_block_index);
2926 		if (!block)
2927 			goto out;
2928 		/* If we work with block index, q is NULL and parent value
2929 		 * will never be used in the following code. The check
2930 		 * in tcf_fill_node prevents it. However, compiler does not
2931 		 * see that far, so set parent to zero to silence the warning
2932 		 * about parent being uninitialized.
2933 		 */
2934 		parent = 0;
2935 	} else {
2936 		const struct Qdisc_class_ops *cops;
2937 		struct net_device *dev;
2938 		unsigned long cl = 0;
2939 
2940 		dev = __dev_get_by_index(net, tcm->tcm_ifindex);
2941 		if (!dev)
2942 			return skb->len;
2943 
2944 		parent = tcm->tcm_parent;
2945 		if (!parent)
2946 			q = rtnl_dereference(dev->qdisc);
2947 		else
2948 			q = qdisc_lookup(dev, TC_H_MAJ(tcm->tcm_parent));
2949 		if (!q)
2950 			goto out;
2951 		cops = q->ops->cl_ops;
2952 		if (!cops)
2953 			goto out;
2954 		if (!cops->tcf_block)
2955 			goto out;
2956 		if (TC_H_MIN(tcm->tcm_parent)) {
2957 			cl = cops->find(q, tcm->tcm_parent);
2958 			if (cl == 0)
2959 				goto out;
2960 		}
2961 		block = cops->tcf_block(q, cl, NULL);
2962 		if (!block)
2963 			goto out;
2964 		parent = block->classid;
2965 		if (tcf_block_shared(block))
2966 			q = NULL;
2967 	}
2968 
2969 	index_start = cb->args[0];
2970 	index = 0;
2971 
2972 	for (chain = __tcf_get_next_chain(block, NULL);
2973 	     chain;
2974 	     chain_prev = chain,
2975 		     chain = __tcf_get_next_chain(block, chain),
2976 		     tcf_chain_put(chain_prev)) {
2977 		if (tca[TCA_CHAIN] &&
2978 		    nla_get_u32(tca[TCA_CHAIN]) != chain->index)
2979 			continue;
2980 		if (!tcf_chain_dump(chain, q, parent, skb, cb,
2981 				    index_start, &index, terse_dump)) {
2982 			tcf_chain_put(chain);
2983 			err = -EMSGSIZE;
2984 			break;
2985 		}
2986 	}
2987 
2988 	if (tcm->tcm_ifindex == TCM_IFINDEX_MAGIC_BLOCK)
2989 		tcf_block_refcnt_put(block, true);
2990 	cb->args[0] = index;
2991 
2992 out:
2993 	/* If we did no progress, the error (EMSGSIZE) is real */
2994 	if (skb->len == 0 && err)
2995 		return err;
2996 	return skb->len;
2997 }
2998 
2999 static int tc_chain_fill_node(const struct tcf_proto_ops *tmplt_ops,
3000 			      void *tmplt_priv, u32 chain_index,
3001 			      struct net *net, struct sk_buff *skb,
3002 			      struct tcf_block *block,
3003 			      u32 portid, u32 seq, u16 flags, int event,
3004 			      struct netlink_ext_ack *extack)
3005 {
3006 	unsigned char *b = skb_tail_pointer(skb);
3007 	const struct tcf_proto_ops *ops;
3008 	struct nlmsghdr *nlh;
3009 	struct tcmsg *tcm;
3010 	void *priv;
3011 
3012 	ops = tmplt_ops;
3013 	priv = tmplt_priv;
3014 
3015 	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*tcm), flags);
3016 	if (!nlh)
3017 		goto out_nlmsg_trim;
3018 	tcm = nlmsg_data(nlh);
3019 	tcm->tcm_family = AF_UNSPEC;
3020 	tcm->tcm__pad1 = 0;
3021 	tcm->tcm__pad2 = 0;
3022 	tcm->tcm_handle = 0;
3023 	tcm->tcm_info = 0;
3024 	if (block->q) {
3025 		tcm->tcm_ifindex = qdisc_dev(block->q)->ifindex;
3026 		tcm->tcm_parent = block->q->handle;
3027 	} else {
3028 		tcm->tcm_ifindex = TCM_IFINDEX_MAGIC_BLOCK;
3029 		tcm->tcm_block_index = block->index;
3030 	}
3031 
3032 	if (nla_put_u32(skb, TCA_CHAIN, chain_index))
3033 		goto nla_put_failure;
3034 
3035 	if (ops) {
3036 		if (nla_put_string(skb, TCA_KIND, ops->kind))
3037 			goto nla_put_failure;
3038 		if (ops->tmplt_dump(skb, net, priv) < 0)
3039 			goto nla_put_failure;
3040 	}
3041 
3042 	if (extack && extack->_msg &&
3043 	    nla_put_string(skb, TCA_EXT_WARN_MSG, extack->_msg))
3044 		goto out_nlmsg_trim;
3045 
3046 	nlh->nlmsg_len = skb_tail_pointer(skb) - b;
3047 
3048 	return skb->len;
3049 
3050 out_nlmsg_trim:
3051 nla_put_failure:
3052 	nlmsg_trim(skb, b);
3053 	return -EMSGSIZE;
3054 }
3055 
3056 static int tc_chain_notify(struct tcf_chain *chain, struct sk_buff *oskb,
3057 			   u32 seq, u16 flags, int event, bool unicast,
3058 			   struct netlink_ext_ack *extack)
3059 {
3060 	u32 portid = oskb ? NETLINK_CB(oskb).portid : 0;
3061 	struct tcf_block *block = chain->block;
3062 	struct net *net = block->net;
3063 	struct sk_buff *skb;
3064 	int err = 0;
3065 
3066 	if (!unicast && !rtnl_notify_needed(net, flags, RTNLGRP_TC))
3067 		return 0;
3068 
3069 	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
3070 	if (!skb)
3071 		return -ENOBUFS;
3072 
3073 	if (tc_chain_fill_node(chain->tmplt_ops, chain->tmplt_priv,
3074 			       chain->index, net, skb, block, portid,
3075 			       seq, flags, event, extack) <= 0) {
3076 		kfree_skb(skb);
3077 		return -EINVAL;
3078 	}
3079 
3080 	if (unicast)
3081 		err = rtnl_unicast(skb, net, portid);
3082 	else
3083 		err = rtnetlink_send(skb, net, portid, RTNLGRP_TC,
3084 				     flags & NLM_F_ECHO);
3085 
3086 	return err;
3087 }
3088 
3089 static int tc_chain_notify_delete(const struct tcf_proto_ops *tmplt_ops,
3090 				  void *tmplt_priv, u32 chain_index,
3091 				  struct tcf_block *block, struct sk_buff *oskb,
3092 				  u32 seq, u16 flags)
3093 {
3094 	u32 portid = oskb ? NETLINK_CB(oskb).portid : 0;
3095 	struct net *net = block->net;
3096 	struct sk_buff *skb;
3097 
3098 	if (!rtnl_notify_needed(net, flags, RTNLGRP_TC))
3099 		return 0;
3100 
3101 	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
3102 	if (!skb)
3103 		return -ENOBUFS;
3104 
3105 	if (tc_chain_fill_node(tmplt_ops, tmplt_priv, chain_index, net, skb,
3106 			       block, portid, seq, flags, RTM_DELCHAIN, NULL) <= 0) {
3107 		kfree_skb(skb);
3108 		return -EINVAL;
3109 	}
3110 
3111 	return rtnetlink_send(skb, net, portid, RTNLGRP_TC, flags & NLM_F_ECHO);
3112 }
3113 
3114 static int tc_chain_tmplt_add(struct tcf_chain *chain, struct net *net,
3115 			      struct nlattr **tca,
3116 			      struct netlink_ext_ack *extack)
3117 {
3118 	const struct tcf_proto_ops *ops;
3119 	char name[IFNAMSIZ];
3120 	void *tmplt_priv;
3121 
3122 	/* If kind is not set, user did not specify template. */
3123 	if (!tca[TCA_KIND])
3124 		return 0;
3125 
3126 	if (tcf_proto_check_kind(tca[TCA_KIND], name)) {
3127 		NL_SET_ERR_MSG(extack, "Specified TC chain template name too long");
3128 		return -EINVAL;
3129 	}
3130 
3131 	ops = tcf_proto_lookup_ops(name, true, extack);
3132 	if (IS_ERR(ops))
3133 		return PTR_ERR(ops);
3134 	if (!ops->tmplt_create || !ops->tmplt_destroy || !ops->tmplt_dump ||
3135 	    !ops->tmplt_reoffload) {
3136 		NL_SET_ERR_MSG(extack, "Chain templates are not supported with specified classifier");
3137 		module_put(ops->owner);
3138 		return -EOPNOTSUPP;
3139 	}
3140 
3141 	tmplt_priv = ops->tmplt_create(net, chain, tca, extack);
3142 	if (IS_ERR(tmplt_priv)) {
3143 		module_put(ops->owner);
3144 		return PTR_ERR(tmplt_priv);
3145 	}
3146 	chain->tmplt_ops = ops;
3147 	chain->tmplt_priv = tmplt_priv;
3148 	return 0;
3149 }
3150 
3151 static void tc_chain_tmplt_del(const struct tcf_proto_ops *tmplt_ops,
3152 			       void *tmplt_priv)
3153 {
3154 	/* If template ops are set, no work to do for us. */
3155 	if (!tmplt_ops)
3156 		return;
3157 
3158 	tmplt_ops->tmplt_destroy(tmplt_priv);
3159 	module_put(tmplt_ops->owner);
3160 }
3161 
3162 /* Add/delete/get a chain */
3163 
3164 static int tc_ctl_chain(struct sk_buff *skb, struct nlmsghdr *n,
3165 			struct netlink_ext_ack *extack)
3166 {
3167 	struct net *net = sock_net(skb->sk);
3168 	struct nlattr *tca[TCA_MAX + 1];
3169 	struct tcmsg *t;
3170 	u32 parent;
3171 	u32 chain_index;
3172 	struct Qdisc *q;
3173 	struct tcf_chain *chain;
3174 	struct tcf_block *block;
3175 	unsigned long cl;
3176 	int err;
3177 
3178 replay:
3179 	q = NULL;
3180 	err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,
3181 				     rtm_tca_policy, extack);
3182 	if (err < 0)
3183 		return err;
3184 
3185 	t = nlmsg_data(n);
3186 	parent = t->tcm_parent;
3187 	cl = 0;
3188 
3189 	block = tcf_block_find(net, &q, &parent, &cl,
3190 			       t->tcm_ifindex, t->tcm_block_index, extack);
3191 	if (IS_ERR(block))
3192 		return PTR_ERR(block);
3193 
3194 	chain_index = nla_get_u32_default(tca[TCA_CHAIN], 0);
3195 	if (chain_index > TC_ACT_EXT_VAL_MASK) {
3196 		NL_SET_ERR_MSG(extack, "Specified chain index exceeds upper limit");
3197 		err = -EINVAL;
3198 		goto errout_block;
3199 	}
3200 
3201 	mutex_lock(&block->lock);
3202 	chain = tcf_chain_lookup(block, chain_index);
3203 	if (n->nlmsg_type == RTM_NEWCHAIN) {
3204 		if (chain) {
3205 			if (tcf_chain_held_by_acts_only(chain)) {
3206 				/* The chain exists only because there is
3207 				 * some action referencing it.
3208 				 */
3209 				tcf_chain_hold(chain);
3210 			} else {
3211 				NL_SET_ERR_MSG(extack, "Filter chain already exists");
3212 				err = -EEXIST;
3213 				goto errout_block_locked;
3214 			}
3215 		} else {
3216 			if (!(n->nlmsg_flags & NLM_F_CREATE)) {
3217 				NL_SET_ERR_MSG(extack, "Need both RTM_NEWCHAIN and NLM_F_CREATE to create a new chain");
3218 				err = -ENOENT;
3219 				goto errout_block_locked;
3220 			}
3221 			chain = tcf_chain_create(block, chain_index);
3222 			if (!chain) {
3223 				NL_SET_ERR_MSG(extack, "Failed to create filter chain");
3224 				err = -ENOMEM;
3225 				goto errout_block_locked;
3226 			}
3227 		}
3228 	} else {
3229 		if (!chain || tcf_chain_held_by_acts_only(chain)) {
3230 			NL_SET_ERR_MSG(extack, "Cannot find specified filter chain");
3231 			err = -EINVAL;
3232 			goto errout_block_locked;
3233 		}
3234 		tcf_chain_hold(chain);
3235 	}
3236 
3237 	if (n->nlmsg_type == RTM_NEWCHAIN) {
3238 		/* Modifying chain requires holding parent block lock. In case
3239 		 * the chain was successfully added, take a reference to the
3240 		 * chain. This ensures that an empty chain does not disappear at
3241 		 * the end of this function.
3242 		 */
3243 		tcf_chain_hold(chain);
3244 		chain->explicitly_created = true;
3245 	}
3246 	mutex_unlock(&block->lock);
3247 
3248 	switch (n->nlmsg_type) {
3249 	case RTM_NEWCHAIN:
3250 		err = tc_chain_tmplt_add(chain, net, tca, extack);
3251 		if (err) {
3252 			tcf_chain_put_explicitly_created(chain);
3253 			goto errout;
3254 		}
3255 
3256 		tc_chain_notify(chain, NULL, 0, NLM_F_CREATE | NLM_F_EXCL,
3257 				RTM_NEWCHAIN, false, extack);
3258 		break;
3259 	case RTM_DELCHAIN:
3260 		tfilter_notify_chain(net, skb, block, q, parent, n,
3261 				     chain, RTM_DELTFILTER, extack);
3262 		/* Flush the chain first as the user requested chain removal. */
3263 		tcf_chain_flush(chain, true);
3264 		/* In case the chain was successfully deleted, put a reference
3265 		 * to the chain previously taken during addition.
3266 		 */
3267 		tcf_chain_put_explicitly_created(chain);
3268 		break;
3269 	case RTM_GETCHAIN:
3270 		err = tc_chain_notify(chain, skb, n->nlmsg_seq,
3271 				      n->nlmsg_flags, n->nlmsg_type, true, extack);
3272 		if (err < 0)
3273 			NL_SET_ERR_MSG(extack, "Failed to send chain notify message");
3274 		break;
3275 	default:
3276 		err = -EOPNOTSUPP;
3277 		NL_SET_ERR_MSG(extack, "Unsupported message type");
3278 		goto errout;
3279 	}
3280 
3281 errout:
3282 	tcf_chain_put(chain);
3283 errout_block:
3284 	tcf_block_release(q, block, true);
3285 	if (err == -EAGAIN && n->nlmsg_type == RTM_NEWCHAIN)
3286 		/* Replay the request. */
3287 		goto replay;
3288 	return err;
3289 
3290 errout_block_locked:
3291 	mutex_unlock(&block->lock);
3292 	goto errout_block;
3293 }
3294 
3295 /* called with RTNL */
3296 static int tc_dump_chain(struct sk_buff *skb, struct netlink_callback *cb)
3297 {
3298 	struct net *net = sock_net(skb->sk);
3299 	struct nlattr *tca[TCA_MAX + 1];
3300 	struct Qdisc *q = NULL;
3301 	struct tcf_block *block;
3302 	struct tcmsg *tcm = nlmsg_data(cb->nlh);
3303 	struct tcf_chain *chain;
3304 	long index_start;
3305 	long index;
3306 	int err;
3307 
3308 	if (nlmsg_len(cb->nlh) < sizeof(*tcm))
3309 		return skb->len;
3310 
3311 	err = nlmsg_parse_deprecated(cb->nlh, sizeof(*tcm), tca, TCA_MAX,
3312 				     rtm_tca_policy, cb->extack);
3313 	if (err)
3314 		return err;
3315 
3316 	if (tcm->tcm_ifindex == TCM_IFINDEX_MAGIC_BLOCK) {
3317 		block = tcf_block_refcnt_get(net, tcm->tcm_block_index);
3318 		if (!block)
3319 			goto out;
3320 	} else {
3321 		const struct Qdisc_class_ops *cops;
3322 		struct net_device *dev;
3323 		unsigned long cl = 0;
3324 
3325 		dev = __dev_get_by_index(net, tcm->tcm_ifindex);
3326 		if (!dev)
3327 			return skb->len;
3328 
3329 		if (!tcm->tcm_parent)
3330 			q = rtnl_dereference(dev->qdisc);
3331 		else
3332 			q = qdisc_lookup(dev, TC_H_MAJ(tcm->tcm_parent));
3333 
3334 		if (!q)
3335 			goto out;
3336 		cops = q->ops->cl_ops;
3337 		if (!cops)
3338 			goto out;
3339 		if (!cops->tcf_block)
3340 			goto out;
3341 		if (TC_H_MIN(tcm->tcm_parent)) {
3342 			cl = cops->find(q, tcm->tcm_parent);
3343 			if (cl == 0)
3344 				goto out;
3345 		}
3346 		block = cops->tcf_block(q, cl, NULL);
3347 		if (!block)
3348 			goto out;
3349 		if (tcf_block_shared(block))
3350 			q = NULL;
3351 	}
3352 
3353 	index_start = cb->args[0];
3354 	index = 0;
3355 
3356 	mutex_lock(&block->lock);
3357 	list_for_each_entry(chain, &block->chain_list, list) {
3358 		if ((tca[TCA_CHAIN] &&
3359 		     nla_get_u32(tca[TCA_CHAIN]) != chain->index))
3360 			continue;
3361 		if (index < index_start) {
3362 			index++;
3363 			continue;
3364 		}
3365 		if (tcf_chain_held_by_acts_only(chain))
3366 			continue;
3367 		err = tc_chain_fill_node(chain->tmplt_ops, chain->tmplt_priv,
3368 					 chain->index, net, skb, block,
3369 					 NETLINK_CB(cb->skb).portid,
3370 					 cb->nlh->nlmsg_seq, NLM_F_MULTI,
3371 					 RTM_NEWCHAIN, NULL);
3372 		if (err <= 0)
3373 			break;
3374 		index++;
3375 	}
3376 	mutex_unlock(&block->lock);
3377 
3378 	if (tcm->tcm_ifindex == TCM_IFINDEX_MAGIC_BLOCK)
3379 		tcf_block_refcnt_put(block, true);
3380 	cb->args[0] = index;
3381 
3382 out:
3383 	/* If we did no progress, the error (EMSGSIZE) is real */
3384 	if (skb->len == 0 && err)
3385 		return err;
3386 	return skb->len;
3387 }
3388 
3389 int tcf_exts_init_ex(struct tcf_exts *exts, struct net *net, int action,
3390 		     int police, struct tcf_proto *tp, u32 handle,
3391 		     bool use_action_miss)
3392 {
3393 	int err = 0;
3394 
3395 #ifdef CONFIG_NET_CLS_ACT
3396 	exts->type = 0;
3397 	exts->nr_actions = 0;
3398 	exts->miss_cookie_node = NULL;
3399 	/* Note: we do not own yet a reference on net.
3400 	 * This reference might be taken later from tcf_exts_get_net().
3401 	 */
3402 	exts->net = net;
3403 	exts->actions = kzalloc_objs(struct tc_action *, TCA_ACT_MAX_PRIO,
3404 				     GFP_KERNEL_ACCOUNT);
3405 	if (!exts->actions)
3406 		return -ENOMEM;
3407 #endif
3408 
3409 	exts->action = action;
3410 	exts->police = police;
3411 
3412 	if (!use_action_miss)
3413 		return 0;
3414 
3415 	err = tcf_exts_miss_cookie_base_alloc(exts, tp, handle);
3416 	if (err)
3417 		goto err_miss_alloc;
3418 
3419 	return 0;
3420 
3421 err_miss_alloc:
3422 	tcf_exts_destroy(exts);
3423 #ifdef CONFIG_NET_CLS_ACT
3424 	exts->actions = NULL;
3425 #endif
3426 	return err;
3427 }
3428 EXPORT_SYMBOL(tcf_exts_init_ex);
3429 
3430 void tcf_exts_destroy(struct tcf_exts *exts)
3431 {
3432 	tcf_exts_miss_cookie_base_destroy(exts);
3433 
3434 #ifdef CONFIG_NET_CLS_ACT
3435 	if (exts->actions) {
3436 		tcf_action_destroy(exts->actions, TCA_ACT_UNBIND);
3437 		kfree(exts->actions);
3438 	}
3439 	exts->nr_actions = 0;
3440 #endif
3441 }
3442 EXPORT_SYMBOL(tcf_exts_destroy);
3443 
3444 int tcf_exts_validate_ex(struct net *net, struct tcf_proto *tp, struct nlattr **tb,
3445 			 struct nlattr *rate_tlv, struct tcf_exts *exts,
3446 			 u32 flags, u32 fl_flags, struct netlink_ext_ack *extack)
3447 {
3448 #ifdef CONFIG_NET_CLS_ACT
3449 	{
3450 		int init_res[TCA_ACT_MAX_PRIO] = {};
3451 		struct tc_action *act;
3452 		size_t attr_size = 0;
3453 
3454 		if (exts->police && tb[exts->police]) {
3455 			struct tc_action_ops *a_o;
3456 
3457 			flags |= TCA_ACT_FLAGS_POLICE | TCA_ACT_FLAGS_BIND;
3458 			a_o = tc_action_load_ops(tb[exts->police], flags,
3459 						 extack);
3460 			if (IS_ERR(a_o))
3461 				return PTR_ERR(a_o);
3462 			act = tcf_action_init_1(net, tp, tb[exts->police],
3463 						rate_tlv, a_o, init_res, flags,
3464 						extack);
3465 			module_put(a_o->owner);
3466 			if (IS_ERR(act))
3467 				return PTR_ERR(act);
3468 
3469 			act->type = exts->type = TCA_OLD_COMPAT;
3470 			exts->actions[0] = act;
3471 			exts->nr_actions = 1;
3472 			tcf_idr_insert_many(exts->actions, init_res);
3473 		} else if (exts->action && tb[exts->action]) {
3474 			int err;
3475 
3476 			flags |= TCA_ACT_FLAGS_BIND;
3477 			err = tcf_action_init(net, tp, tb[exts->action],
3478 					      rate_tlv, exts->actions, init_res,
3479 					      &attr_size, flags, fl_flags,
3480 					      extack);
3481 			if (err < 0)
3482 				return err;
3483 			exts->nr_actions = err;
3484 		}
3485 	}
3486 #else
3487 	if ((exts->action && tb[exts->action]) ||
3488 	    (exts->police && tb[exts->police])) {
3489 		NL_SET_ERR_MSG(extack, "Classifier actions are not supported per compile options (CONFIG_NET_CLS_ACT)");
3490 		return -EOPNOTSUPP;
3491 	}
3492 #endif
3493 
3494 	return 0;
3495 }
3496 EXPORT_SYMBOL(tcf_exts_validate_ex);
3497 
3498 int tcf_exts_validate(struct net *net, struct tcf_proto *tp, struct nlattr **tb,
3499 		      struct nlattr *rate_tlv, struct tcf_exts *exts,
3500 		      u32 flags, struct netlink_ext_ack *extack)
3501 {
3502 	return tcf_exts_validate_ex(net, tp, tb, rate_tlv, exts,
3503 				    flags, 0, extack);
3504 }
3505 EXPORT_SYMBOL(tcf_exts_validate);
3506 
3507 void tcf_exts_change(struct tcf_exts *dst, struct tcf_exts *src)
3508 {
3509 #ifdef CONFIG_NET_CLS_ACT
3510 	struct tcf_exts old = *dst;
3511 
3512 	*dst = *src;
3513 	tcf_exts_destroy(&old);
3514 #endif
3515 }
3516 EXPORT_SYMBOL(tcf_exts_change);
3517 
3518 #ifdef CONFIG_NET_CLS_ACT
3519 static struct tc_action *tcf_exts_first_act(struct tcf_exts *exts)
3520 {
3521 	if (exts->nr_actions == 0)
3522 		return NULL;
3523 	else
3524 		return exts->actions[0];
3525 }
3526 #endif
3527 
3528 int tcf_exts_dump(struct sk_buff *skb, struct tcf_exts *exts)
3529 {
3530 #ifdef CONFIG_NET_CLS_ACT
3531 	struct nlattr *nest;
3532 
3533 	if (exts->action && tcf_exts_has_actions(exts)) {
3534 		/*
3535 		 * again for backward compatible mode - we want
3536 		 * to work with both old and new modes of entering
3537 		 * tc data even if iproute2  was newer - jhs
3538 		 */
3539 		if (exts->type != TCA_OLD_COMPAT) {
3540 			nest = nla_nest_start_noflag(skb, exts->action);
3541 			if (nest == NULL)
3542 				goto nla_put_failure;
3543 
3544 			if (tcf_action_dump(skb, exts->actions, 0, 0, false)
3545 			    < 0)
3546 				goto nla_put_failure;
3547 			if (nla_nest_end_safe(skb, nest) < 0)
3548 				goto nla_put_failure;
3549 		} else if (exts->police) {
3550 			struct tc_action *act = tcf_exts_first_act(exts);
3551 			nest = nla_nest_start_noflag(skb, exts->police);
3552 			if (nest == NULL || !act)
3553 				goto nla_put_failure;
3554 			if (tcf_action_dump_old(skb, act, 0, 0) < 0)
3555 				goto nla_put_failure;
3556 			if (nla_nest_end_safe(skb, nest) < 0)
3557 				goto nla_put_failure;
3558 		}
3559 	}
3560 	return 0;
3561 
3562 nla_put_failure:
3563 	nla_nest_cancel(skb, nest);
3564 	return -1;
3565 #else
3566 	return 0;
3567 #endif
3568 }
3569 EXPORT_SYMBOL(tcf_exts_dump);
3570 
3571 int tcf_exts_terse_dump(struct sk_buff *skb, struct tcf_exts *exts)
3572 {
3573 #ifdef CONFIG_NET_CLS_ACT
3574 	struct nlattr *nest;
3575 
3576 	if (!exts->action || !tcf_exts_has_actions(exts))
3577 		return 0;
3578 
3579 	nest = nla_nest_start_noflag(skb, exts->action);
3580 	if (!nest)
3581 		goto nla_put_failure;
3582 
3583 	if (tcf_action_dump(skb, exts->actions, 0, 0, true) < 0)
3584 		goto nla_put_failure;
3585 	if (nla_nest_end_safe(skb, nest) < 0)
3586 		goto nla_put_failure;
3587 	return 0;
3588 
3589 nla_put_failure:
3590 	nla_nest_cancel(skb, nest);
3591 	return -1;
3592 #else
3593 	return 0;
3594 #endif
3595 }
3596 EXPORT_SYMBOL(tcf_exts_terse_dump);
3597 
3598 int tcf_exts_dump_stats(struct sk_buff *skb, struct tcf_exts *exts)
3599 {
3600 #ifdef CONFIG_NET_CLS_ACT
3601 	struct tc_action *a = tcf_exts_first_act(exts);
3602 	if (a != NULL && tcf_action_copy_stats(skb, a, 1) < 0)
3603 		return -1;
3604 #endif
3605 	return 0;
3606 }
3607 EXPORT_SYMBOL(tcf_exts_dump_stats);
3608 
3609 static void tcf_block_offload_inc(struct tcf_block *block, u32 *flags)
3610 {
3611 	if (*flags & TCA_CLS_FLAGS_IN_HW)
3612 		return;
3613 	*flags |= TCA_CLS_FLAGS_IN_HW;
3614 	atomic_inc(&block->offloadcnt);
3615 }
3616 
3617 static void tcf_block_offload_dec(struct tcf_block *block, u32 *flags)
3618 {
3619 	if (!(*flags & TCA_CLS_FLAGS_IN_HW))
3620 		return;
3621 	*flags &= ~TCA_CLS_FLAGS_IN_HW;
3622 	atomic_dec(&block->offloadcnt);
3623 }
3624 
3625 static void tc_cls_offload_cnt_update(struct tcf_block *block,
3626 				      struct tcf_proto *tp, u32 *cnt,
3627 				      u32 *flags, u32 diff, bool add)
3628 {
3629 	lockdep_assert_held(&block->cb_lock);
3630 
3631 	spin_lock(&tp->lock);
3632 	if (add) {
3633 		if (!*cnt)
3634 			tcf_block_offload_inc(block, flags);
3635 		*cnt += diff;
3636 	} else {
3637 		*cnt -= diff;
3638 		if (!*cnt)
3639 			tcf_block_offload_dec(block, flags);
3640 	}
3641 	spin_unlock(&tp->lock);
3642 }
3643 
3644 static void
3645 tc_cls_offload_cnt_reset(struct tcf_block *block, struct tcf_proto *tp,
3646 			 u32 *cnt, u32 *flags)
3647 {
3648 	lockdep_assert_held(&block->cb_lock);
3649 
3650 	spin_lock(&tp->lock);
3651 	tcf_block_offload_dec(block, flags);
3652 	*cnt = 0;
3653 	spin_unlock(&tp->lock);
3654 }
3655 
3656 static int
3657 __tc_setup_cb_call(struct tcf_block *block, enum tc_setup_type type,
3658 		   void *type_data, bool err_stop)
3659 {
3660 	struct flow_block_cb *block_cb;
3661 	int ok_count = 0;
3662 	int err;
3663 
3664 	list_for_each_entry(block_cb, &block->flow_block.cb_list, list) {
3665 		err = block_cb->cb(type, type_data, block_cb->cb_priv);
3666 		if (err) {
3667 			if (err_stop)
3668 				return err;
3669 		} else {
3670 			ok_count++;
3671 		}
3672 	}
3673 	return ok_count;
3674 }
3675 
3676 int tc_setup_cb_call(struct tcf_block *block, enum tc_setup_type type,
3677 		     void *type_data, bool err_stop, bool rtnl_held)
3678 {
3679 	bool take_rtnl = READ_ONCE(block->lockeddevcnt) && !rtnl_held;
3680 	int ok_count;
3681 
3682 retry:
3683 	if (take_rtnl)
3684 		rtnl_lock();
3685 	down_read(&block->cb_lock);
3686 	/* Need to obtain rtnl lock if block is bound to devs that require it.
3687 	 * In block bind code cb_lock is obtained while holding rtnl, so we must
3688 	 * obtain the locks in same order here.
3689 	 */
3690 	if (!rtnl_held && !take_rtnl && block->lockeddevcnt) {
3691 		up_read(&block->cb_lock);
3692 		take_rtnl = true;
3693 		goto retry;
3694 	}
3695 
3696 	ok_count = __tc_setup_cb_call(block, type, type_data, err_stop);
3697 
3698 	up_read(&block->cb_lock);
3699 	if (take_rtnl)
3700 		rtnl_unlock();
3701 	return ok_count;
3702 }
3703 EXPORT_SYMBOL(tc_setup_cb_call);
3704 
3705 /* Non-destructive filter add. If filter that wasn't already in hardware is
3706  * successfully offloaded, increment block offloads counter. On failure,
3707  * previously offloaded filter is considered to be intact and offloads counter
3708  * is not decremented.
3709  */
3710 
3711 int tc_setup_cb_add(struct tcf_block *block, struct tcf_proto *tp,
3712 		    enum tc_setup_type type, void *type_data, bool err_stop,
3713 		    u32 *flags, unsigned int *in_hw_count, bool rtnl_held)
3714 {
3715 	bool take_rtnl = READ_ONCE(block->lockeddevcnt) && !rtnl_held;
3716 	int ok_count;
3717 
3718 retry:
3719 	if (take_rtnl)
3720 		rtnl_lock();
3721 	down_read(&block->cb_lock);
3722 	/* Need to obtain rtnl lock if block is bound to devs that require it.
3723 	 * In block bind code cb_lock is obtained while holding rtnl, so we must
3724 	 * obtain the locks in same order here.
3725 	 */
3726 	if (!rtnl_held && !take_rtnl && block->lockeddevcnt) {
3727 		up_read(&block->cb_lock);
3728 		take_rtnl = true;
3729 		goto retry;
3730 	}
3731 
3732 	/* Make sure all netdevs sharing this block are offload-capable. */
3733 	if (block->nooffloaddevcnt && err_stop) {
3734 		ok_count = -EOPNOTSUPP;
3735 		goto err_unlock;
3736 	}
3737 
3738 	ok_count = __tc_setup_cb_call(block, type, type_data, err_stop);
3739 	if (ok_count < 0)
3740 		goto err_unlock;
3741 
3742 	if (tp->ops->hw_add)
3743 		tp->ops->hw_add(tp, type_data);
3744 	if (ok_count > 0)
3745 		tc_cls_offload_cnt_update(block, tp, in_hw_count, flags,
3746 					  ok_count, true);
3747 err_unlock:
3748 	up_read(&block->cb_lock);
3749 	if (take_rtnl)
3750 		rtnl_unlock();
3751 	return min(ok_count, 0);
3752 }
3753 EXPORT_SYMBOL(tc_setup_cb_add);
3754 
3755 /* Destructive filter replace. If filter that wasn't already in hardware is
3756  * successfully offloaded, increment block offload counter. On failure,
3757  * previously offloaded filter is considered to be destroyed and offload counter
3758  * is decremented.
3759  */
3760 
3761 int tc_setup_cb_replace(struct tcf_block *block, struct tcf_proto *tp,
3762 			enum tc_setup_type type, void *type_data, bool err_stop,
3763 			u32 *old_flags, unsigned int *old_in_hw_count,
3764 			u32 *new_flags, unsigned int *new_in_hw_count,
3765 			bool rtnl_held)
3766 {
3767 	bool take_rtnl = READ_ONCE(block->lockeddevcnt) && !rtnl_held;
3768 	int ok_count;
3769 
3770 retry:
3771 	if (take_rtnl)
3772 		rtnl_lock();
3773 	down_read(&block->cb_lock);
3774 	/* Need to obtain rtnl lock if block is bound to devs that require it.
3775 	 * In block bind code cb_lock is obtained while holding rtnl, so we must
3776 	 * obtain the locks in same order here.
3777 	 */
3778 	if (!rtnl_held && !take_rtnl && block->lockeddevcnt) {
3779 		up_read(&block->cb_lock);
3780 		take_rtnl = true;
3781 		goto retry;
3782 	}
3783 
3784 	/* Make sure all netdevs sharing this block are offload-capable. */
3785 	if (block->nooffloaddevcnt && err_stop) {
3786 		ok_count = -EOPNOTSUPP;
3787 		goto err_unlock;
3788 	}
3789 
3790 	tc_cls_offload_cnt_reset(block, tp, old_in_hw_count, old_flags);
3791 	if (tp->ops->hw_del)
3792 		tp->ops->hw_del(tp, type_data);
3793 
3794 	ok_count = __tc_setup_cb_call(block, type, type_data, err_stop);
3795 	if (ok_count < 0)
3796 		goto err_unlock;
3797 
3798 	if (tp->ops->hw_add)
3799 		tp->ops->hw_add(tp, type_data);
3800 	if (ok_count > 0)
3801 		tc_cls_offload_cnt_update(block, tp, new_in_hw_count,
3802 					  new_flags, ok_count, true);
3803 err_unlock:
3804 	up_read(&block->cb_lock);
3805 	if (take_rtnl)
3806 		rtnl_unlock();
3807 	return min(ok_count, 0);
3808 }
3809 EXPORT_SYMBOL(tc_setup_cb_replace);
3810 
3811 /* Destroy filter and decrement block offload counter, if filter was previously
3812  * offloaded.
3813  */
3814 
3815 int tc_setup_cb_destroy(struct tcf_block *block, struct tcf_proto *tp,
3816 			enum tc_setup_type type, void *type_data, bool err_stop,
3817 			u32 *flags, unsigned int *in_hw_count, bool rtnl_held)
3818 {
3819 	bool take_rtnl = READ_ONCE(block->lockeddevcnt) && !rtnl_held;
3820 	int ok_count;
3821 
3822 retry:
3823 	if (take_rtnl)
3824 		rtnl_lock();
3825 	down_read(&block->cb_lock);
3826 	/* Need to obtain rtnl lock if block is bound to devs that require it.
3827 	 * In block bind code cb_lock is obtained while holding rtnl, so we must
3828 	 * obtain the locks in same order here.
3829 	 */
3830 	if (!rtnl_held && !take_rtnl && block->lockeddevcnt) {
3831 		up_read(&block->cb_lock);
3832 		take_rtnl = true;
3833 		goto retry;
3834 	}
3835 
3836 	ok_count = __tc_setup_cb_call(block, type, type_data, err_stop);
3837 
3838 	tc_cls_offload_cnt_reset(block, tp, in_hw_count, flags);
3839 	if (tp->ops->hw_del)
3840 		tp->ops->hw_del(tp, type_data);
3841 
3842 	up_read(&block->cb_lock);
3843 	if (take_rtnl)
3844 		rtnl_unlock();
3845 	return min(ok_count, 0);
3846 }
3847 EXPORT_SYMBOL(tc_setup_cb_destroy);
3848 
3849 int tc_setup_cb_reoffload(struct tcf_block *block, struct tcf_proto *tp,
3850 			  bool add, flow_setup_cb_t *cb,
3851 			  enum tc_setup_type type, void *type_data,
3852 			  void *cb_priv, u32 *flags, unsigned int *in_hw_count)
3853 {
3854 	int err = cb(type, type_data, cb_priv);
3855 
3856 	if (err) {
3857 		if (add && tc_skip_sw(*flags))
3858 			return err;
3859 	} else {
3860 		tc_cls_offload_cnt_update(block, tp, in_hw_count, flags, 1,
3861 					  add);
3862 	}
3863 
3864 	return 0;
3865 }
3866 EXPORT_SYMBOL(tc_setup_cb_reoffload);
3867 
3868 static int tcf_act_get_user_cookie(struct flow_action_entry *entry,
3869 				   const struct tc_action *act)
3870 {
3871 	struct tc_cookie *user_cookie;
3872 	int err = 0;
3873 
3874 	rcu_read_lock();
3875 	user_cookie = rcu_dereference(act->user_cookie);
3876 	if (user_cookie) {
3877 		entry->user_cookie = flow_action_cookie_create(user_cookie->data,
3878 							       user_cookie->len,
3879 							       GFP_ATOMIC);
3880 		if (!entry->user_cookie)
3881 			err = -ENOMEM;
3882 	}
3883 	rcu_read_unlock();
3884 	return err;
3885 }
3886 
3887 static void tcf_act_put_user_cookie(struct flow_action_entry *entry)
3888 {
3889 	flow_action_cookie_destroy(entry->user_cookie);
3890 }
3891 
3892 void tc_cleanup_offload_action(struct flow_action *flow_action)
3893 {
3894 	struct flow_action_entry *entry;
3895 	int i;
3896 
3897 	flow_action_for_each(i, entry, flow_action) {
3898 		tcf_act_put_user_cookie(entry);
3899 		if (entry->destructor)
3900 			entry->destructor(entry->destructor_priv);
3901 	}
3902 }
3903 EXPORT_SYMBOL(tc_cleanup_offload_action);
3904 
3905 static int tc_setup_offload_act(struct tc_action *act,
3906 				struct flow_action_entry *entry,
3907 				u32 *index_inc,
3908 				struct netlink_ext_ack *extack)
3909 {
3910 #ifdef CONFIG_NET_CLS_ACT
3911 	if (act->ops->offload_act_setup) {
3912 		return act->ops->offload_act_setup(act, entry, index_inc, true,
3913 						   extack);
3914 	} else {
3915 		NL_SET_ERR_MSG(extack, "Action does not support offload");
3916 		return -EOPNOTSUPP;
3917 	}
3918 #else
3919 	return 0;
3920 #endif
3921 }
3922 
3923 int tc_setup_action(struct flow_action *flow_action,
3924 		    struct tc_action *actions[],
3925 		    u32 miss_cookie_base,
3926 		    struct netlink_ext_ack *extack)
3927 {
3928 	int i, j, k, index, err = 0;
3929 	struct tc_action *act;
3930 
3931 	BUILD_BUG_ON(TCA_ACT_HW_STATS_ANY != FLOW_ACTION_HW_STATS_ANY);
3932 	BUILD_BUG_ON(TCA_ACT_HW_STATS_IMMEDIATE != FLOW_ACTION_HW_STATS_IMMEDIATE);
3933 	BUILD_BUG_ON(TCA_ACT_HW_STATS_DELAYED != FLOW_ACTION_HW_STATS_DELAYED);
3934 
3935 	if (!actions)
3936 		return 0;
3937 
3938 	j = 0;
3939 	tcf_act_for_each_action(i, act, actions) {
3940 		struct flow_action_entry *entry;
3941 
3942 		entry = &flow_action->entries[j];
3943 		spin_lock_bh(&act->tcfa_lock);
3944 
3945 		/* Abort the offload if we have exhausted the allocated capacity */
3946 		if (j >= flow_action->num_entries) {
3947 			NL_SET_ERR_MSG_MOD(extack, "Flow action buffer overflow");
3948 			err = -ENOSPC;
3949 			goto err_out_locked;
3950 		}
3951 
3952 		err = tcf_act_get_user_cookie(entry, act);
3953 		if (err)
3954 			goto err_out_locked;
3955 
3956 		index = flow_action->num_entries - j;
3957 		err = tc_setup_offload_act(act, entry, &index,
3958 					   extack);
3959 		if (err)
3960 			goto err_out_locked;
3961 
3962 		for (k = 0; k < index ; k++) {
3963 			entry[k].hw_stats = tc_act_hw_stats(act->hw_stats);
3964 			entry[k].hw_index = act->tcfa_index;
3965 			entry[k].cookie = (unsigned long)act;
3966 			entry[k].miss_cookie =
3967 				tcf_exts_miss_cookie_get(miss_cookie_base, i);
3968 		}
3969 
3970 		j += index;
3971 
3972 		spin_unlock_bh(&act->tcfa_lock);
3973 	}
3974 
3975 err_out:
3976 	if (err)
3977 		tc_cleanup_offload_action(flow_action);
3978 
3979 	return err;
3980 err_out_locked:
3981 	spin_unlock_bh(&act->tcfa_lock);
3982 	goto err_out;
3983 }
3984 
3985 int tc_setup_offload_action(struct flow_action *flow_action,
3986 			    const struct tcf_exts *exts,
3987 			    struct netlink_ext_ack *extack)
3988 {
3989 #ifdef CONFIG_NET_CLS_ACT
3990 	u32 miss_cookie_base;
3991 
3992 	if (!exts)
3993 		return 0;
3994 
3995 	miss_cookie_base = exts->miss_cookie_node ?
3996 			   exts->miss_cookie_node->miss_cookie_base : 0;
3997 	return tc_setup_action(flow_action, exts->actions, miss_cookie_base,
3998 			       extack);
3999 #else
4000 	return 0;
4001 #endif
4002 }
4003 EXPORT_SYMBOL(tc_setup_offload_action);
4004 
4005 unsigned int tcf_exts_num_actions(struct tcf_exts *exts)
4006 {
4007 	unsigned int num_acts = 0;
4008 	struct tc_action *act;
4009 	int i;
4010 
4011 	tcf_exts_for_each_action(i, act, exts) {
4012 		if (is_tcf_pedit(act)) {
4013 			spin_lock_bh(&act->tcfa_lock);
4014 			num_acts += tcf_pedit_nkeys_locked(act);
4015 			spin_unlock_bh(&act->tcfa_lock);
4016 		} else {
4017 			num_acts++;
4018 		}
4019 	}
4020 	return num_acts;
4021 }
4022 EXPORT_SYMBOL(tcf_exts_num_actions);
4023 
4024 #ifdef CONFIG_NET_CLS_ACT
4025 static int tcf_qevent_parse_block_index(struct nlattr *block_index_attr,
4026 					u32 *p_block_index,
4027 					struct netlink_ext_ack *extack)
4028 {
4029 	*p_block_index = nla_get_u32(block_index_attr);
4030 	if (!*p_block_index) {
4031 		NL_SET_ERR_MSG(extack, "Block number may not be zero");
4032 		return -EINVAL;
4033 	}
4034 
4035 	return 0;
4036 }
4037 
4038 int tcf_qevent_init(struct tcf_qevent *qe, struct Qdisc *sch,
4039 		    enum flow_block_binder_type binder_type,
4040 		    struct nlattr *block_index_attr,
4041 		    struct netlink_ext_ack *extack)
4042 {
4043 	u32 block_index;
4044 	int err;
4045 
4046 	if (!block_index_attr)
4047 		return 0;
4048 
4049 	err = tcf_qevent_parse_block_index(block_index_attr, &block_index, extack);
4050 	if (err)
4051 		return err;
4052 
4053 	qe->info.binder_type = binder_type;
4054 	qe->info.chain_head_change = tcf_chain_head_change_dflt;
4055 	qe->info.chain_head_change_priv = &qe->filter_chain;
4056 	qe->info.block_index = block_index;
4057 
4058 	return tcf_block_get_ext(&qe->block, sch, &qe->info, extack);
4059 }
4060 EXPORT_SYMBOL(tcf_qevent_init);
4061 
4062 void tcf_qevent_destroy(struct tcf_qevent *qe, struct Qdisc *sch)
4063 {
4064 	if (qe->info.block_index)
4065 		tcf_block_put_ext(qe->block, sch, &qe->info);
4066 }
4067 EXPORT_SYMBOL(tcf_qevent_destroy);
4068 
4069 int tcf_qevent_validate_change(struct tcf_qevent *qe, struct nlattr *block_index_attr,
4070 			       struct netlink_ext_ack *extack)
4071 {
4072 	u32 block_index;
4073 	int err;
4074 
4075 	if (!block_index_attr)
4076 		return 0;
4077 
4078 	err = tcf_qevent_parse_block_index(block_index_attr, &block_index, extack);
4079 	if (err)
4080 		return err;
4081 
4082 	/* Bounce newly-configured block or change in block. */
4083 	if (block_index != qe->info.block_index) {
4084 		NL_SET_ERR_MSG(extack, "Change of blocks is not supported");
4085 		return -EINVAL;
4086 	}
4087 
4088 	return 0;
4089 }
4090 EXPORT_SYMBOL(tcf_qevent_validate_change);
4091 
4092 struct sk_buff *tcf_qevent_handle(struct tcf_qevent *qe, struct Qdisc *sch, struct sk_buff *skb,
4093 				  struct sk_buff **to_free, int *ret)
4094 {
4095 	struct tcf_result cl_res;
4096 	struct tcf_proto *fl;
4097 
4098 	if (!qe->info.block_index)
4099 		return skb;
4100 
4101 	fl = rcu_dereference_bh(qe->filter_chain);
4102 
4103 	switch (tcf_classify_qdisc(skb, fl, &cl_res, false)) {
4104 	case TC_ACT_SHOT:
4105 		qdisc_qstats_drop(sch);
4106 		__qdisc_drop(skb, to_free);
4107 		*ret = __NET_XMIT_BYPASS;
4108 		return NULL;
4109 	case TC_ACT_STOLEN:
4110 	case TC_ACT_QUEUED:
4111 	case TC_ACT_TRAP:
4112 		__qdisc_drop(skb, to_free);
4113 		*ret = __NET_XMIT_STOLEN;
4114 		return NULL;
4115 	case TC_ACT_CONSUMED:
4116 		*ret = __NET_XMIT_STOLEN;
4117 		return NULL;
4118 	}
4119 
4120 	return skb;
4121 }
4122 EXPORT_SYMBOL(tcf_qevent_handle);
4123 
4124 int tcf_qevent_dump(struct sk_buff *skb, int attr_name, struct tcf_qevent *qe)
4125 {
4126 	if (!qe->info.block_index)
4127 		return 0;
4128 	return nla_put_u32(skb, attr_name, qe->info.block_index);
4129 }
4130 EXPORT_SYMBOL(tcf_qevent_dump);
4131 #endif
4132 
4133 static __net_init int tcf_net_init(struct net *net)
4134 {
4135 	struct tcf_net *tn = net_generic(net, tcf_net_id);
4136 
4137 	spin_lock_init(&tn->idr_lock);
4138 	idr_init(&tn->idr);
4139 	return 0;
4140 }
4141 
4142 static void __net_exit tcf_net_exit(struct net *net)
4143 {
4144 	struct tcf_net *tn = net_generic(net, tcf_net_id);
4145 
4146 	idr_destroy(&tn->idr);
4147 }
4148 
4149 static struct pernet_operations tcf_net_ops = {
4150 	.init = tcf_net_init,
4151 	.exit = tcf_net_exit,
4152 	.id   = &tcf_net_id,
4153 	.size = sizeof(struct tcf_net),
4154 };
4155 
4156 static const struct rtnl_msg_handler tc_filter_rtnl_msg_handlers[] __initconst = {
4157 	{.msgtype = RTM_NEWTFILTER, .doit = tc_new_tfilter,
4158 	 .flags = RTNL_FLAG_DOIT_UNLOCKED},
4159 	{.msgtype = RTM_DELTFILTER, .doit = tc_del_tfilter,
4160 	 .flags = RTNL_FLAG_DOIT_UNLOCKED},
4161 	{.msgtype = RTM_GETTFILTER, .doit = tc_get_tfilter,
4162 	 .dumpit = tc_dump_tfilter, .flags = RTNL_FLAG_DOIT_UNLOCKED},
4163 	{.msgtype = RTM_NEWCHAIN, .doit = tc_ctl_chain},
4164 	{.msgtype = RTM_DELCHAIN, .doit = tc_ctl_chain},
4165 	{.msgtype = RTM_GETCHAIN, .doit = tc_ctl_chain,
4166 	 .dumpit = tc_dump_chain},
4167 };
4168 
4169 static int __init tc_filter_init(void)
4170 {
4171 	int err;
4172 
4173 	tc_filter_wq = alloc_ordered_workqueue("tc_filter_workqueue", 0);
4174 	if (!tc_filter_wq)
4175 		return -ENOMEM;
4176 
4177 	err = register_pernet_subsys(&tcf_net_ops);
4178 	if (err)
4179 		goto err_register_pernet_subsys;
4180 
4181 	xa_init_flags(&tcf_exts_miss_cookies_xa, XA_FLAGS_ALLOC1);
4182 	rtnl_register_many(tc_filter_rtnl_msg_handlers);
4183 
4184 	return 0;
4185 
4186 err_register_pernet_subsys:
4187 	destroy_workqueue(tc_filter_wq);
4188 	return err;
4189 }
4190 
4191 subsys_initcall(tc_filter_init);
4192