xref: /linux/net/ipv6/seg6_local.c (revision 8ae3f4067ba4ae3a15581392f6dac422e3d3def0)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  SR-IPv6 implementation
4  *
5  *  Authors:
6  *  David Lebrun <david.lebrun@uclouvain.be>
7  *  eBPF support: Mathieu Xhonneux <m.xhonneux@gmail.com>
8  */
9 
10 #include <linux/filter.h>
11 #include <linux/types.h>
12 #include <linux/skbuff.h>
13 #include <linux/net.h>
14 #include <linux/module.h>
15 #include <net/ip.h>
16 #include <net/lwtunnel.h>
17 #include <net/netevent.h>
18 #include <net/netns/generic.h>
19 #include <net/ip6_fib.h>
20 #include <net/route.h>
21 #include <net/seg6.h>
22 #include <linux/seg6.h>
23 #include <linux/seg6_local.h>
24 #include <net/addrconf.h>
25 #include <net/ip6_route.h>
26 #include <net/dst_cache.h>
27 #include <net/ip_tunnels.h>
28 #ifdef CONFIG_IPV6_SEG6_HMAC
29 #include <net/seg6_hmac.h>
30 #endif
31 #include <net/seg6_local.h>
32 #include <linux/etherdevice.h>
33 #include <linux/bpf.h>
34 #include <linux/netfilter.h>
35 
36 #define SEG6_F_ATTR(i)		BIT(i)
37 
38 struct seg6_local_lwt;
39 
40 /* callbacks used for customizing the creation and destruction of a behavior */
41 struct seg6_local_lwtunnel_ops {
42 	int (*build_state)(struct seg6_local_lwt *slwt, const void *cfg,
43 			   struct netlink_ext_ack *extack);
44 	void (*destroy_state)(struct seg6_local_lwt *slwt);
45 };
46 
47 struct seg6_action_desc {
48 	int action;
49 	unsigned long attrs;
50 
51 	/* The optattrs field is used for specifying all the optional
52 	 * attributes supported by a specific behavior.
53 	 * It means that if one of these attributes is not provided in the
54 	 * netlink message during the behavior creation, no errors will be
55 	 * returned to the userspace.
56 	 *
57 	 * Each attribute can be only of two types (mutually exclusive):
58 	 * 1) required or 2) optional.
59 	 * Every user MUST obey to this rule! If you set an attribute as
60 	 * required the same attribute CANNOT be set as optional and vice
61 	 * versa.
62 	 */
63 	unsigned long optattrs;
64 
65 	int (*input)(struct sk_buff *skb, struct seg6_local_lwt *slwt);
66 	int static_headroom;
67 
68 	struct seg6_local_lwtunnel_ops slwt_ops;
69 };
70 
71 struct bpf_lwt_prog {
72 	struct bpf_prog *prog;
73 	char *name;
74 };
75 
76 /* default length values (expressed in bits) for both Locator-Block and
77  * Locator-Node Function.
78  *
79  * Both SEG6_LOCAL_LCBLOCK_DBITS and SEG6_LOCAL_LCNODE_FN_DBITS *must* be:
80  *    i) greater than 0;
81  *   ii) evenly divisible by 8. In other terms, the lengths of the
82  *	 Locator-Block and Locator-Node Function must be byte-aligned (we can
83  *	 relax this constraint in the future if really needed).
84  *
85  * Moreover, a third condition must hold:
86  *  iii) SEG6_LOCAL_LCBLOCK_DBITS + SEG6_LOCAL_LCNODE_FN_DBITS <= 128.
87  *
88  * The correctness of SEG6_LOCAL_LCBLOCK_DBITS and SEG6_LOCAL_LCNODE_FN_DBITS
89  * values are checked during the kernel compilation. If the compilation stops,
90  * check the value of these parameters to see if they meet conditions (i), (ii)
91  * and (iii).
92  */
93 #define SEG6_LOCAL_LCBLOCK_DBITS	32
94 #define SEG6_LOCAL_LCNODE_FN_DBITS	16
95 
96 /* The following next_csid_chk_{cntr,lcblock,lcblock_fn}_bits macros can be
97  * used directly to check whether the lengths (in bits) of Locator-Block and
98  * Locator-Node Function are valid according to (i), (ii), (iii).
99  */
100 #define next_csid_chk_cntr_bits(blen, flen)		\
101 	((blen) + (flen) > 128)
102 
103 #define next_csid_chk_lcblock_bits(blen)		\
104 ({							\
105 	typeof(blen) __tmp = blen;			\
106 	(!__tmp || __tmp > 120 || (__tmp & 0x07));	\
107 })
108 
109 #define next_csid_chk_lcnode_fn_bits(flen)		\
110 	next_csid_chk_lcblock_bits(flen)
111 
112 /* flag indicating that flavors are set up for a given End* behavior */
113 #define SEG6_F_LOCAL_FLAVORS		SEG6_F_ATTR(SEG6_LOCAL_FLAVORS)
114 
115 #define SEG6_F_LOCAL_FLV_OP(flvname)	BIT(SEG6_LOCAL_FLV_OP_##flvname)
116 #define SEG6_F_LOCAL_FLV_NEXT_CSID	SEG6_F_LOCAL_FLV_OP(NEXT_CSID)
117 #define SEG6_F_LOCAL_FLV_PSP		SEG6_F_LOCAL_FLV_OP(PSP)
118 
119 /* Supported RFC8986 Flavor operations are reported in this bitmask */
120 #define SEG6_LOCAL_FLV8986_SUPP_OPS	SEG6_F_LOCAL_FLV_PSP
121 
122 #define SEG6_LOCAL_END_FLV_SUPP_OPS	(SEG6_F_LOCAL_FLV_NEXT_CSID | \
123 					 SEG6_LOCAL_FLV8986_SUPP_OPS)
124 #define SEG6_LOCAL_END_X_FLV_SUPP_OPS	SEG6_F_LOCAL_FLV_NEXT_CSID
125 
126 struct seg6_flavors_info {
127 	/* Flavor operations */
128 	__u32 flv_ops;
129 
130 	/* Locator-Block length, expressed in bits */
131 	__u8 lcblock_bits;
132 	/* Locator-Node Function length, expressed in bits*/
133 	__u8 lcnode_func_bits;
134 };
135 
136 enum seg6_end_dt_mode {
137 	DT_INVALID_MODE	= -EINVAL,
138 	DT_LEGACY_MODE	= 0,
139 	DT_VRF_MODE	= 1,
140 };
141 
142 struct seg6_end_dt_info {
143 	enum seg6_end_dt_mode mode;
144 
145 	struct net *net;
146 	/* VRF device associated to the routing table used by the SRv6
147 	 * End.DT4/DT6 behavior for routing IPv4/IPv6 packets.
148 	 */
149 	int vrf_ifindex;
150 	int vrf_table;
151 
152 	/* tunneled packet family (IPv4 or IPv6).
153 	 * Protocol and header length are inferred from family.
154 	 */
155 	u16 family;
156 };
157 
158 struct pcpu_seg6_local_counters {
159 	u64_stats_t packets;
160 	u64_stats_t bytes;
161 	u64_stats_t errors;
162 
163 	struct u64_stats_sync syncp;
164 };
165 
166 /* This struct groups all the SRv6 Behavior counters supported so far.
167  *
168  * put_nla_counters() makes use of this data structure to collect all counter
169  * values after the per-CPU counter evaluation has been performed.
170  * Finally, each counter value (in seg6_local_counters) is stored in the
171  * corresponding netlink attribute and sent to user space.
172  *
173  * NB: we don't want to expose this structure to user space!
174  */
175 struct seg6_local_counters {
176 	__u64 packets;
177 	__u64 bytes;
178 	__u64 errors;
179 };
180 
181 #define seg6_local_alloc_pcpu_counters(__gfp)				\
182 	__netdev_alloc_pcpu_stats(struct pcpu_seg6_local_counters,	\
183 				  ((__gfp) | __GFP_ZERO))
184 
185 #define SEG6_F_LOCAL_COUNTERS	SEG6_F_ATTR(SEG6_LOCAL_COUNTERS)
186 
187 struct seg6_local_lwt {
188 	int action;
189 	struct ipv6_sr_hdr *srh;
190 	int table;
191 	struct in_addr nh4;
192 	struct in6_addr nh6;
193 	int iif;
194 	int oif;
195 	struct bpf_lwt_prog bpf;
196 #ifdef CONFIG_NET_L3_MASTER_DEV
197 	struct seg6_end_dt_info dt_info;
198 #endif
199 	struct seg6_flavors_info flv_info;
200 
201 	struct pcpu_seg6_local_counters __percpu *pcpu_counters;
202 
203 	int headroom;
204 	struct seg6_action_desc *desc;
205 	/* unlike the required attrs, we have to track the optional attributes
206 	 * that have been effectively parsed.
207 	 */
208 	unsigned long parsed_optattrs;
209 };
210 
211 static struct seg6_local_lwt *seg6_local_lwtunnel(struct lwtunnel_state *lwt)
212 {
213 	return (struct seg6_local_lwt *)lwt->data;
214 }
215 
216 static struct ipv6_sr_hdr *get_and_validate_srh(struct sk_buff *skb)
217 {
218 	struct ipv6_sr_hdr *srh;
219 
220 	srh = seg6_get_srh(skb, IP6_FH_F_SKIP_RH);
221 	if (!srh)
222 		return NULL;
223 
224 #ifdef CONFIG_IPV6_SEG6_HMAC
225 	if (!seg6_hmac_validate_skb(skb))
226 		return NULL;
227 #endif
228 
229 	return srh;
230 }
231 
232 static bool decap_and_validate(struct sk_buff *skb, int proto)
233 {
234 	struct ipv6_sr_hdr *srh;
235 	unsigned int off = 0;
236 
237 	srh = seg6_get_srh(skb, 0);
238 	if (srh && srh->segments_left > 0)
239 		return false;
240 
241 #ifdef CONFIG_IPV6_SEG6_HMAC
242 	if (srh && !seg6_hmac_validate_skb(skb))
243 		return false;
244 #endif
245 
246 	if (ipv6_find_hdr(skb, &off, proto, NULL, NULL) < 0)
247 		return false;
248 
249 	if (!pskb_pull(skb, off))
250 		return false;
251 
252 	skb_postpull_rcsum(skb, skb_network_header(skb), off);
253 
254 	skb_reset_network_header(skb);
255 	skb_reset_transport_header(skb);
256 	if (iptunnel_pull_offloads(skb))
257 		return false;
258 
259 	if (proto == IPPROTO_IPIP) {
260 		bool l3slave = ipv6_l3mdev_skb(IP6CB(skb)->flags);
261 		int iif = IP6CB(skb)->iif;
262 
263 		memset(IPCB(skb), 0, sizeof(*IPCB(skb)));
264 		IPCB(skb)->iif = iif;
265 		if (l3slave)
266 			IPCB(skb)->flags |= IPSKB_L3SLAVE;
267 	} else if (proto == IPPROTO_IPV6) {
268 		bool l3slave = ipv6_l3mdev_skb(IP6CB(skb)->flags);
269 		int iif = IP6CB(skb)->iif;
270 
271 		memset(IP6CB(skb), 0, sizeof(*IP6CB(skb)));
272 		IP6CB(skb)->iif = iif;
273 		IP6CB(skb)->nhoff = offsetof(struct ipv6hdr, nexthdr);
274 		if (l3slave)
275 			IP6CB(skb)->flags |= IP6SKB_L3SLAVE;
276 	}
277 
278 	return true;
279 }
280 
281 /* advance the SRH to the next segment and set the IPv6 DA accordingly.
282  * skb pointers may change: after this call, the caller must evaluate again
283  * any pointer into the packet data.
284  *
285  * This function returns:
286  *  - the SRH on success;
287  *  - NULL when the skb cannot be made writable. In this case, the function
288  *    sets the drop reason to SKB_DROP_REASON_NOMEM.
289  */
290 static struct ipv6_sr_hdr *advance_nextseg(struct sk_buff *skb,
291 					   struct ipv6_sr_hdr *srh,
292 					   enum skb_drop_reason *reason)
293 {
294 	struct in6_addr *addr;
295 	int srhoff;
296 	int wlen;
297 
298 	srhoff = (unsigned char *)srh - skb->data;
299 	/* we write only the Segment Left field and the IPv6 DA. The segment
300 	 * list is only read, and seg6_get_srh() already pulled it into the
301 	 * linear area.
302 	 */
303 	wlen = srhoff + sizeof(*srh);
304 
305 	if (unlikely(skb_ensure_writable(skb, wlen))) {
306 		*reason = SKB_DROP_REASON_NOMEM;
307 		return NULL;
308 	}
309 
310 	/* skb_ensure_writable() may change skb pointers; evaluate srh again */
311 	srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
312 
313 	srh->segments_left--;
314 	addr = srh->segments + srh->segments_left;
315 	ipv6_hdr(skb)->daddr = *addr;
316 
317 	return srh;
318 }
319 
320 static int
321 seg6_lookup_any_nexthop(struct sk_buff *skb, struct in6_addr *nhaddr,
322 			u32 tbl_id, bool local_delivery, int oif)
323 {
324 	struct net *net = dev_net(skb->dev);
325 	struct ipv6hdr *hdr = ipv6_hdr(skb);
326 	int flags = RT6_LOOKUP_F_HAS_SADDR;
327 	struct dst_entry *dst = NULL;
328 	struct rt6_info *rt;
329 	struct flowi6 fl6;
330 	int dev_flags = 0;
331 
332 	memset(&fl6, 0, sizeof(fl6));
333 	fl6.flowi6_iif = skb->dev->ifindex;
334 	fl6.flowi6_oif = oif;
335 	fl6.daddr = nhaddr ? *nhaddr : hdr->daddr;
336 	fl6.saddr = hdr->saddr;
337 	fl6.flowlabel = ip6_flowinfo(hdr);
338 	fl6.flowi6_mark = skb->mark;
339 	fl6.flowi6_proto = hdr->nexthdr;
340 
341 	if (nhaddr)
342 		fl6.flowi6_flags = FLOWI_FLAG_KNOWN_NH;
343 
344 	if (!tbl_id && !oif) {
345 		dst = ip6_route_input_lookup(net, skb->dev, &fl6, skb, flags);
346 	} else if (tbl_id) {
347 		struct fib6_table *table;
348 
349 		table = fib6_get_table(net, tbl_id);
350 		if (!table)
351 			goto out;
352 
353 		rt = ip6_pol_route(net, table, oif, &fl6, skb, flags);
354 		dst = &rt->dst;
355 	} else {
356 		dst = ip6_route_output(net, NULL, &fl6);
357 	}
358 
359 	/* we want to discard traffic destined for local packet processing,
360 	 * if @local_delivery is set to false.
361 	 */
362 	if (!local_delivery)
363 		dev_flags |= IFF_LOOPBACK;
364 
365 	if (dst && (dst_dev(dst)->flags & dev_flags) && !dst->error) {
366 		dst_release(dst);
367 		dst = NULL;
368 	}
369 
370 out:
371 	if (!dst) {
372 		rt = net->ipv6.ip6_blk_hole_entry;
373 		dst = &rt->dst;
374 		dst_hold(dst);
375 	}
376 
377 	skb_dst_drop(skb);
378 	skb_dst_set(skb, dst);
379 	return dst->error;
380 }
381 
382 int seg6_lookup_nexthop(struct sk_buff *skb,
383 			struct in6_addr *nhaddr, u32 tbl_id)
384 {
385 	return seg6_lookup_any_nexthop(skb, nhaddr, tbl_id, false, 0);
386 }
387 
388 static __u8 seg6_flv_lcblock_octects(const struct seg6_flavors_info *finfo)
389 {
390 	return finfo->lcblock_bits >> 3;
391 }
392 
393 static __u8 seg6_flv_lcnode_func_octects(const struct seg6_flavors_info *finfo)
394 {
395 	return finfo->lcnode_func_bits >> 3;
396 }
397 
398 static bool seg6_next_csid_is_arg_zero(const struct in6_addr *addr,
399 				       const struct seg6_flavors_info *finfo)
400 {
401 	__u8 fnc_octects = seg6_flv_lcnode_func_octects(finfo);
402 	__u8 blk_octects = seg6_flv_lcblock_octects(finfo);
403 	__u8 arg_octects;
404 	int i;
405 
406 	arg_octects = 16 - blk_octects - fnc_octects;
407 	for (i = 0; i < arg_octects; ++i) {
408 		if (addr->s6_addr[blk_octects + fnc_octects + i] != 0x00)
409 			return false;
410 	}
411 
412 	return true;
413 }
414 
415 /* assume that DA.Argument length > 0.
416  * skb pointers may change: after this call, the caller must evaluate again
417  * any pointer into the packet data.
418  *
419  * This function returns:
420  *  - SKB_NOT_DROPPED_YET on success;
421  *  - SKB_DROP_REASON_NOMEM when the skb cannot be made writable.
422  */
423 static enum skb_drop_reason
424 seg6_next_csid_advance_arg(struct sk_buff *skb,
425 			   const struct seg6_flavors_info *finfo)
426 {
427 	__u8 fnc_octects = seg6_flv_lcnode_func_octects(finfo);
428 	__u8 blk_octects = seg6_flv_lcblock_octects(finfo);
429 	struct in6_addr *addr;
430 
431 	if (unlikely(skb_ensure_writable(skb, sizeof(struct ipv6hdr))))
432 		return SKB_DROP_REASON_NOMEM;
433 
434 	addr = &ipv6_hdr(skb)->daddr;
435 
436 	/* advance DA.Argument */
437 	memmove(&addr->s6_addr[blk_octects],
438 		&addr->s6_addr[blk_octects + fnc_octects],
439 		16 - blk_octects - fnc_octects);
440 
441 	memset(&addr->s6_addr[16 - fnc_octects], 0x00, fnc_octects);
442 
443 	return SKB_NOT_DROPPED_YET;
444 }
445 
446 static int input_action_end_finish(struct sk_buff *skb,
447 				   struct seg6_local_lwt *slwt)
448 {
449 	seg6_lookup_nexthop(skb, NULL, 0);
450 
451 	return dst_input(skb);
452 }
453 
454 static int input_action_end_core(struct sk_buff *skb,
455 				 struct seg6_local_lwt *slwt)
456 {
457 	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
458 	struct ipv6_sr_hdr *srh;
459 	int err = -EINVAL;
460 
461 	srh = get_and_validate_srh(skb);
462 	if (!srh)
463 		goto drop;
464 
465 	srh = advance_nextseg(skb, srh, &reason);
466 	if (!srh) {
467 		err = -ENOMEM;
468 		goto drop;
469 	}
470 
471 	return input_action_end_finish(skb, slwt);
472 
473 drop:
474 	kfree_skb_reason(skb, reason);
475 	return err;
476 }
477 
478 static int end_next_csid_core(struct sk_buff *skb, struct seg6_local_lwt *slwt)
479 {
480 	const struct seg6_flavors_info *finfo = &slwt->flv_info;
481 	struct in6_addr *daddr = &ipv6_hdr(skb)->daddr;
482 	enum skb_drop_reason reason;
483 
484 	if (seg6_next_csid_is_arg_zero(daddr, finfo))
485 		return input_action_end_core(skb, slwt);
486 
487 	/* update DA */
488 	reason = seg6_next_csid_advance_arg(skb, finfo);
489 	if (reason) {
490 		kfree_skb_reason(skb, reason);
491 		return -ENOMEM;
492 	}
493 
494 	return input_action_end_finish(skb, slwt);
495 }
496 
497 static int input_action_end_x_finish(struct sk_buff *skb,
498 				     struct seg6_local_lwt *slwt)
499 {
500 	seg6_lookup_any_nexthop(skb, &slwt->nh6, 0, false, slwt->oif);
501 
502 	return dst_input(skb);
503 }
504 
505 static int input_action_end_x_core(struct sk_buff *skb,
506 				   struct seg6_local_lwt *slwt)
507 {
508 	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
509 	struct ipv6_sr_hdr *srh;
510 	int err = -EINVAL;
511 
512 	srh = get_and_validate_srh(skb);
513 	if (!srh)
514 		goto drop;
515 
516 	srh = advance_nextseg(skb, srh, &reason);
517 	if (!srh) {
518 		err = -ENOMEM;
519 		goto drop;
520 	}
521 
522 	return input_action_end_x_finish(skb, slwt);
523 
524 drop:
525 	kfree_skb_reason(skb, reason);
526 	return err;
527 }
528 
529 static int end_x_next_csid_core(struct sk_buff *skb,
530 				struct seg6_local_lwt *slwt)
531 {
532 	const struct seg6_flavors_info *finfo = &slwt->flv_info;
533 	struct in6_addr *daddr = &ipv6_hdr(skb)->daddr;
534 	enum skb_drop_reason reason;
535 
536 	if (seg6_next_csid_is_arg_zero(daddr, finfo))
537 		return input_action_end_x_core(skb, slwt);
538 
539 	/* update DA */
540 	reason = seg6_next_csid_advance_arg(skb, finfo);
541 	if (reason) {
542 		kfree_skb_reason(skb, reason);
543 		return -ENOMEM;
544 	}
545 
546 	return input_action_end_x_finish(skb, slwt);
547 }
548 
549 static bool seg6_next_csid_enabled(__u32 fops)
550 {
551 	return fops & SEG6_F_LOCAL_FLV_NEXT_CSID;
552 }
553 
554 /* Processing of SRv6 End, End.X, and End.T behaviors can be extended through
555  * the flavors framework. These behaviors must report the subset of (flavor)
556  * operations they currently implement. In this way, if a user specifies a
557  * flavor combination that is not supported by a given End* behavior, the
558  * kernel refuses to instantiate the tunnel reporting the error.
559  */
560 static int seg6_flv_supp_ops_by_action(int action, __u32 *fops)
561 {
562 	switch (action) {
563 	case SEG6_LOCAL_ACTION_END:
564 		*fops = SEG6_LOCAL_END_FLV_SUPP_OPS;
565 		break;
566 	case SEG6_LOCAL_ACTION_END_X:
567 		*fops = SEG6_LOCAL_END_X_FLV_SUPP_OPS;
568 		break;
569 	default:
570 		return -EOPNOTSUPP;
571 	}
572 
573 	return 0;
574 }
575 
576 /* We describe the packet state in relation to the absence/presence of the SRH
577  * and the Segment Left (SL) field.
578  * For our purposes, it is not necessary to record the exact value of the SL
579  * when the SID List consists of two or more segments.
580  */
581 enum seg6_local_pktinfo {
582 	/* the order really matters! */
583 	SEG6_LOCAL_PKTINFO_NOHDR	= 0,
584 	SEG6_LOCAL_PKTINFO_SL_ZERO,
585 	SEG6_LOCAL_PKTINFO_SL_ONE,
586 	SEG6_LOCAL_PKTINFO_SL_MORE,
587 	__SEG6_LOCAL_PKTINFO_MAX,
588 };
589 
590 #define SEG6_LOCAL_PKTINFO_MAX (__SEG6_LOCAL_PKTINFO_MAX - 1)
591 
592 static enum seg6_local_pktinfo seg6_get_srh_pktinfo(struct ipv6_sr_hdr *srh)
593 {
594 	__u8 sgl;
595 
596 	if (!srh)
597 		return SEG6_LOCAL_PKTINFO_NOHDR;
598 
599 	sgl = srh->segments_left;
600 	if (sgl < 2)
601 		return SEG6_LOCAL_PKTINFO_SL_ZERO + sgl;
602 
603 	return SEG6_LOCAL_PKTINFO_SL_MORE;
604 }
605 
606 enum seg6_local_flv_action {
607 	SEG6_LOCAL_FLV_ACT_UNSPEC	= 0,
608 	SEG6_LOCAL_FLV_ACT_END,
609 	SEG6_LOCAL_FLV_ACT_PSP,
610 	SEG6_LOCAL_FLV_ACT_USP,
611 	SEG6_LOCAL_FLV_ACT_USD,
612 	__SEG6_LOCAL_FLV_ACT_MAX
613 };
614 
615 #define SEG6_LOCAL_FLV_ACT_MAX (__SEG6_LOCAL_FLV_ACT_MAX - 1)
616 
617 /* The action table for RFC8986 flavors (see the flv8986_act_tbl below)
618  * contains the actions (i.e. processing operations) to be applied on packets
619  * when flavors are configured for an End* behavior.
620  * By combining the pkinfo data and from the flavors mask, the macro
621  * computes the index used to access the elements (actions) stored in the
622  * action table. The index is structured as follows:
623  *
624  *                     index
625  *       _______________/\________________
626  *      /                                 \
627  *      +----------------+----------------+
628  *      |        pf      |      afm       |
629  *      +----------------+----------------+
630  *        ph-1 ... p1 p0   fk-1 ... f1 f0
631  *     MSB                               LSB
632  *
633  * where:
634  *  - 'afm' (adjusted flavor mask) is the mask containing a combination of the
635  *     RFC8986 flavors currently supported. 'afm' corresponds to the @fm
636  *     argument of the macro whose value is righ-shifted by 1 bit. By doing so,
637  *     we discard the SEG6_LOCAL_FLV_OP_UNSPEC flag (bit 0 in @fm) which is
638  *     never used here;
639  *  - 'pf' encodes the packet info (pktinfo) regarding the presence/absence of
640  *    the SRH, SL = 0, etc. 'pf' is set with the value of @pf provided as
641  *    argument to the macro.
642  */
643 #define flv8986_act_tbl_idx(pf, fm)					\
644 	((((pf) << bits_per(SEG6_LOCAL_FLV8986_SUPP_OPS)) |		\
645 	  ((fm) & SEG6_LOCAL_FLV8986_SUPP_OPS)) >> SEG6_LOCAL_FLV_OP_PSP)
646 
647 /* We compute the size of the action table by considering the RFC8986 flavors
648  * actually supported by the kernel. In this way, the size is automatically
649  * adjusted when new flavors are supported.
650  */
651 #define FLV8986_ACT_TBL_SIZE						\
652 	roundup_pow_of_two(flv8986_act_tbl_idx(SEG6_LOCAL_PKTINFO_MAX,	\
653 					       SEG6_LOCAL_FLV8986_SUPP_OPS))
654 
655 /* tbl_cfg(act, pf, fm) macro is used to easily configure the action
656  * table; it accepts 3 arguments:
657  *     i) @act, the suffix from SEG6_LOCAL_FLV_ACT_{act} representing
658  *        the action that should be applied on the packet;
659  *    ii) @pf, the suffix from SEG6_LOCAL_PKTINFO_{pf} reporting the packet
660  *        info about the lack/presence of SRH, SRH with SL = 0, etc;
661  *   iii) @fm, the mask of flavors.
662  */
663 #define tbl_cfg(act, pf, fm)						\
664 	[flv8986_act_tbl_idx(SEG6_LOCAL_PKTINFO_##pf,			\
665 			     (fm))] = SEG6_LOCAL_FLV_ACT_##act
666 
667 /* shorthand for improving readability */
668 #define F_PSP	SEG6_F_LOCAL_FLV_PSP
669 
670 /* The table contains, for each combination of the pktinfo data and
671  * flavors, the action that should be taken on a packet (e.g.
672  * "standard" Endpoint processing, Penultimate Segment Pop, etc).
673  *
674  * By default, table entries not explicitly configured are initialized with the
675  * SEG6_LOCAL_FLV_ACT_UNSPEC action, which generally has the effect of
676  * discarding the processed packet.
677  */
678 static const u8 flv8986_act_tbl[FLV8986_ACT_TBL_SIZE] = {
679 	/* PSP variant for packet where SRH with SL = 1 */
680 	tbl_cfg(PSP, SL_ONE, F_PSP),
681 	/* End for packet where the SRH with SL > 1*/
682 	tbl_cfg(END, SL_MORE, F_PSP),
683 };
684 
685 #undef F_PSP
686 #undef tbl_cfg
687 
688 /* For each flavor defined in RFC8986 (or a combination of them) an action is
689  * performed on the packet. The specific action depends on:
690  *  - info extracted from the packet (i.e. pktinfo data) regarding the
691  *    lack/presence of the SRH, and if the SRH is available, on the value of
692  *    Segment Left field;
693  *  - the mask of flavors configured for the specific SRv6 End* behavior.
694  *
695  * The function combines both the pkinfo and the flavors mask to evaluate the
696  * corresponding action to be taken on the packet.
697  */
698 static enum seg6_local_flv_action
699 seg6_local_flv8986_act_lookup(enum seg6_local_pktinfo pinfo, __u32 flvmask)
700 {
701 	unsigned long index;
702 
703 	/* check if the provided mask of flavors is supported */
704 	if (unlikely(flvmask & ~SEG6_LOCAL_FLV8986_SUPP_OPS))
705 		return SEG6_LOCAL_FLV_ACT_UNSPEC;
706 
707 	index = flv8986_act_tbl_idx(pinfo, flvmask);
708 	if (unlikely(index >= FLV8986_ACT_TBL_SIZE))
709 		return SEG6_LOCAL_FLV_ACT_UNSPEC;
710 
711 	return flv8986_act_tbl[index];
712 }
713 
714 /* skb->data must be aligned with skb->network_header */
715 static bool seg6_pop_srh(struct sk_buff *skb, int srhoff)
716 {
717 	struct ipv6_sr_hdr *srh;
718 	struct ipv6hdr *iph;
719 	__u8 srh_nexthdr;
720 	int thoff = -1;
721 	int srhlen;
722 	int nhlen;
723 
724 	if (unlikely(srhoff < sizeof(*iph) ||
725 		     !pskb_may_pull(skb, srhoff + sizeof(*srh))))
726 		return false;
727 
728 	srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
729 	srhlen = ipv6_optlen(srh);
730 
731 	/* we are about to mangle the pkt, let's check if we can write on it */
732 	if (unlikely(skb_ensure_writable(skb, srhoff + srhlen)))
733 		return false;
734 
735 	/* skb_ensure_writable() may change skb pointers; evaluate srh again */
736 	srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
737 	srh_nexthdr = srh->nexthdr;
738 
739 	if (unlikely(!skb_transport_header_was_set(skb)))
740 		goto pull;
741 
742 	nhlen = skb_network_header_len(skb);
743 	/* we have to deal with the transport header: it could be set before
744 	 * the SRH, after the SRH, or within it (which is considered wrong,
745 	 * however).
746 	 */
747 	if (likely(nhlen <= srhoff))
748 		thoff = nhlen;
749 	else if (nhlen >= srhoff + srhlen)
750 		/* transport_header is set after the SRH */
751 		thoff = nhlen - srhlen;
752 	else
753 		/* transport_header falls inside the SRH; hence, we can't
754 		 * restore the transport_header pointer properly after
755 		 * SRH removing operation.
756 		 */
757 		return false;
758 pull:
759 	/* we need to pop the SRH:
760 	 *  1) first of all, we pull out everything from IPv6 header up to SRH
761 	 *     (included) evaluating also the rcsum;
762 	 *  2) we overwrite (and then remove) the SRH by properly moving the
763 	 *     IPv6 along with any extension header that precedes the SRH;
764 	 *  3) At the end, we push back the pulled headers (except for SRH,
765 	 *     obviously).
766 	 */
767 	skb_pull_rcsum(skb, srhoff + srhlen);
768 	memmove(skb_network_header(skb) + srhlen, skb_network_header(skb),
769 		srhoff);
770 	skb_push(skb, srhoff);
771 
772 	skb_reset_network_header(skb);
773 	skb_mac_header_rebuild(skb);
774 	if (likely(thoff >= 0))
775 		skb_set_transport_header(skb, thoff);
776 
777 	iph = ipv6_hdr(skb);
778 	if (iph->nexthdr == NEXTHDR_ROUTING) {
779 		iph->nexthdr = srh_nexthdr;
780 	} else {
781 		/* we must look for the extension header (EXTH, for short) that
782 		 * immediately precedes the SRH we have just removed.
783 		 * Then, we update the value of the EXTH nexthdr with the one
784 		 * contained in the SRH nexthdr.
785 		 */
786 		unsigned int off = sizeof(*iph);
787 		struct ipv6_opt_hdr *hp, _hdr;
788 		__u8 nexthdr = iph->nexthdr;
789 
790 		for (;;) {
791 			if (unlikely(!ipv6_ext_hdr(nexthdr) ||
792 				     nexthdr == NEXTHDR_NONE))
793 				return false;
794 
795 			hp = skb_header_pointer(skb, off, sizeof(_hdr), &_hdr);
796 			if (unlikely(!hp))
797 				return false;
798 
799 			if (hp->nexthdr == NEXTHDR_ROUTING) {
800 				hp->nexthdr = srh_nexthdr;
801 				break;
802 			}
803 
804 			switch (nexthdr) {
805 			case NEXTHDR_FRAGMENT:
806 				fallthrough;
807 			case NEXTHDR_AUTH:
808 				/* we expect SRH before FRAG and AUTH */
809 				return false;
810 			default:
811 				off += ipv6_optlen(hp);
812 				break;
813 			}
814 
815 			nexthdr = hp->nexthdr;
816 		}
817 	}
818 
819 	iph->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
820 
821 	skb_postpush_rcsum(skb, iph, srhoff);
822 
823 	return true;
824 }
825 
826 /* process the packet on the basis of the RFC8986 flavors set for the given
827  * SRv6 End behavior instance.
828  */
829 static int end_flv8986_core(struct sk_buff *skb, struct seg6_local_lwt *slwt)
830 {
831 	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
832 	const struct seg6_flavors_info *finfo = &slwt->flv_info;
833 	enum seg6_local_flv_action action;
834 	enum seg6_local_pktinfo pinfo;
835 	struct ipv6_sr_hdr *srh;
836 	int err = -EINVAL;
837 	__u32 flvmask;
838 	int srhoff;
839 
840 	srh = seg6_get_srh(skb, 0);
841 	srhoff = srh ? ((unsigned char *)srh - skb->data) : 0;
842 	pinfo = seg6_get_srh_pktinfo(srh);
843 #ifdef CONFIG_IPV6_SEG6_HMAC
844 	if (srh && !seg6_hmac_validate_skb(skb))
845 		goto drop;
846 #endif
847 	flvmask = finfo->flv_ops;
848 	if (unlikely(flvmask & ~SEG6_LOCAL_FLV8986_SUPP_OPS)) {
849 		pr_warn_once("seg6local: invalid RFC8986 flavors\n");
850 		goto drop;
851 	}
852 
853 	/* retrieve the action triggered by the combination of pktinfo data and
854 	 * the flavors mask.
855 	 */
856 	action = seg6_local_flv8986_act_lookup(pinfo, flvmask);
857 	switch (action) {
858 	case SEG6_LOCAL_FLV_ACT_END:
859 		/* process the packet as the "standard" End behavior */
860 		srh = advance_nextseg(skb, srh, &reason);
861 		if (!srh) {
862 			err = -ENOMEM;
863 			goto drop;
864 		}
865 		break;
866 	case SEG6_LOCAL_FLV_ACT_PSP:
867 		srh = advance_nextseg(skb, srh, &reason);
868 		if (!srh) {
869 			err = -ENOMEM;
870 			goto drop;
871 		}
872 
873 		if (unlikely(!seg6_pop_srh(skb, srhoff)))
874 			goto drop;
875 		break;
876 	case SEG6_LOCAL_FLV_ACT_UNSPEC:
877 		fallthrough;
878 	default:
879 		/* by default, we drop the packet since we could not find a
880 		 * suitable action.
881 		 */
882 		goto drop;
883 	}
884 
885 	return input_action_end_finish(skb, slwt);
886 
887 drop:
888 	kfree_skb_reason(skb, reason);
889 	return err;
890 }
891 
892 /* regular endpoint function */
893 static int input_action_end(struct sk_buff *skb, struct seg6_local_lwt *slwt)
894 {
895 	const struct seg6_flavors_info *finfo = &slwt->flv_info;
896 	__u32 fops = finfo->flv_ops;
897 
898 	if (!fops)
899 		return input_action_end_core(skb, slwt);
900 
901 	/* check for the presence of NEXT-C-SID since it applies first */
902 	if (seg6_next_csid_enabled(fops))
903 		return end_next_csid_core(skb, slwt);
904 
905 	/* the specific processing function to be performed on the packet
906 	 * depends on the combination of flavors defined in RFC8986 and some
907 	 * information extracted from the packet, e.g. presence/absence of SRH,
908 	 * Segment Left = 0, etc.
909 	 */
910 	return end_flv8986_core(skb, slwt);
911 }
912 
913 /* regular endpoint, and forward to specified nexthop */
914 static int input_action_end_x(struct sk_buff *skb, struct seg6_local_lwt *slwt)
915 {
916 	const struct seg6_flavors_info *finfo = &slwt->flv_info;
917 	__u32 fops = finfo->flv_ops;
918 
919 	/* check for the presence of NEXT-C-SID since it applies first */
920 	if (seg6_next_csid_enabled(fops))
921 		return end_x_next_csid_core(skb, slwt);
922 
923 	return input_action_end_x_core(skb, slwt);
924 }
925 
926 static int input_action_end_t(struct sk_buff *skb, struct seg6_local_lwt *slwt)
927 {
928 	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
929 	struct ipv6_sr_hdr *srh;
930 	int err = -EINVAL;
931 
932 	srh = get_and_validate_srh(skb);
933 	if (!srh)
934 		goto drop;
935 
936 	srh = advance_nextseg(skb, srh, &reason);
937 	if (!srh) {
938 		err = -ENOMEM;
939 		goto drop;
940 	}
941 
942 	seg6_lookup_nexthop(skb, NULL, slwt->table);
943 
944 	return dst_input(skb);
945 
946 drop:
947 	kfree_skb_reason(skb, reason);
948 	return err;
949 }
950 
951 /* decapsulate and forward inner L2 frame on specified interface */
952 static int input_action_end_dx2(struct sk_buff *skb,
953 				struct seg6_local_lwt *slwt)
954 {
955 	struct net *net = dev_net(skb->dev);
956 	struct net_device *odev;
957 	struct ethhdr *eth;
958 
959 	if (!decap_and_validate(skb, IPPROTO_ETHERNET))
960 		goto drop;
961 
962 	if (!pskb_may_pull(skb, ETH_HLEN))
963 		goto drop;
964 
965 	skb_reset_mac_header(skb);
966 	eth = (struct ethhdr *)skb->data;
967 
968 	/* To determine the frame's protocol, we assume it is 802.3. This avoids
969 	 * a call to eth_type_trans(), which is not really relevant for our
970 	 * use case.
971 	 */
972 	if (!eth_proto_is_802_3(eth->h_proto))
973 		goto drop;
974 
975 	odev = dev_get_by_index_rcu(net, slwt->oif);
976 	if (!odev)
977 		goto drop;
978 
979 	/* As we accept Ethernet frames, make sure the egress device is of
980 	 * the correct type.
981 	 */
982 	if (odev->type != ARPHRD_ETHER)
983 		goto drop;
984 
985 	if (!(odev->flags & IFF_UP) || !netif_carrier_ok(odev))
986 		goto drop;
987 
988 	skb_orphan(skb);
989 
990 	if (skb_warn_if_lro(skb))
991 		goto drop;
992 
993 	skb_forward_csum(skb);
994 
995 	if (skb->len - ETH_HLEN > odev->mtu)
996 		goto drop;
997 
998 	skb->dev = odev;
999 	skb->protocol = eth->h_proto;
1000 
1001 	return dev_queue_xmit(skb);
1002 
1003 drop:
1004 	kfree_skb(skb);
1005 	return -EINVAL;
1006 }
1007 
1008 static int input_action_end_dx6_finish(struct net *net, struct sock *sk,
1009 				       struct sk_buff *skb)
1010 {
1011 	struct dst_entry *orig_dst = skb_dst(skb);
1012 	struct in6_addr *nhaddr = NULL;
1013 	struct seg6_local_lwt *slwt;
1014 
1015 	slwt = seg6_local_lwtunnel(orig_dst->lwtstate);
1016 
1017 	/* The inner packet is not associated to any local interface,
1018 	 * so we do not call netif_rx().
1019 	 *
1020 	 * If slwt->nh6 is set to ::, then lookup the nexthop for the
1021 	 * inner packet's DA. Otherwise, use the specified nexthop.
1022 	 */
1023 	if (!ipv6_addr_any(&slwt->nh6))
1024 		nhaddr = &slwt->nh6;
1025 
1026 	seg6_lookup_nexthop(skb, nhaddr, 0);
1027 
1028 	return dst_input(skb);
1029 }
1030 
1031 /* decapsulate and forward to specified nexthop */
1032 static int input_action_end_dx6(struct sk_buff *skb,
1033 				struct seg6_local_lwt *slwt)
1034 {
1035 	/* this function accepts IPv6 encapsulated packets, with either
1036 	 * an SRH with SL=0, or no SRH.
1037 	 */
1038 
1039 	if (!decap_and_validate(skb, IPPROTO_IPV6))
1040 		goto drop;
1041 
1042 	if (!pskb_may_pull(skb, sizeof(struct ipv6hdr)))
1043 		goto drop;
1044 
1045 	skb_set_transport_header(skb, sizeof(struct ipv6hdr));
1046 	nf_reset_ct(skb);
1047 
1048 	if (static_branch_unlikely(&nf_hooks_lwtunnel_enabled))
1049 		return NF_HOOK(NFPROTO_IPV6, NF_INET_PRE_ROUTING,
1050 			       dev_net(skb->dev), NULL, skb, skb->dev,
1051 			       NULL, input_action_end_dx6_finish);
1052 
1053 	return input_action_end_dx6_finish(dev_net(skb->dev), NULL, skb);
1054 drop:
1055 	kfree_skb(skb);
1056 	return -EINVAL;
1057 }
1058 
1059 static int input_action_end_dx4_finish(struct net *net, struct sock *sk,
1060 				       struct sk_buff *skb)
1061 {
1062 	struct dst_entry *orig_dst = skb_dst(skb);
1063 	enum skb_drop_reason reason;
1064 	struct seg6_local_lwt *slwt;
1065 	struct iphdr *iph;
1066 	__be32 nhaddr;
1067 
1068 	slwt = seg6_local_lwtunnel(orig_dst->lwtstate);
1069 
1070 	iph = ip_hdr(skb);
1071 
1072 	nhaddr = slwt->nh4.s_addr ?: iph->daddr;
1073 
1074 	skb_dst_drop(skb);
1075 
1076 	reason = ip_route_input(skb, nhaddr, iph->saddr, 0, skb->dev);
1077 	if (reason) {
1078 		kfree_skb_reason(skb, reason);
1079 		return -EINVAL;
1080 	}
1081 
1082 	return dst_input(skb);
1083 }
1084 
1085 static int input_action_end_dx4(struct sk_buff *skb,
1086 				struct seg6_local_lwt *slwt)
1087 {
1088 	if (!decap_and_validate(skb, IPPROTO_IPIP))
1089 		goto drop;
1090 
1091 	if (!pskb_may_pull(skb, sizeof(struct iphdr)))
1092 		goto drop;
1093 
1094 	skb->protocol = htons(ETH_P_IP);
1095 	skb_set_transport_header(skb, sizeof(struct iphdr));
1096 	nf_reset_ct(skb);
1097 
1098 	if (static_branch_unlikely(&nf_hooks_lwtunnel_enabled))
1099 		return NF_HOOK(NFPROTO_IPV4, NF_INET_PRE_ROUTING,
1100 			       dev_net(skb->dev), NULL, skb, skb->dev,
1101 			       NULL, input_action_end_dx4_finish);
1102 
1103 	return input_action_end_dx4_finish(dev_net(skb->dev), NULL, skb);
1104 drop:
1105 	kfree_skb(skb);
1106 	return -EINVAL;
1107 }
1108 
1109 #ifdef CONFIG_NET_L3_MASTER_DEV
1110 static struct net *fib6_config_get_net(const struct fib6_config *fib6_cfg)
1111 {
1112 	const struct nl_info *nli = &fib6_cfg->fc_nlinfo;
1113 
1114 	return nli->nl_net;
1115 }
1116 
1117 static int __seg6_end_dt_vrf_build(struct seg6_local_lwt *slwt, const void *cfg,
1118 				   u16 family, struct netlink_ext_ack *extack)
1119 {
1120 	struct seg6_end_dt_info *info = &slwt->dt_info;
1121 	int vrf_ifindex;
1122 	struct net *net;
1123 
1124 	net = fib6_config_get_net(cfg);
1125 
1126 	/* note that vrf_table was already set by parse_nla_vrftable() */
1127 	vrf_ifindex = l3mdev_ifindex_lookup_by_table_id(L3MDEV_TYPE_VRF, net,
1128 							info->vrf_table);
1129 	if (vrf_ifindex < 0) {
1130 		if (vrf_ifindex == -EPERM) {
1131 			NL_SET_ERR_MSG(extack,
1132 				       "Strict mode for VRF is disabled");
1133 		} else if (vrf_ifindex == -ENODEV) {
1134 			NL_SET_ERR_MSG(extack,
1135 				       "Table has no associated VRF device");
1136 		} else {
1137 			pr_debug("seg6local: SRv6 End.DT* creation error=%d\n",
1138 				 vrf_ifindex);
1139 		}
1140 
1141 		return vrf_ifindex;
1142 	}
1143 
1144 	info->net = net;
1145 	info->vrf_ifindex = vrf_ifindex;
1146 
1147 	info->family = family;
1148 	info->mode = DT_VRF_MODE;
1149 
1150 	return 0;
1151 }
1152 
1153 /* The SRv6 End.DT4/DT6 behavior extracts the inner (IPv4/IPv6) packet and
1154  * routes the IPv4/IPv6 packet by looking at the configured routing table.
1155  *
1156  * In the SRv6 End.DT4/DT6 use case, we can receive traffic (IPv6+Segment
1157  * Routing Header packets) from several interfaces and the outer IPv6
1158  * destination address (DA) is used for retrieving the specific instance of the
1159  * End.DT4/DT6 behavior that should process the packets.
1160  *
1161  * However, the inner IPv4/IPv6 packet is not really bound to any receiving
1162  * interface and thus the End.DT4/DT6 sets the VRF (associated with the
1163  * corresponding routing table) as the *receiving* interface.
1164  * In other words, the End.DT4/DT6 processes a packet as if it has been received
1165  * directly by the VRF (and not by one of its slave devices, if any).
1166  * In this way, the VRF interface is used for routing the IPv4/IPv6 packet in
1167  * according to the routing table configured by the End.DT4/DT6 instance.
1168  *
1169  * This design allows you to get some interesting features like:
1170  *  1) the statistics on rx packets;
1171  *  2) the possibility to install a packet sniffer on the receiving interface
1172  *     (the VRF one) for looking at the incoming packets;
1173  *  3) the possibility to leverage the netfilter prerouting hook for the inner
1174  *     IPv4 packet.
1175  *
1176  * This function returns:
1177  *  - the sk_buff* when the VRF rcv handler has processed the packet correctly;
1178  *  - NULL when the skb is consumed by the VRF rcv handler;
1179  *  - a pointer which encodes a negative error number in case of error.
1180  *    Note that in this case, the function takes care of freeing the skb.
1181  */
1182 static struct sk_buff *end_dt_vrf_rcv(struct sk_buff *skb, u16 family,
1183 				      struct net_device *dev)
1184 {
1185 	/* based on l3mdev_ip_rcv; we are only interested in the master */
1186 	if (unlikely(!netif_is_l3_master(dev) && !netif_has_l3_rx_handler(dev)))
1187 		goto drop;
1188 
1189 	if (unlikely(!dev->l3mdev_ops->l3mdev_l3_rcv))
1190 		goto drop;
1191 
1192 	/* the decap packet IPv4/IPv6 does not come with any mac header info.
1193 	 * We must unset the mac header to allow the VRF device to rebuild it,
1194 	 * just in case there is a sniffer attached on the device.
1195 	 */
1196 	skb_unset_mac_header(skb);
1197 
1198 	skb = dev->l3mdev_ops->l3mdev_l3_rcv(dev, skb, family);
1199 	if (!skb)
1200 		/* the skb buffer was consumed by the handler */
1201 		return NULL;
1202 
1203 	/* when a packet is received by a VRF or by one of its slaves, the
1204 	 * master device reference is set into the skb.
1205 	 */
1206 	if (unlikely(skb->dev != dev || skb->skb_iif != dev->ifindex))
1207 		goto drop;
1208 
1209 	return skb;
1210 
1211 drop:
1212 	kfree_skb(skb);
1213 	return ERR_PTR(-EINVAL);
1214 }
1215 
1216 static struct net_device *end_dt_get_vrf_rcu(struct sk_buff *skb,
1217 					     struct seg6_end_dt_info *info)
1218 {
1219 	int vrf_ifindex = info->vrf_ifindex;
1220 	struct net *net = info->net;
1221 
1222 	if (unlikely(vrf_ifindex < 0))
1223 		goto error;
1224 
1225 	if (unlikely(!net_eq(dev_net(skb->dev), net)))
1226 		goto error;
1227 
1228 	return dev_get_by_index_rcu(net, vrf_ifindex);
1229 
1230 error:
1231 	return NULL;
1232 }
1233 
1234 static struct sk_buff *end_dt_vrf_core(struct sk_buff *skb,
1235 				       struct seg6_local_lwt *slwt, u16 family)
1236 {
1237 	struct seg6_end_dt_info *info = &slwt->dt_info;
1238 	struct net_device *vrf;
1239 	__be16 protocol;
1240 	int hdrlen;
1241 
1242 	vrf = end_dt_get_vrf_rcu(skb, info);
1243 	if (unlikely(!vrf))
1244 		goto drop;
1245 
1246 	switch (family) {
1247 	case AF_INET:
1248 		protocol = htons(ETH_P_IP);
1249 		hdrlen = sizeof(struct iphdr);
1250 		break;
1251 	case AF_INET6:
1252 		protocol = htons(ETH_P_IPV6);
1253 		hdrlen = sizeof(struct ipv6hdr);
1254 		break;
1255 	case AF_UNSPEC:
1256 		fallthrough;
1257 	default:
1258 		goto drop;
1259 	}
1260 
1261 	if (unlikely(info->family != AF_UNSPEC && info->family != family)) {
1262 		pr_warn_once("seg6local: SRv6 End.DT* family mismatch");
1263 		goto drop;
1264 	}
1265 
1266 	skb->protocol = protocol;
1267 
1268 	skb_dst_drop(skb);
1269 
1270 	skb_set_transport_header(skb, hdrlen);
1271 	nf_reset_ct(skb);
1272 
1273 	return end_dt_vrf_rcv(skb, family, vrf);
1274 
1275 drop:
1276 	kfree_skb(skb);
1277 	return ERR_PTR(-EINVAL);
1278 }
1279 
1280 static int input_action_end_dt4(struct sk_buff *skb,
1281 				struct seg6_local_lwt *slwt)
1282 {
1283 	enum skb_drop_reason reason;
1284 	struct iphdr *iph;
1285 
1286 	if (!decap_and_validate(skb, IPPROTO_IPIP))
1287 		goto drop;
1288 
1289 	if (!pskb_may_pull(skb, sizeof(struct iphdr)))
1290 		goto drop;
1291 
1292 	skb = end_dt_vrf_core(skb, slwt, AF_INET);
1293 	if (!skb)
1294 		/* packet has been processed and consumed by the VRF */
1295 		return 0;
1296 
1297 	if (IS_ERR(skb))
1298 		return PTR_ERR(skb);
1299 
1300 	iph = ip_hdr(skb);
1301 
1302 	reason = ip_route_input(skb, iph->daddr, iph->saddr, 0, skb->dev);
1303 	if (unlikely(reason))
1304 		goto drop;
1305 
1306 	return dst_input(skb);
1307 
1308 drop:
1309 	kfree_skb(skb);
1310 	return -EINVAL;
1311 }
1312 
1313 static int seg6_end_dt4_build(struct seg6_local_lwt *slwt, const void *cfg,
1314 			      struct netlink_ext_ack *extack)
1315 {
1316 	return __seg6_end_dt_vrf_build(slwt, cfg, AF_INET, extack);
1317 }
1318 
1319 static enum
1320 seg6_end_dt_mode seg6_end_dt6_parse_mode(struct seg6_local_lwt *slwt)
1321 {
1322 	unsigned long parsed_optattrs = slwt->parsed_optattrs;
1323 	bool legacy, vrfmode;
1324 
1325 	legacy	= !!(parsed_optattrs & SEG6_F_ATTR(SEG6_LOCAL_TABLE));
1326 	vrfmode	= !!(parsed_optattrs & SEG6_F_ATTR(SEG6_LOCAL_VRFTABLE));
1327 
1328 	if (!(legacy ^ vrfmode))
1329 		/* both are absent or present: invalid DT6 mode */
1330 		return DT_INVALID_MODE;
1331 
1332 	return legacy ? DT_LEGACY_MODE : DT_VRF_MODE;
1333 }
1334 
1335 static enum seg6_end_dt_mode seg6_end_dt6_get_mode(struct seg6_local_lwt *slwt)
1336 {
1337 	struct seg6_end_dt_info *info = &slwt->dt_info;
1338 
1339 	return info->mode;
1340 }
1341 
1342 static int seg6_end_dt6_build(struct seg6_local_lwt *slwt, const void *cfg,
1343 			      struct netlink_ext_ack *extack)
1344 {
1345 	enum seg6_end_dt_mode mode = seg6_end_dt6_parse_mode(slwt);
1346 	struct seg6_end_dt_info *info = &slwt->dt_info;
1347 
1348 	switch (mode) {
1349 	case DT_LEGACY_MODE:
1350 		info->mode = DT_LEGACY_MODE;
1351 		return 0;
1352 	case DT_VRF_MODE:
1353 		return __seg6_end_dt_vrf_build(slwt, cfg, AF_INET6, extack);
1354 	default:
1355 		NL_SET_ERR_MSG(extack, "table or vrftable must be specified");
1356 		return -EINVAL;
1357 	}
1358 }
1359 #endif
1360 
1361 static int input_action_end_dt6(struct sk_buff *skb,
1362 				struct seg6_local_lwt *slwt)
1363 {
1364 	if (!decap_and_validate(skb, IPPROTO_IPV6))
1365 		goto drop;
1366 
1367 	if (!pskb_may_pull(skb, sizeof(struct ipv6hdr)))
1368 		goto drop;
1369 
1370 #ifdef CONFIG_NET_L3_MASTER_DEV
1371 	if (seg6_end_dt6_get_mode(slwt) == DT_LEGACY_MODE)
1372 		goto legacy_mode;
1373 
1374 	/* DT6_VRF_MODE */
1375 	skb = end_dt_vrf_core(skb, slwt, AF_INET6);
1376 	if (!skb)
1377 		/* packet has been processed and consumed by the VRF */
1378 		return 0;
1379 
1380 	if (IS_ERR(skb))
1381 		return PTR_ERR(skb);
1382 
1383 	/* note: this time we do not need to specify the table because the VRF
1384 	 * takes care of selecting the correct table.
1385 	 */
1386 	seg6_lookup_any_nexthop(skb, NULL, 0, true, 0);
1387 
1388 	return dst_input(skb);
1389 
1390 legacy_mode:
1391 #endif
1392 	skb_set_transport_header(skb, sizeof(struct ipv6hdr));
1393 
1394 	seg6_lookup_any_nexthop(skb, NULL, slwt->table, true, 0);
1395 
1396 	return dst_input(skb);
1397 
1398 drop:
1399 	kfree_skb(skb);
1400 	return -EINVAL;
1401 }
1402 
1403 #ifdef CONFIG_NET_L3_MASTER_DEV
1404 static int seg6_end_dt46_build(struct seg6_local_lwt *slwt, const void *cfg,
1405 			       struct netlink_ext_ack *extack)
1406 {
1407 	return __seg6_end_dt_vrf_build(slwt, cfg, AF_UNSPEC, extack);
1408 }
1409 
1410 static int input_action_end_dt46(struct sk_buff *skb,
1411 				 struct seg6_local_lwt *slwt)
1412 {
1413 	unsigned int off = 0;
1414 	int nexthdr;
1415 
1416 	nexthdr = ipv6_find_hdr(skb, &off, -1, NULL, NULL);
1417 	if (unlikely(nexthdr < 0))
1418 		goto drop;
1419 
1420 	switch (nexthdr) {
1421 	case IPPROTO_IPIP:
1422 		return input_action_end_dt4(skb, slwt);
1423 	case IPPROTO_IPV6:
1424 		return input_action_end_dt6(skb, slwt);
1425 	}
1426 
1427 drop:
1428 	kfree_skb(skb);
1429 	return -EINVAL;
1430 }
1431 #endif
1432 
1433 /* push an SRH on top of the current one */
1434 static int input_action_end_b6(struct sk_buff *skb, struct seg6_local_lwt *slwt)
1435 {
1436 	struct ipv6_sr_hdr *srh;
1437 	int err = -EINVAL;
1438 
1439 	srh = get_and_validate_srh(skb);
1440 	if (!srh)
1441 		goto drop;
1442 
1443 	err = seg6_do_srh_inline(skb, slwt->srh);
1444 	if (err)
1445 		goto drop;
1446 
1447 	skb_set_transport_header(skb, sizeof(struct ipv6hdr));
1448 
1449 	seg6_lookup_nexthop(skb, NULL, 0);
1450 
1451 	return dst_input(skb);
1452 
1453 drop:
1454 	kfree_skb(skb);
1455 	return err;
1456 }
1457 
1458 /* encapsulate within an outer IPv6 header and a specified SRH */
1459 static int input_action_end_b6_encap(struct sk_buff *skb,
1460 				     struct seg6_local_lwt *slwt)
1461 {
1462 	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
1463 	struct ipv6_sr_hdr *srh;
1464 	int err = -EINVAL;
1465 
1466 	srh = get_and_validate_srh(skb);
1467 	if (!srh)
1468 		goto drop;
1469 
1470 	srh = advance_nextseg(skb, srh, &reason);
1471 	if (!srh) {
1472 		err = -ENOMEM;
1473 		goto drop;
1474 	}
1475 
1476 	skb_reset_inner_headers(skb);
1477 	skb->encapsulation = 1;
1478 
1479 	err = seg6_do_srh_encap(skb, slwt->srh, IPPROTO_IPV6);
1480 	if (err)
1481 		goto drop;
1482 
1483 	skb_set_transport_header(skb, sizeof(struct ipv6hdr));
1484 
1485 	seg6_lookup_nexthop(skb, NULL, 0);
1486 
1487 	return dst_input(skb);
1488 
1489 drop:
1490 	kfree_skb_reason(skb, reason);
1491 	return err;
1492 }
1493 
1494 DEFINE_PER_CPU(struct seg6_bpf_srh_state, seg6_bpf_srh_states) = {
1495 	.bh_lock	= INIT_LOCAL_LOCK(bh_lock),
1496 };
1497 
1498 bool seg6_bpf_has_valid_srh(struct sk_buff *skb)
1499 {
1500 	struct seg6_bpf_srh_state *srh_state =
1501 		this_cpu_ptr(&seg6_bpf_srh_states);
1502 	struct ipv6_sr_hdr *srh = srh_state->srh;
1503 
1504 	lockdep_assert_held(&srh_state->bh_lock);
1505 	if (unlikely(srh == NULL))
1506 		return false;
1507 
1508 	if (unlikely(!srh_state->valid)) {
1509 		if ((srh_state->hdrlen & 7) != 0)
1510 			return false;
1511 
1512 		srh->hdrlen = (u8)(srh_state->hdrlen >> 3);
1513 		if (!seg6_validate_srh(srh, (srh->hdrlen + 1) << 3, true))
1514 			return false;
1515 
1516 		srh_state->valid = true;
1517 	}
1518 
1519 	return true;
1520 }
1521 
1522 static int input_action_end_bpf(struct sk_buff *skb,
1523 				struct seg6_local_lwt *slwt)
1524 {
1525 	struct seg6_bpf_srh_state *srh_state;
1526 	enum skb_drop_reason reason;
1527 	struct ipv6_sr_hdr *srh;
1528 	int ret;
1529 
1530 	srh = get_and_validate_srh(skb);
1531 	if (!srh) {
1532 		kfree_skb(skb);
1533 		return -EINVAL;
1534 	}
1535 	srh = advance_nextseg(skb, srh, &reason);
1536 	if (!srh) {
1537 		kfree_skb_reason(skb, reason);
1538 		return -ENOMEM;
1539 	}
1540 
1541 	/* The access to the per-CPU buffer srh_state is protected by running
1542 	 * always in softirq context (with disabled BH). On PREEMPT_RT the
1543 	 * required locking is provided by the following local_lock_nested_bh()
1544 	 * statement. It is also accessed by the bpf_lwt_seg6_* helpers via
1545 	 * bpf_prog_run_save_cb().
1546 	 */
1547 	local_lock_nested_bh(&seg6_bpf_srh_states.bh_lock);
1548 	srh_state = this_cpu_ptr(&seg6_bpf_srh_states);
1549 	srh_state->srh = srh;
1550 	srh_state->hdrlen = srh->hdrlen << 3;
1551 	srh_state->valid = true;
1552 
1553 	rcu_read_lock();
1554 	bpf_compute_data_pointers(skb);
1555 	ret = bpf_prog_run_save_cb(slwt->bpf.prog, skb);
1556 	rcu_read_unlock();
1557 
1558 	switch (ret) {
1559 	case BPF_OK:
1560 	case BPF_REDIRECT:
1561 		break;
1562 	case BPF_DROP:
1563 		goto drop;
1564 	default:
1565 		pr_warn_once("bpf-seg6local: Illegal return value %u\n", ret);
1566 		goto drop;
1567 	}
1568 
1569 	if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
1570 		goto drop;
1571 	local_unlock_nested_bh(&seg6_bpf_srh_states.bh_lock);
1572 
1573 	if (ret != BPF_REDIRECT)
1574 		seg6_lookup_nexthop(skb, NULL, 0);
1575 
1576 	return dst_input(skb);
1577 
1578 drop:
1579 	local_unlock_nested_bh(&seg6_bpf_srh_states.bh_lock);
1580 	kfree_skb(skb);
1581 	return -EINVAL;
1582 }
1583 
1584 static struct seg6_action_desc seg6_action_table[] = {
1585 	{
1586 		.action		= SEG6_LOCAL_ACTION_END,
1587 		.attrs		= 0,
1588 		.optattrs	= SEG6_F_LOCAL_COUNTERS |
1589 				  SEG6_F_LOCAL_FLAVORS,
1590 		.input		= input_action_end,
1591 	},
1592 	{
1593 		.action		= SEG6_LOCAL_ACTION_END_X,
1594 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_NH6),
1595 		.optattrs	= SEG6_F_LOCAL_COUNTERS |
1596 				  SEG6_F_LOCAL_FLAVORS |
1597 				  SEG6_F_ATTR(SEG6_LOCAL_OIF),
1598 		.input		= input_action_end_x,
1599 	},
1600 	{
1601 		.action		= SEG6_LOCAL_ACTION_END_T,
1602 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_TABLE),
1603 		.optattrs	= SEG6_F_LOCAL_COUNTERS,
1604 		.input		= input_action_end_t,
1605 	},
1606 	{
1607 		.action		= SEG6_LOCAL_ACTION_END_DX2,
1608 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_OIF),
1609 		.optattrs	= SEG6_F_LOCAL_COUNTERS,
1610 		.input		= input_action_end_dx2,
1611 	},
1612 	{
1613 		.action		= SEG6_LOCAL_ACTION_END_DX6,
1614 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_NH6),
1615 		.optattrs	= SEG6_F_LOCAL_COUNTERS,
1616 		.input		= input_action_end_dx6,
1617 	},
1618 	{
1619 		.action		= SEG6_LOCAL_ACTION_END_DX4,
1620 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_NH4),
1621 		.optattrs	= SEG6_F_LOCAL_COUNTERS,
1622 		.input		= input_action_end_dx4,
1623 	},
1624 	{
1625 		.action		= SEG6_LOCAL_ACTION_END_DT4,
1626 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_VRFTABLE),
1627 		.optattrs	= SEG6_F_LOCAL_COUNTERS,
1628 #ifdef CONFIG_NET_L3_MASTER_DEV
1629 		.input		= input_action_end_dt4,
1630 		.slwt_ops	= {
1631 					.build_state = seg6_end_dt4_build,
1632 				  },
1633 #endif
1634 	},
1635 	{
1636 		.action		= SEG6_LOCAL_ACTION_END_DT6,
1637 #ifdef CONFIG_NET_L3_MASTER_DEV
1638 		.attrs		= 0,
1639 		.optattrs	= SEG6_F_LOCAL_COUNTERS		|
1640 				  SEG6_F_ATTR(SEG6_LOCAL_TABLE) |
1641 				  SEG6_F_ATTR(SEG6_LOCAL_VRFTABLE),
1642 		.slwt_ops	= {
1643 					.build_state = seg6_end_dt6_build,
1644 				  },
1645 #else
1646 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_TABLE),
1647 		.optattrs	= SEG6_F_LOCAL_COUNTERS,
1648 #endif
1649 		.input		= input_action_end_dt6,
1650 	},
1651 	{
1652 		.action		= SEG6_LOCAL_ACTION_END_DT46,
1653 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_VRFTABLE),
1654 		.optattrs	= SEG6_F_LOCAL_COUNTERS,
1655 #ifdef CONFIG_NET_L3_MASTER_DEV
1656 		.input		= input_action_end_dt46,
1657 		.slwt_ops	= {
1658 					.build_state = seg6_end_dt46_build,
1659 				  },
1660 #endif
1661 	},
1662 	{
1663 		.action		= SEG6_LOCAL_ACTION_END_B6,
1664 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_SRH),
1665 		.optattrs	= SEG6_F_LOCAL_COUNTERS,
1666 		.input		= input_action_end_b6,
1667 	},
1668 	{
1669 		.action		= SEG6_LOCAL_ACTION_END_B6_ENCAP,
1670 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_SRH),
1671 		.optattrs	= SEG6_F_LOCAL_COUNTERS,
1672 		.input		= input_action_end_b6_encap,
1673 		.static_headroom	= sizeof(struct ipv6hdr),
1674 	},
1675 	{
1676 		.action		= SEG6_LOCAL_ACTION_END_BPF,
1677 		.attrs		= SEG6_F_ATTR(SEG6_LOCAL_BPF),
1678 		.optattrs	= SEG6_F_LOCAL_COUNTERS,
1679 		.input		= input_action_end_bpf,
1680 	},
1681 
1682 };
1683 
1684 static struct seg6_action_desc *__get_action_desc(int action)
1685 {
1686 	struct seg6_action_desc *desc;
1687 	int i, count;
1688 
1689 	count = ARRAY_SIZE(seg6_action_table);
1690 	for (i = 0; i < count; i++) {
1691 		desc = &seg6_action_table[i];
1692 		if (desc->action == action)
1693 			return desc;
1694 	}
1695 
1696 	return NULL;
1697 }
1698 
1699 static bool seg6_lwtunnel_counters_enabled(struct seg6_local_lwt *slwt)
1700 {
1701 	return slwt->parsed_optattrs & SEG6_F_LOCAL_COUNTERS;
1702 }
1703 
1704 static void seg6_local_update_counters(struct seg6_local_lwt *slwt,
1705 				       unsigned int len, int err)
1706 {
1707 	struct pcpu_seg6_local_counters *pcounters;
1708 
1709 	pcounters = this_cpu_ptr(slwt->pcpu_counters);
1710 	u64_stats_update_begin(&pcounters->syncp);
1711 
1712 	if (likely(!err)) {
1713 		u64_stats_inc(&pcounters->packets);
1714 		u64_stats_add(&pcounters->bytes, len);
1715 	} else {
1716 		u64_stats_inc(&pcounters->errors);
1717 	}
1718 
1719 	u64_stats_update_end(&pcounters->syncp);
1720 }
1721 
1722 static int seg6_local_input_core(struct net *net, struct sock *sk,
1723 				 struct sk_buff *skb)
1724 {
1725 	struct dst_entry *orig_dst = skb_dst(skb);
1726 	struct seg6_action_desc *desc;
1727 	struct seg6_local_lwt *slwt;
1728 	unsigned int len = skb->len;
1729 	int rc;
1730 
1731 	slwt = seg6_local_lwtunnel(orig_dst->lwtstate);
1732 	desc = slwt->desc;
1733 
1734 	rc = desc->input(skb, slwt);
1735 
1736 	if (!seg6_lwtunnel_counters_enabled(slwt))
1737 		return rc;
1738 
1739 	seg6_local_update_counters(slwt, len, rc);
1740 
1741 	return rc;
1742 }
1743 
1744 static int seg6_local_input(struct sk_buff *skb)
1745 {
1746 	if (skb->protocol != htons(ETH_P_IPV6)) {
1747 		kfree_skb(skb);
1748 		return -EINVAL;
1749 	}
1750 
1751 	if (static_branch_unlikely(&nf_hooks_lwtunnel_enabled))
1752 		return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_IN,
1753 			       dev_net(skb->dev), NULL, skb, skb->dev, NULL,
1754 			       seg6_local_input_core);
1755 
1756 	return seg6_local_input_core(dev_net(skb->dev), NULL, skb);
1757 }
1758 
1759 static const struct nla_policy seg6_local_policy[SEG6_LOCAL_MAX + 1] = {
1760 	[SEG6_LOCAL_ACTION]	= { .type = NLA_U32 },
1761 	[SEG6_LOCAL_SRH]	= { .type = NLA_BINARY },
1762 	[SEG6_LOCAL_TABLE]	= { .type = NLA_U32 },
1763 	[SEG6_LOCAL_VRFTABLE]	= { .type = NLA_U32 },
1764 	[SEG6_LOCAL_NH4]	= NLA_POLICY_EXACT_LEN(sizeof(struct in_addr)),
1765 	[SEG6_LOCAL_NH6]	= NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
1766 	[SEG6_LOCAL_IIF]	= { .type = NLA_U32 },
1767 	[SEG6_LOCAL_OIF]	= { .type = NLA_U32 },
1768 	[SEG6_LOCAL_BPF]	= { .type = NLA_NESTED },
1769 	[SEG6_LOCAL_COUNTERS]	= { .type = NLA_NESTED },
1770 	[SEG6_LOCAL_FLAVORS]	= { .type = NLA_NESTED },
1771 };
1772 
1773 static int parse_nla_srh(struct nlattr **attrs, struct seg6_local_lwt *slwt,
1774 			 struct netlink_ext_ack *extack)
1775 {
1776 	struct ipv6_sr_hdr *srh;
1777 	int len;
1778 
1779 	srh = nla_data(attrs[SEG6_LOCAL_SRH]);
1780 	len = nla_len(attrs[SEG6_LOCAL_SRH]);
1781 
1782 	/* SRH must contain at least one segment */
1783 	if (len < sizeof(*srh) + sizeof(struct in6_addr))
1784 		return -EINVAL;
1785 
1786 	if (!seg6_validate_srh(srh, len, false))
1787 		return -EINVAL;
1788 
1789 	slwt->srh = kmemdup(srh, len, GFP_KERNEL);
1790 	if (!slwt->srh)
1791 		return -ENOMEM;
1792 
1793 	slwt->headroom += len;
1794 
1795 	return 0;
1796 }
1797 
1798 static int put_nla_srh(struct sk_buff *skb, struct seg6_local_lwt *slwt)
1799 {
1800 	struct ipv6_sr_hdr *srh;
1801 	struct nlattr *nla;
1802 	int len;
1803 
1804 	srh = slwt->srh;
1805 	len = (srh->hdrlen + 1) << 3;
1806 
1807 	nla = nla_reserve(skb, SEG6_LOCAL_SRH, len);
1808 	if (!nla)
1809 		return -EMSGSIZE;
1810 
1811 	memcpy(nla_data(nla), srh, len);
1812 
1813 	return 0;
1814 }
1815 
1816 static int cmp_nla_srh(struct seg6_local_lwt *a, struct seg6_local_lwt *b)
1817 {
1818 	int len = (a->srh->hdrlen + 1) << 3;
1819 
1820 	if (len != ((b->srh->hdrlen + 1) << 3))
1821 		return 1;
1822 
1823 	return memcmp(a->srh, b->srh, len);
1824 }
1825 
1826 static void destroy_attr_srh(struct seg6_local_lwt *slwt)
1827 {
1828 	kfree(slwt->srh);
1829 }
1830 
1831 static int parse_nla_table(struct nlattr **attrs, struct seg6_local_lwt *slwt,
1832 			   struct netlink_ext_ack *extack)
1833 {
1834 	slwt->table = nla_get_u32(attrs[SEG6_LOCAL_TABLE]);
1835 
1836 	return 0;
1837 }
1838 
1839 static int put_nla_table(struct sk_buff *skb, struct seg6_local_lwt *slwt)
1840 {
1841 	if (nla_put_u32(skb, SEG6_LOCAL_TABLE, slwt->table))
1842 		return -EMSGSIZE;
1843 
1844 	return 0;
1845 }
1846 
1847 static int cmp_nla_table(struct seg6_local_lwt *a, struct seg6_local_lwt *b)
1848 {
1849 	if (a->table != b->table)
1850 		return 1;
1851 
1852 	return 0;
1853 }
1854 
1855 static struct
1856 seg6_end_dt_info *seg6_possible_end_dt_info(struct seg6_local_lwt *slwt)
1857 {
1858 #ifdef CONFIG_NET_L3_MASTER_DEV
1859 	return &slwt->dt_info;
1860 #else
1861 	return ERR_PTR(-EOPNOTSUPP);
1862 #endif
1863 }
1864 
1865 static int parse_nla_vrftable(struct nlattr **attrs,
1866 			      struct seg6_local_lwt *slwt,
1867 			      struct netlink_ext_ack *extack)
1868 {
1869 	struct seg6_end_dt_info *info = seg6_possible_end_dt_info(slwt);
1870 
1871 	if (IS_ERR(info))
1872 		return PTR_ERR(info);
1873 
1874 	info->vrf_table = nla_get_u32(attrs[SEG6_LOCAL_VRFTABLE]);
1875 
1876 	return 0;
1877 }
1878 
1879 static int put_nla_vrftable(struct sk_buff *skb, struct seg6_local_lwt *slwt)
1880 {
1881 	struct seg6_end_dt_info *info = seg6_possible_end_dt_info(slwt);
1882 
1883 	if (IS_ERR(info))
1884 		return PTR_ERR(info);
1885 
1886 	if (nla_put_u32(skb, SEG6_LOCAL_VRFTABLE, info->vrf_table))
1887 		return -EMSGSIZE;
1888 
1889 	return 0;
1890 }
1891 
1892 static int cmp_nla_vrftable(struct seg6_local_lwt *a, struct seg6_local_lwt *b)
1893 {
1894 	struct seg6_end_dt_info *info_a = seg6_possible_end_dt_info(a);
1895 	struct seg6_end_dt_info *info_b = seg6_possible_end_dt_info(b);
1896 
1897 	if (info_a->vrf_table != info_b->vrf_table)
1898 		return 1;
1899 
1900 	return 0;
1901 }
1902 
1903 static int parse_nla_nh4(struct nlattr **attrs, struct seg6_local_lwt *slwt,
1904 			 struct netlink_ext_ack *extack)
1905 {
1906 	memcpy(&slwt->nh4, nla_data(attrs[SEG6_LOCAL_NH4]),
1907 	       sizeof(struct in_addr));
1908 
1909 	return 0;
1910 }
1911 
1912 static int put_nla_nh4(struct sk_buff *skb, struct seg6_local_lwt *slwt)
1913 {
1914 	struct nlattr *nla;
1915 
1916 	nla = nla_reserve(skb, SEG6_LOCAL_NH4, sizeof(struct in_addr));
1917 	if (!nla)
1918 		return -EMSGSIZE;
1919 
1920 	memcpy(nla_data(nla), &slwt->nh4, sizeof(struct in_addr));
1921 
1922 	return 0;
1923 }
1924 
1925 static int cmp_nla_nh4(struct seg6_local_lwt *a, struct seg6_local_lwt *b)
1926 {
1927 	return memcmp(&a->nh4, &b->nh4, sizeof(struct in_addr));
1928 }
1929 
1930 static int parse_nla_nh6(struct nlattr **attrs, struct seg6_local_lwt *slwt,
1931 			 struct netlink_ext_ack *extack)
1932 {
1933 	memcpy(&slwt->nh6, nla_data(attrs[SEG6_LOCAL_NH6]),
1934 	       sizeof(struct in6_addr));
1935 
1936 	return 0;
1937 }
1938 
1939 static int put_nla_nh6(struct sk_buff *skb, struct seg6_local_lwt *slwt)
1940 {
1941 	struct nlattr *nla;
1942 
1943 	nla = nla_reserve(skb, SEG6_LOCAL_NH6, sizeof(struct in6_addr));
1944 	if (!nla)
1945 		return -EMSGSIZE;
1946 
1947 	memcpy(nla_data(nla), &slwt->nh6, sizeof(struct in6_addr));
1948 
1949 	return 0;
1950 }
1951 
1952 static int cmp_nla_nh6(struct seg6_local_lwt *a, struct seg6_local_lwt *b)
1953 {
1954 	return memcmp(&a->nh6, &b->nh6, sizeof(struct in6_addr));
1955 }
1956 
1957 static int parse_nla_iif(struct nlattr **attrs, struct seg6_local_lwt *slwt,
1958 			 struct netlink_ext_ack *extack)
1959 {
1960 	slwt->iif = nla_get_u32(attrs[SEG6_LOCAL_IIF]);
1961 
1962 	return 0;
1963 }
1964 
1965 static int put_nla_iif(struct sk_buff *skb, struct seg6_local_lwt *slwt)
1966 {
1967 	if (nla_put_u32(skb, SEG6_LOCAL_IIF, slwt->iif))
1968 		return -EMSGSIZE;
1969 
1970 	return 0;
1971 }
1972 
1973 static int cmp_nla_iif(struct seg6_local_lwt *a, struct seg6_local_lwt *b)
1974 {
1975 	if (a->iif != b->iif)
1976 		return 1;
1977 
1978 	return 0;
1979 }
1980 
1981 static int parse_nla_oif(struct nlattr **attrs, struct seg6_local_lwt *slwt,
1982 			 struct netlink_ext_ack *extack)
1983 {
1984 	slwt->oif = nla_get_u32(attrs[SEG6_LOCAL_OIF]);
1985 
1986 	return 0;
1987 }
1988 
1989 static int put_nla_oif(struct sk_buff *skb, struct seg6_local_lwt *slwt)
1990 {
1991 	if (nla_put_u32(skb, SEG6_LOCAL_OIF, slwt->oif))
1992 		return -EMSGSIZE;
1993 
1994 	return 0;
1995 }
1996 
1997 static int cmp_nla_oif(struct seg6_local_lwt *a, struct seg6_local_lwt *b)
1998 {
1999 	if (a->oif != b->oif)
2000 		return 1;
2001 
2002 	return 0;
2003 }
2004 
2005 #define MAX_PROG_NAME 256
2006 static const struct nla_policy bpf_prog_policy[SEG6_LOCAL_BPF_PROG_MAX + 1] = {
2007 	[SEG6_LOCAL_BPF_PROG]	   = { .type = NLA_U32, },
2008 	[SEG6_LOCAL_BPF_PROG_NAME] = { .type = NLA_NUL_STRING,
2009 				       .len = MAX_PROG_NAME },
2010 };
2011 
2012 static int parse_nla_bpf(struct nlattr **attrs, struct seg6_local_lwt *slwt,
2013 			 struct netlink_ext_ack *extack)
2014 {
2015 	struct nlattr *tb[SEG6_LOCAL_BPF_PROG_MAX + 1];
2016 	struct bpf_prog *p;
2017 	int ret;
2018 	u32 fd;
2019 
2020 	ret = nla_parse_nested_deprecated(tb, SEG6_LOCAL_BPF_PROG_MAX,
2021 					  attrs[SEG6_LOCAL_BPF],
2022 					  bpf_prog_policy, NULL);
2023 	if (ret < 0)
2024 		return ret;
2025 
2026 	if (!tb[SEG6_LOCAL_BPF_PROG] || !tb[SEG6_LOCAL_BPF_PROG_NAME])
2027 		return -EINVAL;
2028 
2029 	slwt->bpf.name = nla_memdup(tb[SEG6_LOCAL_BPF_PROG_NAME], GFP_KERNEL);
2030 	if (!slwt->bpf.name)
2031 		return -ENOMEM;
2032 
2033 	fd = nla_get_u32(tb[SEG6_LOCAL_BPF_PROG]);
2034 	p = bpf_prog_get_type(fd, BPF_PROG_TYPE_LWT_SEG6LOCAL);
2035 	if (IS_ERR(p)) {
2036 		kfree(slwt->bpf.name);
2037 		return PTR_ERR(p);
2038 	}
2039 
2040 	slwt->bpf.prog = p;
2041 	return 0;
2042 }
2043 
2044 static int put_nla_bpf(struct sk_buff *skb, struct seg6_local_lwt *slwt)
2045 {
2046 	struct nlattr *nest;
2047 
2048 	if (!slwt->bpf.prog)
2049 		return 0;
2050 
2051 	nest = nla_nest_start_noflag(skb, SEG6_LOCAL_BPF);
2052 	if (!nest)
2053 		return -EMSGSIZE;
2054 
2055 	if (nla_put_u32(skb, SEG6_LOCAL_BPF_PROG, slwt->bpf.prog->aux->id))
2056 		return -EMSGSIZE;
2057 
2058 	if (slwt->bpf.name &&
2059 	    nla_put_string(skb, SEG6_LOCAL_BPF_PROG_NAME, slwt->bpf.name))
2060 		return -EMSGSIZE;
2061 
2062 	return nla_nest_end(skb, nest);
2063 }
2064 
2065 static int cmp_nla_bpf(struct seg6_local_lwt *a, struct seg6_local_lwt *b)
2066 {
2067 	if (!a->bpf.name && !b->bpf.name)
2068 		return 0;
2069 
2070 	if (!a->bpf.name || !b->bpf.name)
2071 		return 1;
2072 
2073 	return strcmp(a->bpf.name, b->bpf.name);
2074 }
2075 
2076 static void destroy_attr_bpf(struct seg6_local_lwt *slwt)
2077 {
2078 	kfree(slwt->bpf.name);
2079 	if (slwt->bpf.prog)
2080 		bpf_prog_put(slwt->bpf.prog);
2081 }
2082 
2083 static const struct
2084 nla_policy seg6_local_counters_policy[SEG6_LOCAL_CNT_MAX + 1] = {
2085 	[SEG6_LOCAL_CNT_PACKETS]	= { .type = NLA_U64 },
2086 	[SEG6_LOCAL_CNT_BYTES]		= { .type = NLA_U64 },
2087 	[SEG6_LOCAL_CNT_ERRORS]		= { .type = NLA_U64 },
2088 };
2089 
2090 static int parse_nla_counters(struct nlattr **attrs,
2091 			      struct seg6_local_lwt *slwt,
2092 			      struct netlink_ext_ack *extack)
2093 {
2094 	struct pcpu_seg6_local_counters __percpu *pcounters;
2095 	struct nlattr *tb[SEG6_LOCAL_CNT_MAX + 1];
2096 	int ret;
2097 
2098 	ret = nla_parse_nested_deprecated(tb, SEG6_LOCAL_CNT_MAX,
2099 					  attrs[SEG6_LOCAL_COUNTERS],
2100 					  seg6_local_counters_policy, NULL);
2101 	if (ret < 0)
2102 		return ret;
2103 
2104 	/* basic support for SRv6 Behavior counters requires at least:
2105 	 * packets, bytes and errors.
2106 	 */
2107 	if (!tb[SEG6_LOCAL_CNT_PACKETS] || !tb[SEG6_LOCAL_CNT_BYTES] ||
2108 	    !tb[SEG6_LOCAL_CNT_ERRORS])
2109 		return -EINVAL;
2110 
2111 	/* counters are always zero initialized */
2112 	pcounters = seg6_local_alloc_pcpu_counters(GFP_KERNEL);
2113 	if (!pcounters)
2114 		return -ENOMEM;
2115 
2116 	slwt->pcpu_counters = pcounters;
2117 
2118 	return 0;
2119 }
2120 
2121 static int seg6_local_fill_nla_counters(struct sk_buff *skb,
2122 					struct seg6_local_counters *counters)
2123 {
2124 	if (nla_put_u64_64bit(skb, SEG6_LOCAL_CNT_PACKETS, counters->packets,
2125 			      SEG6_LOCAL_CNT_PAD))
2126 		return -EMSGSIZE;
2127 
2128 	if (nla_put_u64_64bit(skb, SEG6_LOCAL_CNT_BYTES, counters->bytes,
2129 			      SEG6_LOCAL_CNT_PAD))
2130 		return -EMSGSIZE;
2131 
2132 	if (nla_put_u64_64bit(skb, SEG6_LOCAL_CNT_ERRORS, counters->errors,
2133 			      SEG6_LOCAL_CNT_PAD))
2134 		return -EMSGSIZE;
2135 
2136 	return 0;
2137 }
2138 
2139 static int put_nla_counters(struct sk_buff *skb, struct seg6_local_lwt *slwt)
2140 {
2141 	struct seg6_local_counters counters = { 0, 0, 0 };
2142 	struct nlattr *nest;
2143 	int rc, i;
2144 
2145 	nest = nla_nest_start(skb, SEG6_LOCAL_COUNTERS);
2146 	if (!nest)
2147 		return -EMSGSIZE;
2148 
2149 	for_each_possible_cpu(i) {
2150 		struct pcpu_seg6_local_counters *pcounters;
2151 		u64 packets, bytes, errors;
2152 		unsigned int start;
2153 
2154 		pcounters = per_cpu_ptr(slwt->pcpu_counters, i);
2155 		do {
2156 			start = u64_stats_fetch_begin(&pcounters->syncp);
2157 
2158 			packets = u64_stats_read(&pcounters->packets);
2159 			bytes = u64_stats_read(&pcounters->bytes);
2160 			errors = u64_stats_read(&pcounters->errors);
2161 
2162 		} while (u64_stats_fetch_retry(&pcounters->syncp, start));
2163 
2164 		counters.packets += packets;
2165 		counters.bytes += bytes;
2166 		counters.errors += errors;
2167 	}
2168 
2169 	rc = seg6_local_fill_nla_counters(skb, &counters);
2170 	if (rc < 0) {
2171 		nla_nest_cancel(skb, nest);
2172 		return rc;
2173 	}
2174 
2175 	return nla_nest_end(skb, nest);
2176 }
2177 
2178 static int cmp_nla_counters(struct seg6_local_lwt *a, struct seg6_local_lwt *b)
2179 {
2180 	/* a and b are equal if both have pcpu_counters set or not */
2181 	return (!!((unsigned long)a->pcpu_counters)) ^
2182 		(!!((unsigned long)b->pcpu_counters));
2183 }
2184 
2185 static void destroy_attr_counters(struct seg6_local_lwt *slwt)
2186 {
2187 	free_percpu(slwt->pcpu_counters);
2188 }
2189 
2190 static const
2191 struct nla_policy seg6_local_flavors_policy[SEG6_LOCAL_FLV_MAX + 1] = {
2192 	[SEG6_LOCAL_FLV_OPERATION]	= { .type = NLA_U32 },
2193 	[SEG6_LOCAL_FLV_LCBLOCK_BITS]	= { .type = NLA_U8 },
2194 	[SEG6_LOCAL_FLV_LCNODE_FN_BITS]	= { .type = NLA_U8 },
2195 };
2196 
2197 /* check whether the lengths of the Locator-Block and Locator-Node Function
2198  * are compatible with the dimension of a C-SID container.
2199  */
2200 static int seg6_chk_next_csid_cfg(__u8 block_len, __u8 func_len)
2201 {
2202 	/* Locator-Block and Locator-Node Function cannot exceed 128 bits
2203 	 * (i.e. C-SID container length).
2204 	 */
2205 	if (next_csid_chk_cntr_bits(block_len, func_len))
2206 		return -EINVAL;
2207 
2208 	/* Locator-Block length must be greater than zero and evenly divisible
2209 	 * by 8. There must be room for a Locator-Node Function, at least.
2210 	 */
2211 	if (next_csid_chk_lcblock_bits(block_len))
2212 		return -EINVAL;
2213 
2214 	/* Locator-Node Function length must be greater than zero and evenly
2215 	 * divisible by 8. There must be room for the Locator-Block.
2216 	 */
2217 	if (next_csid_chk_lcnode_fn_bits(func_len))
2218 		return -EINVAL;
2219 
2220 	return 0;
2221 }
2222 
2223 static int seg6_parse_nla_next_csid_cfg(struct nlattr **tb,
2224 					struct seg6_flavors_info *finfo,
2225 					struct netlink_ext_ack *extack)
2226 {
2227 	__u8 func_len = SEG6_LOCAL_LCNODE_FN_DBITS;
2228 	__u8 block_len = SEG6_LOCAL_LCBLOCK_DBITS;
2229 	int rc;
2230 
2231 	if (tb[SEG6_LOCAL_FLV_LCBLOCK_BITS])
2232 		block_len = nla_get_u8(tb[SEG6_LOCAL_FLV_LCBLOCK_BITS]);
2233 
2234 	if (tb[SEG6_LOCAL_FLV_LCNODE_FN_BITS])
2235 		func_len = nla_get_u8(tb[SEG6_LOCAL_FLV_LCNODE_FN_BITS]);
2236 
2237 	rc = seg6_chk_next_csid_cfg(block_len, func_len);
2238 	if (rc < 0) {
2239 		NL_SET_ERR_MSG(extack,
2240 			       "Invalid Locator Block/Node Function lengths");
2241 		return rc;
2242 	}
2243 
2244 	finfo->lcblock_bits = block_len;
2245 	finfo->lcnode_func_bits = func_len;
2246 
2247 	return 0;
2248 }
2249 
2250 static int parse_nla_flavors(struct nlattr **attrs, struct seg6_local_lwt *slwt,
2251 			     struct netlink_ext_ack *extack)
2252 {
2253 	struct seg6_flavors_info *finfo = &slwt->flv_info;
2254 	struct nlattr *tb[SEG6_LOCAL_FLV_MAX + 1];
2255 	int action = slwt->action;
2256 	__u32 fops, supp_fops;
2257 	int rc;
2258 
2259 	rc = nla_parse_nested_deprecated(tb, SEG6_LOCAL_FLV_MAX,
2260 					 attrs[SEG6_LOCAL_FLAVORS],
2261 					 seg6_local_flavors_policy, NULL);
2262 	if (rc < 0)
2263 		return rc;
2264 
2265 	/* this attribute MUST always be present since it represents the Flavor
2266 	 * operation(s) to be carried out.
2267 	 */
2268 	if (!tb[SEG6_LOCAL_FLV_OPERATION])
2269 		return -EINVAL;
2270 
2271 	fops = nla_get_u32(tb[SEG6_LOCAL_FLV_OPERATION]);
2272 	rc = seg6_flv_supp_ops_by_action(action, &supp_fops);
2273 	if (rc < 0 || (fops & ~supp_fops)) {
2274 		NL_SET_ERR_MSG(extack, "Unsupported Flavor operation(s)");
2275 		return -EOPNOTSUPP;
2276 	}
2277 
2278 	finfo->flv_ops = fops;
2279 
2280 	if (seg6_next_csid_enabled(fops)) {
2281 		/* Locator-Block and Locator-Node Function lengths can be
2282 		 * provided by the user space. Otherwise, default values are
2283 		 * applied.
2284 		 */
2285 		rc = seg6_parse_nla_next_csid_cfg(tb, finfo, extack);
2286 		if (rc < 0)
2287 			return rc;
2288 	}
2289 
2290 	return 0;
2291 }
2292 
2293 static int seg6_fill_nla_next_csid_cfg(struct sk_buff *skb,
2294 				       struct seg6_flavors_info *finfo)
2295 {
2296 	if (nla_put_u8(skb, SEG6_LOCAL_FLV_LCBLOCK_BITS, finfo->lcblock_bits))
2297 		return -EMSGSIZE;
2298 
2299 	if (nla_put_u8(skb, SEG6_LOCAL_FLV_LCNODE_FN_BITS,
2300 		       finfo->lcnode_func_bits))
2301 		return -EMSGSIZE;
2302 
2303 	return 0;
2304 }
2305 
2306 static int put_nla_flavors(struct sk_buff *skb, struct seg6_local_lwt *slwt)
2307 {
2308 	struct seg6_flavors_info *finfo = &slwt->flv_info;
2309 	__u32 fops = finfo->flv_ops;
2310 	struct nlattr *nest;
2311 	int rc;
2312 
2313 	nest = nla_nest_start(skb, SEG6_LOCAL_FLAVORS);
2314 	if (!nest)
2315 		return -EMSGSIZE;
2316 
2317 	if (nla_put_u32(skb, SEG6_LOCAL_FLV_OPERATION, fops)) {
2318 		rc = -EMSGSIZE;
2319 		goto err;
2320 	}
2321 
2322 	if (seg6_next_csid_enabled(fops)) {
2323 		rc = seg6_fill_nla_next_csid_cfg(skb, finfo);
2324 		if (rc < 0)
2325 			goto err;
2326 	}
2327 
2328 	return nla_nest_end(skb, nest);
2329 
2330 err:
2331 	nla_nest_cancel(skb, nest);
2332 	return rc;
2333 }
2334 
2335 static int seg6_cmp_nla_next_csid_cfg(struct seg6_flavors_info *finfo_a,
2336 				      struct seg6_flavors_info *finfo_b)
2337 {
2338 	if (finfo_a->lcblock_bits != finfo_b->lcblock_bits)
2339 		return 1;
2340 
2341 	if (finfo_a->lcnode_func_bits != finfo_b->lcnode_func_bits)
2342 		return 1;
2343 
2344 	return 0;
2345 }
2346 
2347 static int cmp_nla_flavors(struct seg6_local_lwt *a, struct seg6_local_lwt *b)
2348 {
2349 	struct seg6_flavors_info *finfo_a = &a->flv_info;
2350 	struct seg6_flavors_info *finfo_b = &b->flv_info;
2351 
2352 	if (finfo_a->flv_ops != finfo_b->flv_ops)
2353 		return 1;
2354 
2355 	if (seg6_next_csid_enabled(finfo_a->flv_ops)) {
2356 		if (seg6_cmp_nla_next_csid_cfg(finfo_a, finfo_b))
2357 			return 1;
2358 	}
2359 
2360 	return 0;
2361 }
2362 
2363 static int encap_size_flavors(struct seg6_local_lwt *slwt)
2364 {
2365 	struct seg6_flavors_info *finfo = &slwt->flv_info;
2366 	int nlsize;
2367 
2368 	nlsize = nla_total_size(0) +	/* nest SEG6_LOCAL_FLAVORS */
2369 		 nla_total_size(4);	/* SEG6_LOCAL_FLV_OPERATION */
2370 
2371 	if (seg6_next_csid_enabled(finfo->flv_ops))
2372 		nlsize += nla_total_size(1) + /* SEG6_LOCAL_FLV_LCBLOCK_BITS */
2373 			  nla_total_size(1); /* SEG6_LOCAL_FLV_LCNODE_FN_BITS */
2374 
2375 	return nlsize;
2376 }
2377 
2378 struct seg6_action_param {
2379 	int (*parse)(struct nlattr **attrs, struct seg6_local_lwt *slwt,
2380 		     struct netlink_ext_ack *extack);
2381 	int (*put)(struct sk_buff *skb, struct seg6_local_lwt *slwt);
2382 	int (*cmp)(struct seg6_local_lwt *a, struct seg6_local_lwt *b);
2383 
2384 	/* optional destroy() callback useful for releasing resources which
2385 	 * have been previously acquired in the corresponding parse()
2386 	 * function.
2387 	 */
2388 	void (*destroy)(struct seg6_local_lwt *slwt);
2389 };
2390 
2391 static struct seg6_action_param seg6_action_params[SEG6_LOCAL_MAX + 1] = {
2392 	[SEG6_LOCAL_SRH]	= { .parse = parse_nla_srh,
2393 				    .put = put_nla_srh,
2394 				    .cmp = cmp_nla_srh,
2395 				    .destroy = destroy_attr_srh },
2396 
2397 	[SEG6_LOCAL_TABLE]	= { .parse = parse_nla_table,
2398 				    .put = put_nla_table,
2399 				    .cmp = cmp_nla_table },
2400 
2401 	[SEG6_LOCAL_NH4]	= { .parse = parse_nla_nh4,
2402 				    .put = put_nla_nh4,
2403 				    .cmp = cmp_nla_nh4 },
2404 
2405 	[SEG6_LOCAL_NH6]	= { .parse = parse_nla_nh6,
2406 				    .put = put_nla_nh6,
2407 				    .cmp = cmp_nla_nh6 },
2408 
2409 	[SEG6_LOCAL_IIF]	= { .parse = parse_nla_iif,
2410 				    .put = put_nla_iif,
2411 				    .cmp = cmp_nla_iif },
2412 
2413 	[SEG6_LOCAL_OIF]	= { .parse = parse_nla_oif,
2414 				    .put = put_nla_oif,
2415 				    .cmp = cmp_nla_oif },
2416 
2417 	[SEG6_LOCAL_BPF]	= { .parse = parse_nla_bpf,
2418 				    .put = put_nla_bpf,
2419 				    .cmp = cmp_nla_bpf,
2420 				    .destroy = destroy_attr_bpf },
2421 
2422 	[SEG6_LOCAL_VRFTABLE]	= { .parse = parse_nla_vrftable,
2423 				    .put = put_nla_vrftable,
2424 				    .cmp = cmp_nla_vrftable },
2425 
2426 	[SEG6_LOCAL_COUNTERS]	= { .parse = parse_nla_counters,
2427 				    .put = put_nla_counters,
2428 				    .cmp = cmp_nla_counters,
2429 				    .destroy = destroy_attr_counters },
2430 
2431 	[SEG6_LOCAL_FLAVORS]	= { .parse = parse_nla_flavors,
2432 				    .put = put_nla_flavors,
2433 				    .cmp = cmp_nla_flavors },
2434 };
2435 
2436 /* call the destroy() callback (if available) for each set attribute in
2437  * @parsed_attrs, starting from the first attribute up to the @max_parsed
2438  * (excluded) attribute.
2439  */
2440 static void __destroy_attrs(unsigned long parsed_attrs, int max_parsed,
2441 			    struct seg6_local_lwt *slwt)
2442 {
2443 	struct seg6_action_param *param;
2444 	int i;
2445 
2446 	/* Every required seg6local attribute is identified by an ID which is
2447 	 * encoded as a flag (i.e: 1 << ID) in the 'attrs' bitmask;
2448 	 *
2449 	 * We scan the 'parsed_attrs' bitmask, starting from the first attribute
2450 	 * up to the @max_parsed (excluded) attribute.
2451 	 * For each set attribute, we retrieve the corresponding destroy()
2452 	 * callback. If the callback is not available, then we skip to the next
2453 	 * attribute; otherwise, we call the destroy() callback.
2454 	 */
2455 	for (i = SEG6_LOCAL_SRH; i < max_parsed; ++i) {
2456 		if (!(parsed_attrs & SEG6_F_ATTR(i)))
2457 			continue;
2458 
2459 		param = &seg6_action_params[i];
2460 
2461 		if (param->destroy)
2462 			param->destroy(slwt);
2463 	}
2464 }
2465 
2466 /* release all the resources that may have been acquired during parsing
2467  * operations.
2468  */
2469 static void destroy_attrs(struct seg6_local_lwt *slwt)
2470 {
2471 	unsigned long attrs = slwt->desc->attrs | slwt->parsed_optattrs;
2472 
2473 	__destroy_attrs(attrs, SEG6_LOCAL_MAX + 1, slwt);
2474 }
2475 
2476 static int parse_nla_optional_attrs(struct nlattr **attrs,
2477 				    struct seg6_local_lwt *slwt,
2478 				    struct netlink_ext_ack *extack)
2479 {
2480 	struct seg6_action_desc *desc = slwt->desc;
2481 	unsigned long parsed_optattrs = 0;
2482 	struct seg6_action_param *param;
2483 	int err, i;
2484 
2485 	for (i = SEG6_LOCAL_SRH; i < SEG6_LOCAL_MAX + 1; ++i) {
2486 		if (!(desc->optattrs & SEG6_F_ATTR(i)) || !attrs[i])
2487 			continue;
2488 
2489 		/* once here, the i-th attribute is provided by the
2490 		 * userspace AND it is identified optional as well.
2491 		 */
2492 		param = &seg6_action_params[i];
2493 
2494 		err = param->parse(attrs, slwt, extack);
2495 		if (err < 0)
2496 			goto parse_optattrs_err;
2497 
2498 		/* current attribute has been correctly parsed */
2499 		parsed_optattrs |= SEG6_F_ATTR(i);
2500 	}
2501 
2502 	/* store in the tunnel state all the optional attributed successfully
2503 	 * parsed.
2504 	 */
2505 	slwt->parsed_optattrs = parsed_optattrs;
2506 
2507 	return 0;
2508 
2509 parse_optattrs_err:
2510 	__destroy_attrs(parsed_optattrs, i, slwt);
2511 
2512 	return err;
2513 }
2514 
2515 /* call the custom constructor of the behavior during its initialization phase
2516  * and after that all its attributes have been parsed successfully.
2517  */
2518 static int
2519 seg6_local_lwtunnel_build_state(struct seg6_local_lwt *slwt, const void *cfg,
2520 				struct netlink_ext_ack *extack)
2521 {
2522 	struct seg6_action_desc *desc = slwt->desc;
2523 	struct seg6_local_lwtunnel_ops *ops;
2524 
2525 	ops = &desc->slwt_ops;
2526 	if (!ops->build_state)
2527 		return 0;
2528 
2529 	return ops->build_state(slwt, cfg, extack);
2530 }
2531 
2532 /* call the custom destructor of the behavior which is invoked before the
2533  * tunnel is going to be destroyed.
2534  */
2535 static void seg6_local_lwtunnel_destroy_state(struct seg6_local_lwt *slwt)
2536 {
2537 	struct seg6_action_desc *desc = slwt->desc;
2538 	struct seg6_local_lwtunnel_ops *ops;
2539 
2540 	ops = &desc->slwt_ops;
2541 	if (!ops->destroy_state)
2542 		return;
2543 
2544 	ops->destroy_state(slwt);
2545 }
2546 
2547 static int parse_nla_action(struct nlattr **attrs, struct seg6_local_lwt *slwt,
2548 			    struct netlink_ext_ack *extack)
2549 {
2550 	struct seg6_action_param *param;
2551 	struct seg6_action_desc *desc;
2552 	unsigned long invalid_attrs;
2553 	int i, err;
2554 
2555 	desc = __get_action_desc(slwt->action);
2556 	if (!desc)
2557 		return -EINVAL;
2558 
2559 	if (!desc->input)
2560 		return -EOPNOTSUPP;
2561 
2562 	slwt->desc = desc;
2563 	slwt->headroom += desc->static_headroom;
2564 
2565 	/* Forcing the desc->optattrs *set* and the desc->attrs *set* to be
2566 	 * disjoined, this allow us to release acquired resources by optional
2567 	 * attributes and by required attributes independently from each other
2568 	 * without any interference.
2569 	 * In other terms, we are sure that we do not release some the acquired
2570 	 * resources twice.
2571 	 *
2572 	 * Note that if an attribute is configured both as required and as
2573 	 * optional, it means that the user has messed something up in the
2574 	 * seg6_action_table. Therefore, this check is required for SRv6
2575 	 * behaviors to work properly.
2576 	 */
2577 	invalid_attrs = desc->attrs & desc->optattrs;
2578 	if (invalid_attrs) {
2579 		WARN_ONCE(1,
2580 			  "An attribute cannot be both required AND optional");
2581 		return -EINVAL;
2582 	}
2583 
2584 	/* parse the required attributes */
2585 	for (i = SEG6_LOCAL_SRH; i < SEG6_LOCAL_MAX + 1; i++) {
2586 		if (desc->attrs & SEG6_F_ATTR(i)) {
2587 			if (!attrs[i])
2588 				return -EINVAL;
2589 
2590 			param = &seg6_action_params[i];
2591 
2592 			err = param->parse(attrs, slwt, extack);
2593 			if (err < 0)
2594 				goto parse_attrs_err;
2595 		}
2596 	}
2597 
2598 	/* parse the optional attributes, if any */
2599 	err = parse_nla_optional_attrs(attrs, slwt, extack);
2600 	if (err < 0)
2601 		goto parse_attrs_err;
2602 
2603 	return 0;
2604 
2605 parse_attrs_err:
2606 	/* release any resource that may have been acquired during the i-1
2607 	 * parse() operations.
2608 	 */
2609 	__destroy_attrs(desc->attrs, i, slwt);
2610 
2611 	return err;
2612 }
2613 
2614 static int seg6_local_build_state(struct net *net, struct nlattr *nla,
2615 				  unsigned int family, const void *cfg,
2616 				  struct lwtunnel_state **ts,
2617 				  struct netlink_ext_ack *extack)
2618 {
2619 	struct nlattr *tb[SEG6_LOCAL_MAX + 1];
2620 	struct lwtunnel_state *newts;
2621 	struct seg6_local_lwt *slwt;
2622 	int err;
2623 
2624 	if (family != AF_INET6)
2625 		return -EINVAL;
2626 
2627 	err = nla_parse_nested_deprecated(tb, SEG6_LOCAL_MAX, nla,
2628 					  seg6_local_policy, extack);
2629 
2630 	if (err < 0)
2631 		return err;
2632 
2633 	if (!tb[SEG6_LOCAL_ACTION])
2634 		return -EINVAL;
2635 
2636 	newts = lwtunnel_state_alloc(sizeof(*slwt));
2637 	if (!newts)
2638 		return -ENOMEM;
2639 
2640 	slwt = seg6_local_lwtunnel(newts);
2641 	slwt->action = nla_get_u32(tb[SEG6_LOCAL_ACTION]);
2642 
2643 	err = parse_nla_action(tb, slwt, extack);
2644 	if (err < 0)
2645 		goto out_free;
2646 
2647 	err = seg6_local_lwtunnel_build_state(slwt, cfg, extack);
2648 	if (err < 0)
2649 		goto out_destroy_attrs;
2650 
2651 	newts->type = LWTUNNEL_ENCAP_SEG6_LOCAL;
2652 	newts->flags = LWTUNNEL_STATE_INPUT_REDIRECT;
2653 	newts->headroom = slwt->headroom;
2654 
2655 	*ts = newts;
2656 
2657 	return 0;
2658 
2659 out_destroy_attrs:
2660 	destroy_attrs(slwt);
2661 out_free:
2662 	kfree(newts);
2663 	return err;
2664 }
2665 
2666 static void seg6_local_destroy_state(struct lwtunnel_state *lwt)
2667 {
2668 	struct seg6_local_lwt *slwt = seg6_local_lwtunnel(lwt);
2669 
2670 	seg6_local_lwtunnel_destroy_state(slwt);
2671 
2672 	destroy_attrs(slwt);
2673 
2674 	return;
2675 }
2676 
2677 static int seg6_local_fill_encap(struct sk_buff *skb,
2678 				 struct lwtunnel_state *lwt)
2679 {
2680 	struct seg6_local_lwt *slwt = seg6_local_lwtunnel(lwt);
2681 	struct seg6_action_param *param;
2682 	unsigned long attrs;
2683 	int i, err;
2684 
2685 	if (nla_put_u32(skb, SEG6_LOCAL_ACTION, slwt->action))
2686 		return -EMSGSIZE;
2687 
2688 	attrs = slwt->desc->attrs | slwt->parsed_optattrs;
2689 
2690 	for (i = SEG6_LOCAL_SRH; i < SEG6_LOCAL_MAX + 1; i++) {
2691 		if (attrs & SEG6_F_ATTR(i)) {
2692 			param = &seg6_action_params[i];
2693 			err = param->put(skb, slwt);
2694 			if (err < 0)
2695 				return err;
2696 		}
2697 	}
2698 
2699 	return 0;
2700 }
2701 
2702 static int seg6_local_get_encap_size(struct lwtunnel_state *lwt)
2703 {
2704 	struct seg6_local_lwt *slwt = seg6_local_lwtunnel(lwt);
2705 	unsigned long attrs;
2706 	int nlsize;
2707 
2708 	nlsize = nla_total_size(4); /* action */
2709 
2710 	attrs = slwt->desc->attrs | slwt->parsed_optattrs;
2711 
2712 	if (attrs & SEG6_F_ATTR(SEG6_LOCAL_SRH))
2713 		nlsize += nla_total_size((slwt->srh->hdrlen + 1) << 3);
2714 
2715 	if (attrs & SEG6_F_ATTR(SEG6_LOCAL_TABLE))
2716 		nlsize += nla_total_size(4);
2717 
2718 	if (attrs & SEG6_F_ATTR(SEG6_LOCAL_NH4))
2719 		nlsize += nla_total_size(4);
2720 
2721 	if (attrs & SEG6_F_ATTR(SEG6_LOCAL_NH6))
2722 		nlsize += nla_total_size(16);
2723 
2724 	if (attrs & SEG6_F_ATTR(SEG6_LOCAL_IIF))
2725 		nlsize += nla_total_size(4);
2726 
2727 	if (attrs & SEG6_F_ATTR(SEG6_LOCAL_OIF))
2728 		nlsize += nla_total_size(4);
2729 
2730 	if (attrs & SEG6_F_ATTR(SEG6_LOCAL_BPF))
2731 		nlsize += nla_total_size(sizeof(struct nlattr)) +
2732 		       nla_total_size(MAX_PROG_NAME) +
2733 		       nla_total_size(4);
2734 
2735 	if (attrs & SEG6_F_ATTR(SEG6_LOCAL_VRFTABLE))
2736 		nlsize += nla_total_size(4);
2737 
2738 	if (attrs & SEG6_F_LOCAL_COUNTERS)
2739 		nlsize += nla_total_size(0) + /* nest SEG6_LOCAL_COUNTERS */
2740 			  /* SEG6_LOCAL_CNT_PACKETS */
2741 			  nla_total_size_64bit(sizeof(__u64)) +
2742 			  /* SEG6_LOCAL_CNT_BYTES */
2743 			  nla_total_size_64bit(sizeof(__u64)) +
2744 			  /* SEG6_LOCAL_CNT_ERRORS */
2745 			  nla_total_size_64bit(sizeof(__u64));
2746 
2747 	if (attrs & SEG6_F_ATTR(SEG6_LOCAL_FLAVORS))
2748 		nlsize += encap_size_flavors(slwt);
2749 
2750 	return nlsize;
2751 }
2752 
2753 static int seg6_local_cmp_encap(struct lwtunnel_state *a,
2754 				struct lwtunnel_state *b)
2755 {
2756 	struct seg6_local_lwt *slwt_a, *slwt_b;
2757 	struct seg6_action_param *param;
2758 	unsigned long attrs_a, attrs_b;
2759 	int i;
2760 
2761 	slwt_a = seg6_local_lwtunnel(a);
2762 	slwt_b = seg6_local_lwtunnel(b);
2763 
2764 	if (slwt_a->action != slwt_b->action)
2765 		return 1;
2766 
2767 	attrs_a = slwt_a->desc->attrs | slwt_a->parsed_optattrs;
2768 	attrs_b = slwt_b->desc->attrs | slwt_b->parsed_optattrs;
2769 
2770 	if (attrs_a != attrs_b)
2771 		return 1;
2772 
2773 	for (i = SEG6_LOCAL_SRH; i < SEG6_LOCAL_MAX + 1; i++) {
2774 		if (attrs_a & SEG6_F_ATTR(i)) {
2775 			param = &seg6_action_params[i];
2776 			if (param->cmp(slwt_a, slwt_b))
2777 				return 1;
2778 		}
2779 	}
2780 
2781 	return 0;
2782 }
2783 
2784 static const struct lwtunnel_encap_ops seg6_local_ops = {
2785 	.build_state	= seg6_local_build_state,
2786 	.destroy_state	= seg6_local_destroy_state,
2787 	.input		= seg6_local_input,
2788 	.fill_encap	= seg6_local_fill_encap,
2789 	.get_encap_size	= seg6_local_get_encap_size,
2790 	.cmp_encap	= seg6_local_cmp_encap,
2791 	.owner		= THIS_MODULE,
2792 };
2793 
2794 int __init seg6_local_init(void)
2795 {
2796 	/* If the max total number of defined attributes is reached, then your
2797 	 * kernel build stops here.
2798 	 *
2799 	 * This check is required to avoid arithmetic overflows when processing
2800 	 * behavior attributes and the maximum number of defined attributes
2801 	 * exceeds the allowed value.
2802 	 */
2803 	BUILD_BUG_ON(SEG6_LOCAL_MAX + 1 > BITS_PER_TYPE(unsigned long));
2804 
2805 	/* Check whether the number of defined flavors exceeds the maximum
2806 	 * allowed value.
2807 	 */
2808 	BUILD_BUG_ON(SEG6_LOCAL_FLV_OP_MAX + 1 > BITS_PER_TYPE(__u32));
2809 
2810 	/* If the default NEXT-C-SID Locator-Block/Node Function lengths (in
2811 	 * bits) have been changed with invalid values, kernel build stops
2812 	 * here.
2813 	 */
2814 	BUILD_BUG_ON(next_csid_chk_cntr_bits(SEG6_LOCAL_LCBLOCK_DBITS,
2815 					     SEG6_LOCAL_LCNODE_FN_DBITS));
2816 	BUILD_BUG_ON(next_csid_chk_lcblock_bits(SEG6_LOCAL_LCBLOCK_DBITS));
2817 	BUILD_BUG_ON(next_csid_chk_lcnode_fn_bits(SEG6_LOCAL_LCNODE_FN_DBITS));
2818 
2819 	/* To be memory efficient, we use 'u8' to represent the different
2820 	 * actions related to RFC8986 flavors. If the kernel build stops here,
2821 	 * it means that it is not possible to correctly encode these actions
2822 	 * with the data type chosen for the action table.
2823 	 */
2824 	BUILD_BUG_ON(SEG6_LOCAL_FLV_ACT_MAX > (typeof(flv8986_act_tbl[0]))~0U);
2825 
2826 	return lwtunnel_encap_add_ops(&seg6_local_ops,
2827 				      LWTUNNEL_ENCAP_SEG6_LOCAL);
2828 }
2829 
2830 void seg6_local_exit(void)
2831 {
2832 	lwtunnel_encap_del_ops(&seg6_local_ops, LWTUNNEL_ENCAP_SEG6_LOCAL);
2833 }
2834