xref: /linux/net/openvswitch/flow.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2007-2014 Nicira, Inc.
4  */
5 
6 #include <linux/uaccess.h>
7 #include <linux/netdevice.h>
8 #include <linux/etherdevice.h>
9 #include <linux/if_ether.h>
10 #include <linux/if_vlan.h>
11 #include <linux/kernel.h>
12 #include <linux/jhash.h>
13 #include <linux/jiffies.h>
14 #include <linux/llc.h>
15 #include <linux/module.h>
16 #include <linux/in.h>
17 #include <linux/rcupdate.h>
18 #include <linux/cpumask.h>
19 #include <linux/if_arp.h>
20 #include <linux/ip.h>
21 #include <linux/ipv6.h>
22 #include <linux/mpls.h>
23 #include <linux/sctp.h>
24 #include <linux/smp.h>
25 #include <linux/tcp.h>
26 #include <linux/udp.h>
27 #include <linux/icmp.h>
28 #include <linux/icmpv6.h>
29 #include <linux/rculist.h>
30 #include <net/ip.h>
31 #include <net/ip_tunnels.h>
32 #include <net/ipv6.h>
33 #include <net/mpls.h>
34 #include <net/ndisc.h>
35 #include <net/nsh.h>
36 #include <net/pkt_cls.h>
37 #include <net/netfilter/nf_conntrack_zones.h>
38 
39 #include "conntrack.h"
40 #include "datapath.h"
41 #include "flow.h"
42 #include "flow_netlink.h"
43 #include "vport.h"
44 
45 u64 ovs_flow_used_time(unsigned long flow_jiffies)
46 {
47 	struct timespec64 cur_ts;
48 	u64 cur_ms, idle_ms;
49 
50 	ktime_get_ts64(&cur_ts);
51 	idle_ms = jiffies_to_msecs(jiffies - flow_jiffies);
52 	cur_ms = (u64)(u32)cur_ts.tv_sec * MSEC_PER_SEC +
53 		 cur_ts.tv_nsec / NSEC_PER_MSEC;
54 
55 	return cur_ms - idle_ms;
56 }
57 
58 #define TCP_FLAGS_BE16(tp) (*(__be16 *)&tcp_flag_word(tp) & htons(0x0FFF))
59 
60 void ovs_flow_stats_update(struct sw_flow *flow, __be16 tcp_flags,
61 			   const struct sk_buff *skb)
62 {
63 	struct sw_flow_stats *stats;
64 	unsigned int cpu = smp_processor_id();
65 	int len = skb->len + (skb_vlan_tag_present(skb) ? VLAN_HLEN : 0);
66 
67 	stats = rcu_dereference(flow->stats[cpu]);
68 
69 	/* Check if already have CPU-specific stats. */
70 	if (likely(stats)) {
71 		spin_lock(&stats->lock);
72 		/* Mark if we write on the pre-allocated stats. */
73 		if (cpu == 0 && unlikely(flow->stats_last_writer != cpu))
74 			flow->stats_last_writer = cpu;
75 	} else {
76 		stats = rcu_dereference(flow->stats[0]); /* Pre-allocated. */
77 		spin_lock(&stats->lock);
78 
79 		/* If the current CPU is the only writer on the
80 		 * pre-allocated stats keep using them.
81 		 */
82 		if (unlikely(flow->stats_last_writer != cpu)) {
83 			/* A previous locker may have already allocated the
84 			 * stats, so we need to check again.  If CPU-specific
85 			 * stats were already allocated, we update the pre-
86 			 * allocated stats as we have already locked them.
87 			 */
88 			if (likely(flow->stats_last_writer != -1) &&
89 			    likely(!rcu_access_pointer(flow->stats[cpu]))) {
90 				/* Try to allocate CPU-specific stats. */
91 				struct sw_flow_stats *new_stats;
92 
93 				new_stats =
94 					kmem_cache_alloc_node(flow_stats_cache,
95 							      GFP_NOWAIT |
96 							      __GFP_THISNODE |
97 							      __GFP_NOWARN |
98 							      __GFP_NOMEMALLOC,
99 							      numa_node_id());
100 				if (likely(new_stats)) {
101 					new_stats->used = jiffies;
102 					new_stats->packet_count = 1;
103 					new_stats->byte_count = len;
104 					new_stats->tcp_flags = tcp_flags;
105 					spin_lock_init(&new_stats->lock);
106 
107 					rcu_assign_pointer(flow->stats[cpu],
108 							   new_stats);
109 					cpumask_set_cpu(cpu,
110 							flow->cpu_used_mask);
111 					goto unlock;
112 				}
113 			}
114 			flow->stats_last_writer = cpu;
115 		}
116 	}
117 
118 	stats->used = jiffies;
119 	stats->packet_count++;
120 	stats->byte_count += len;
121 	stats->tcp_flags |= tcp_flags;
122 unlock:
123 	spin_unlock(&stats->lock);
124 }
125 
126 /* Must be called with rcu_read_lock or ovs_mutex. */
127 void ovs_flow_stats_get(const struct sw_flow *flow,
128 			struct ovs_flow_stats *ovs_stats,
129 			unsigned long *used, __be16 *tcp_flags)
130 {
131 	unsigned int cpu;
132 
133 	*used = 0;
134 	*tcp_flags = 0;
135 	memset(ovs_stats, 0, sizeof(*ovs_stats));
136 
137 	for_each_cpu(cpu, flow->cpu_used_mask) {
138 		struct sw_flow_stats *stats = rcu_dereference_ovsl(flow->stats[cpu]);
139 
140 		if (stats) {
141 			/* Local CPU may write on non-local stats, so we must
142 			 * block bottom-halves here.
143 			 */
144 			spin_lock_bh(&stats->lock);
145 			if (!*used || time_after(stats->used, *used))
146 				*used = stats->used;
147 			*tcp_flags |= stats->tcp_flags;
148 			ovs_stats->n_packets += stats->packet_count;
149 			ovs_stats->n_bytes += stats->byte_count;
150 			spin_unlock_bh(&stats->lock);
151 		}
152 	}
153 }
154 
155 /* Called with ovs_mutex. */
156 void ovs_flow_stats_clear(struct sw_flow *flow)
157 {
158 	unsigned int cpu;
159 
160 	for_each_cpu(cpu, flow->cpu_used_mask) {
161 		struct sw_flow_stats *stats = ovsl_dereference(flow->stats[cpu]);
162 
163 		if (stats) {
164 			spin_lock_bh(&stats->lock);
165 			stats->used = 0;
166 			stats->packet_count = 0;
167 			stats->byte_count = 0;
168 			stats->tcp_flags = 0;
169 			spin_unlock_bh(&stats->lock);
170 		}
171 	}
172 }
173 
174 static int check_header(struct sk_buff *skb, int len)
175 {
176 	if (unlikely(skb->len < len))
177 		return -EINVAL;
178 	if (unlikely(!pskb_may_pull(skb, len)))
179 		return -ENOMEM;
180 	return 0;
181 }
182 
183 static bool arphdr_ok(struct sk_buff *skb)
184 {
185 	return pskb_may_pull(skb, skb_network_offset(skb) +
186 				  sizeof(struct arp_eth_header));
187 }
188 
189 static int check_iphdr(struct sk_buff *skb)
190 {
191 	unsigned int nh_ofs = skb_network_offset(skb);
192 	unsigned int ip_len;
193 	int err;
194 
195 	err = check_header(skb, nh_ofs + sizeof(struct iphdr));
196 	if (unlikely(err))
197 		return err;
198 
199 	ip_len = ip_hdrlen(skb);
200 	if (unlikely(ip_len < sizeof(struct iphdr) ||
201 		     skb->len < nh_ofs + ip_len))
202 		return -EINVAL;
203 
204 	skb_set_transport_header(skb, nh_ofs + ip_len);
205 	return 0;
206 }
207 
208 static bool tcphdr_ok(struct sk_buff *skb)
209 {
210 	int th_ofs = skb_transport_offset(skb);
211 	int tcp_len;
212 
213 	if (unlikely(!pskb_may_pull(skb, th_ofs + sizeof(struct tcphdr))))
214 		return false;
215 
216 	tcp_len = tcp_hdrlen(skb);
217 	if (unlikely(tcp_len < sizeof(struct tcphdr) ||
218 		     skb->len < th_ofs + tcp_len))
219 		return false;
220 
221 	return true;
222 }
223 
224 static bool udphdr_ok(struct sk_buff *skb)
225 {
226 	return pskb_may_pull(skb, skb_transport_offset(skb) +
227 				  sizeof(struct udphdr));
228 }
229 
230 static bool sctphdr_ok(struct sk_buff *skb)
231 {
232 	return pskb_may_pull(skb, skb_transport_offset(skb) +
233 				  sizeof(struct sctphdr));
234 }
235 
236 static bool icmphdr_ok(struct sk_buff *skb)
237 {
238 	return pskb_may_pull(skb, skb_transport_offset(skb) +
239 				  sizeof(struct icmphdr));
240 }
241 
242 /**
243  * get_ipv6_ext_hdrs() - Parses packet and sets IPv6 extension header flags.
244  *
245  * @skb: buffer where extension header data starts in packet
246  * @nh: ipv6 header
247  * @ext_hdrs: flags are stored here
248  *
249  * OFPIEH12_UNREP is set if more than one of a given IPv6 extension header
250  * is unexpectedly encountered. (Two destination options headers may be
251  * expected and would not cause this bit to be set.)
252  *
253  * OFPIEH12_UNSEQ is set if IPv6 extension headers were not in the order
254  * preferred (but not required) by RFC 2460:
255  *
256  * When more than one extension header is used in the same packet, it is
257  * recommended that those headers appear in the following order:
258  *      IPv6 header
259  *      Hop-by-Hop Options header
260  *      Destination Options header
261  *      Routing header
262  *      Fragment header
263  *      Authentication header
264  *      Encapsulating Security Payload header
265  *      Destination Options header
266  *      upper-layer header
267  */
268 static void get_ipv6_ext_hdrs(struct sk_buff *skb, struct ipv6hdr *nh,
269 			      u16 *ext_hdrs)
270 {
271 	u8 next_type = nh->nexthdr;
272 	unsigned int start = skb_network_offset(skb) + sizeof(struct ipv6hdr);
273 	int dest_options_header_count = 0;
274 
275 	*ext_hdrs = 0;
276 
277 	while (ipv6_ext_hdr(next_type)) {
278 		struct ipv6_opt_hdr _hdr, *hp;
279 
280 		switch (next_type) {
281 		case IPPROTO_NONE:
282 			*ext_hdrs |= OFPIEH12_NONEXT;
283 			/* stop parsing */
284 			return;
285 
286 		case IPPROTO_ESP:
287 			if (*ext_hdrs & OFPIEH12_ESP)
288 				*ext_hdrs |= OFPIEH12_UNREP;
289 			if ((*ext_hdrs & ~(OFPIEH12_HOP | OFPIEH12_DEST |
290 					   OFPIEH12_ROUTER | OFPIEH12_FRAG |
291 					   OFPIEH12_AUTH | OFPIEH12_UNREP)) ||
292 			    dest_options_header_count >= 2) {
293 				*ext_hdrs |= OFPIEH12_UNSEQ;
294 			}
295 			*ext_hdrs |= OFPIEH12_ESP;
296 			break;
297 
298 		case IPPROTO_AH:
299 			if (*ext_hdrs & OFPIEH12_AUTH)
300 				*ext_hdrs |= OFPIEH12_UNREP;
301 			if ((*ext_hdrs &
302 			     ~(OFPIEH12_HOP | OFPIEH12_DEST | OFPIEH12_ROUTER |
303 			       OFPIEH12_FRAG | OFPIEH12_UNREP)) ||
304 			    dest_options_header_count >= 2) {
305 				*ext_hdrs |= OFPIEH12_UNSEQ;
306 			}
307 			*ext_hdrs |= OFPIEH12_AUTH;
308 			break;
309 
310 		case IPPROTO_DSTOPTS:
311 			if (dest_options_header_count == 0) {
312 				if (*ext_hdrs &
313 				    ~(OFPIEH12_HOP | OFPIEH12_UNREP))
314 					*ext_hdrs |= OFPIEH12_UNSEQ;
315 				*ext_hdrs |= OFPIEH12_DEST;
316 			} else if (dest_options_header_count == 1) {
317 				if (*ext_hdrs &
318 				    ~(OFPIEH12_HOP | OFPIEH12_DEST |
319 				      OFPIEH12_ROUTER | OFPIEH12_FRAG |
320 				      OFPIEH12_AUTH | OFPIEH12_ESP |
321 				      OFPIEH12_UNREP)) {
322 					*ext_hdrs |= OFPIEH12_UNSEQ;
323 				}
324 			} else {
325 				*ext_hdrs |= OFPIEH12_UNREP;
326 			}
327 			dest_options_header_count++;
328 			break;
329 
330 		case IPPROTO_FRAGMENT:
331 			if (*ext_hdrs & OFPIEH12_FRAG)
332 				*ext_hdrs |= OFPIEH12_UNREP;
333 			if ((*ext_hdrs & ~(OFPIEH12_HOP |
334 					   OFPIEH12_DEST |
335 					   OFPIEH12_ROUTER |
336 					   OFPIEH12_UNREP)) ||
337 			    dest_options_header_count >= 2) {
338 				*ext_hdrs |= OFPIEH12_UNSEQ;
339 			}
340 			*ext_hdrs |= OFPIEH12_FRAG;
341 			break;
342 
343 		case IPPROTO_ROUTING:
344 			if (*ext_hdrs & OFPIEH12_ROUTER)
345 				*ext_hdrs |= OFPIEH12_UNREP;
346 			if ((*ext_hdrs & ~(OFPIEH12_HOP |
347 					   OFPIEH12_DEST |
348 					   OFPIEH12_UNREP)) ||
349 			    dest_options_header_count >= 2) {
350 				*ext_hdrs |= OFPIEH12_UNSEQ;
351 			}
352 			*ext_hdrs |= OFPIEH12_ROUTER;
353 			break;
354 
355 		case IPPROTO_HOPOPTS:
356 			if (*ext_hdrs & OFPIEH12_HOP)
357 				*ext_hdrs |= OFPIEH12_UNREP;
358 			/* OFPIEH12_HOP is set to 1 if a hop-by-hop IPv6
359 			 * extension header is present as the first
360 			 * extension header in the packet.
361 			 */
362 			if (*ext_hdrs == 0)
363 				*ext_hdrs |= OFPIEH12_HOP;
364 			else
365 				*ext_hdrs |= OFPIEH12_UNSEQ;
366 			break;
367 
368 		default:
369 			return;
370 		}
371 
372 		if (next_type == IPPROTO_FRAGMENT) {
373 			struct frag_hdr _fh, *fh;
374 
375 			fh = skb_header_pointer(skb, start, sizeof(_fh), &_fh);
376 			if (!fh)
377 				break;
378 			/* Only the first fragment has the headers that follow. */
379 			if (fh->frag_off & htons(IP6_OFFSET))
380 				break;
381 			start += sizeof(_fh);
382 			next_type = fh->nexthdr;
383 			continue;
384 		}
385 
386 		hp = skb_header_pointer(skb, start, sizeof(_hdr), &_hdr);
387 		if (!hp)
388 			break;
389 		if (next_type == IPPROTO_AH)
390 			start += ipv6_authlen(hp);
391 		else
392 			start += ipv6_optlen(hp);
393 		next_type = hp->nexthdr;
394 	}
395 }
396 
397 static int parse_ipv6hdr(struct sk_buff *skb, struct sw_flow_key *key)
398 {
399 	unsigned short frag_off;
400 	unsigned int payload_ofs = 0;
401 	unsigned int nh_ofs = skb_network_offset(skb);
402 	unsigned int nh_len;
403 	struct ipv6hdr *nh;
404 	int err, nexthdr, flags = 0;
405 
406 	err = check_header(skb, nh_ofs + sizeof(*nh));
407 	if (unlikely(err))
408 		return err;
409 
410 	nh = ipv6_hdr(skb);
411 
412 	get_ipv6_ext_hdrs(skb, nh, &key->ipv6.exthdrs);
413 
414 	key->ip.proto = NEXTHDR_NONE;
415 	key->ip.tos = ipv6_get_dsfield(nh);
416 	key->ip.ttl = nh->hop_limit;
417 	key->ipv6.label = *(__be32 *)nh & htonl(IPV6_FLOWINFO_FLOWLABEL);
418 	key->ipv6.addr.src = nh->saddr;
419 	key->ipv6.addr.dst = nh->daddr;
420 
421 	nexthdr = ipv6_find_hdr(skb, &payload_ofs, -1, &frag_off, &flags);
422 	if (flags & IP6_FH_F_FRAG) {
423 		if (frag_off) {
424 			key->ip.frag = OVS_FRAG_TYPE_LATER;
425 			key->ip.proto = NEXTHDR_FRAGMENT;
426 			return 0;
427 		}
428 		key->ip.frag = OVS_FRAG_TYPE_FIRST;
429 	} else {
430 		key->ip.frag = OVS_FRAG_TYPE_NONE;
431 	}
432 
433 	/* Delayed handling of error in ipv6_find_hdr() as it
434 	 * always sets flags and frag_off to a valid value which may be
435 	 * used to set key->ip.frag above.
436 	 */
437 	if (unlikely(nexthdr < 0))
438 		return -EPROTO;
439 
440 	nh_len = payload_ofs - nh_ofs;
441 	skb_set_transport_header(skb, nh_ofs + nh_len);
442 	key->ip.proto = nexthdr;
443 	return nh_len;
444 }
445 
446 static bool icmp6hdr_ok(struct sk_buff *skb)
447 {
448 	return pskb_may_pull(skb, skb_transport_offset(skb) +
449 				  sizeof(struct icmp6hdr));
450 }
451 
452 /**
453  * parse_vlan_tag - Parse vlan tag from vlan header.
454  * @skb: skb containing frame to parse
455  * @key_vh: pointer to parsed vlan tag
456  * @untag_vlan: should the vlan header be removed from the frame
457  *
458  * Return: ERROR on memory error.
459  * %0 if it encounters a non-vlan or incomplete packet.
460  * %1 after successfully parsing vlan tag.
461  */
462 static int parse_vlan_tag(struct sk_buff *skb, struct vlan_head *key_vh,
463 			  bool untag_vlan)
464 {
465 	struct vlan_head *vh = (struct vlan_head *)skb->data;
466 
467 	if (likely(!eth_type_vlan(vh->tpid)))
468 		return 0;
469 
470 	if (unlikely(skb->len < sizeof(struct vlan_head) + sizeof(__be16)))
471 		return 0;
472 
473 	if (unlikely(!pskb_may_pull(skb, sizeof(struct vlan_head) +
474 				 sizeof(__be16))))
475 		return -ENOMEM;
476 
477 	vh = (struct vlan_head *)skb->data;
478 	key_vh->tci = vh->tci | htons(VLAN_CFI_MASK);
479 	key_vh->tpid = vh->tpid;
480 
481 	if (unlikely(untag_vlan)) {
482 		int offset = skb->data - skb_mac_header(skb);
483 		u16 tci;
484 		int err;
485 
486 		__skb_push(skb, offset);
487 		err = __skb_vlan_pop(skb, &tci);
488 		__skb_pull(skb, offset);
489 		if (err)
490 			return err;
491 		__vlan_hwaccel_put_tag(skb, key_vh->tpid, tci);
492 	} else {
493 		__skb_pull(skb, sizeof(struct vlan_head));
494 	}
495 	return 1;
496 }
497 
498 static void clear_vlan(struct sw_flow_key *key)
499 {
500 	key->eth.vlan.tci = 0;
501 	key->eth.vlan.tpid = 0;
502 	key->eth.cvlan.tci = 0;
503 	key->eth.cvlan.tpid = 0;
504 }
505 
506 static int parse_vlan(struct sk_buff *skb, struct sw_flow_key *key)
507 {
508 	int res;
509 
510 	if (skb_vlan_tag_present(skb)) {
511 		key->eth.vlan.tci = htons(skb->vlan_tci) | htons(VLAN_CFI_MASK);
512 		key->eth.vlan.tpid = skb->vlan_proto;
513 	} else {
514 		/* Parse outer vlan tag in the non-accelerated case. */
515 		res = parse_vlan_tag(skb, &key->eth.vlan, true);
516 		if (res <= 0)
517 			return res;
518 	}
519 
520 	/* Parse inner vlan tag. */
521 	res = parse_vlan_tag(skb, &key->eth.cvlan, false);
522 	if (res <= 0)
523 		return res;
524 
525 	return 0;
526 }
527 
528 static __be16 parse_ethertype(struct sk_buff *skb)
529 {
530 	struct llc_snap_hdr {
531 		u8  dsap;  /* Always 0xAA */
532 		u8  ssap;  /* Always 0xAA */
533 		u8  ctrl;
534 		u8  oui[3];
535 		__be16 ethertype;
536 	};
537 	struct llc_snap_hdr *llc;
538 	__be16 proto;
539 
540 	proto = *(__be16 *) skb->data;
541 	__skb_pull(skb, sizeof(__be16));
542 
543 	if (eth_proto_is_802_3(proto))
544 		return proto;
545 
546 	if (skb->len < sizeof(struct llc_snap_hdr))
547 		return htons(ETH_P_802_2);
548 
549 	if (unlikely(!pskb_may_pull(skb, sizeof(struct llc_snap_hdr))))
550 		return htons(0);
551 
552 	llc = (struct llc_snap_hdr *) skb->data;
553 	if (llc->dsap != LLC_SAP_SNAP ||
554 	    llc->ssap != LLC_SAP_SNAP ||
555 	    (llc->oui[0] | llc->oui[1] | llc->oui[2]) != 0)
556 		return htons(ETH_P_802_2);
557 
558 	__skb_pull(skb, sizeof(struct llc_snap_hdr));
559 
560 	if (eth_proto_is_802_3(llc->ethertype))
561 		return llc->ethertype;
562 
563 	return htons(ETH_P_802_2);
564 }
565 
566 static int parse_icmpv6(struct sk_buff *skb, struct sw_flow_key *key,
567 			int nh_len)
568 {
569 	struct icmp6hdr *icmp = icmp6_hdr(skb);
570 
571 	/* The ICMPv6 type and code fields use the 16-bit transport port
572 	 * fields, so we need to store them in 16-bit network byte order.
573 	 */
574 	key->tp.src = htons(icmp->icmp6_type);
575 	key->tp.dst = htons(icmp->icmp6_code);
576 
577 	if (icmp->icmp6_code == 0 &&
578 	    (icmp->icmp6_type == NDISC_NEIGHBOUR_SOLICITATION ||
579 	     icmp->icmp6_type == NDISC_NEIGHBOUR_ADVERTISEMENT)) {
580 		int icmp_len = skb->len - skb_transport_offset(skb);
581 		struct nd_msg *nd;
582 		int offset;
583 
584 		memset(&key->ipv6.nd, 0, sizeof(key->ipv6.nd));
585 
586 		/* In order to process neighbor discovery options, we need the
587 		 * entire packet.
588 		 */
589 		if (unlikely(icmp_len < sizeof(*nd)))
590 			return 0;
591 
592 		if (unlikely(skb_linearize(skb)))
593 			return -ENOMEM;
594 
595 		nd = (struct nd_msg *)skb_transport_header(skb);
596 		key->ipv6.nd.target = nd->target;
597 
598 		icmp_len -= sizeof(*nd);
599 		offset = 0;
600 		while (icmp_len >= 8) {
601 			struct nd_opt_hdr *nd_opt =
602 				 (struct nd_opt_hdr *)(nd->opt + offset);
603 			int opt_len = nd_opt->nd_opt_len * 8;
604 
605 			if (unlikely(!opt_len || opt_len > icmp_len))
606 				return 0;
607 
608 			/* Store the link layer address if the appropriate
609 			 * option is provided.  It is considered an error if
610 			 * the same link layer option is specified twice.
611 			 */
612 			if (nd_opt->nd_opt_type == ND_OPT_SOURCE_LL_ADDR
613 			    && opt_len == 8) {
614 				if (unlikely(!is_zero_ether_addr(key->ipv6.nd.sll)))
615 					goto invalid;
616 				ether_addr_copy(key->ipv6.nd.sll,
617 						&nd->opt[offset+sizeof(*nd_opt)]);
618 			} else if (nd_opt->nd_opt_type == ND_OPT_TARGET_LL_ADDR
619 				   && opt_len == 8) {
620 				if (unlikely(!is_zero_ether_addr(key->ipv6.nd.tll)))
621 					goto invalid;
622 				ether_addr_copy(key->ipv6.nd.tll,
623 						&nd->opt[offset+sizeof(*nd_opt)]);
624 			}
625 
626 			icmp_len -= opt_len;
627 			offset += opt_len;
628 		}
629 	}
630 
631 	return 0;
632 
633 invalid:
634 	memset(&key->ipv6.nd.target, 0, sizeof(key->ipv6.nd.target));
635 	memset(key->ipv6.nd.sll, 0, sizeof(key->ipv6.nd.sll));
636 	memset(key->ipv6.nd.tll, 0, sizeof(key->ipv6.nd.tll));
637 
638 	return 0;
639 }
640 
641 static int parse_nsh(struct sk_buff *skb, struct sw_flow_key *key)
642 {
643 	struct nshhdr *nh;
644 	unsigned int nh_ofs = skb_network_offset(skb);
645 	u8 version, length;
646 	int err;
647 
648 	err = check_header(skb, nh_ofs + NSH_BASE_HDR_LEN);
649 	if (unlikely(err))
650 		return err;
651 
652 	nh = nsh_hdr(skb);
653 	version = nsh_get_ver(nh);
654 	length = nsh_hdr_len(nh);
655 
656 	if (version != 0)
657 		return -EINVAL;
658 
659 	err = check_header(skb, nh_ofs + length);
660 	if (unlikely(err))
661 		return err;
662 
663 	nh = nsh_hdr(skb);
664 	key->nsh.base.flags = nsh_get_flags(nh);
665 	key->nsh.base.ttl = nsh_get_ttl(nh);
666 	key->nsh.base.mdtype = nh->mdtype;
667 	key->nsh.base.np = nh->np;
668 	key->nsh.base.path_hdr = nh->path_hdr;
669 	switch (key->nsh.base.mdtype) {
670 	case NSH_M_TYPE1:
671 		if (length != NSH_M_TYPE1_LEN)
672 			return -EINVAL;
673 		memcpy(key->nsh.context, nh->md1.context,
674 		       sizeof(nh->md1));
675 		break;
676 	case NSH_M_TYPE2:
677 		memset(key->nsh.context, 0,
678 		       sizeof(nh->md1));
679 		break;
680 	default:
681 		return -EINVAL;
682 	}
683 
684 	return 0;
685 }
686 
687 /**
688  * key_extract_l3l4 - extracts L3/L4 header information.
689  * @skb: sk_buff that contains the frame, with skb->data pointing to the
690  *       L3 header
691  * @key: output flow key
692  *
693  * Return: %0 if successful, otherwise a negative errno value.
694  */
695 static int key_extract_l3l4(struct sk_buff *skb, struct sw_flow_key *key)
696 {
697 	int error;
698 
699 	/* Network layer. */
700 	if (key->eth.type == htons(ETH_P_IP)) {
701 		struct iphdr *nh;
702 		__be16 offset;
703 
704 		error = check_iphdr(skb);
705 		if (unlikely(error)) {
706 			memset(&key->ip, 0, sizeof(key->ip));
707 			memset(&key->ipv4, 0, sizeof(key->ipv4));
708 			if (error == -EINVAL) {
709 				skb->transport_header = skb->network_header;
710 				error = 0;
711 			}
712 			return error;
713 		}
714 
715 		nh = ip_hdr(skb);
716 		key->ipv4.addr.src = nh->saddr;
717 		key->ipv4.addr.dst = nh->daddr;
718 
719 		key->ip.proto = nh->protocol;
720 		key->ip.tos = nh->tos;
721 		key->ip.ttl = nh->ttl;
722 
723 		offset = nh->frag_off & htons(IP_OFFSET);
724 		if (offset) {
725 			key->ip.frag = OVS_FRAG_TYPE_LATER;
726 			memset(&key->tp, 0, sizeof(key->tp));
727 			return 0;
728 		}
729 		if (nh->frag_off & htons(IP_MF) ||
730 			skb_shinfo(skb)->gso_type & SKB_GSO_UDP)
731 			key->ip.frag = OVS_FRAG_TYPE_FIRST;
732 		else
733 			key->ip.frag = OVS_FRAG_TYPE_NONE;
734 
735 		/* Transport layer. */
736 		if (key->ip.proto == IPPROTO_TCP) {
737 			if (tcphdr_ok(skb)) {
738 				struct tcphdr *tcp = tcp_hdr(skb);
739 				key->tp.src = tcp->source;
740 				key->tp.dst = tcp->dest;
741 				key->tp.flags = TCP_FLAGS_BE16(tcp);
742 			} else {
743 				memset(&key->tp, 0, sizeof(key->tp));
744 			}
745 
746 		} else if (key->ip.proto == IPPROTO_UDP) {
747 			if (udphdr_ok(skb)) {
748 				struct udphdr *udp = udp_hdr(skb);
749 				key->tp.src = udp->source;
750 				key->tp.dst = udp->dest;
751 			} else {
752 				memset(&key->tp, 0, sizeof(key->tp));
753 			}
754 		} else if (key->ip.proto == IPPROTO_SCTP) {
755 			if (sctphdr_ok(skb)) {
756 				struct sctphdr *sctp = sctp_hdr(skb);
757 				key->tp.src = sctp->source;
758 				key->tp.dst = sctp->dest;
759 			} else {
760 				memset(&key->tp, 0, sizeof(key->tp));
761 			}
762 		} else if (key->ip.proto == IPPROTO_ICMP) {
763 			if (icmphdr_ok(skb)) {
764 				struct icmphdr *icmp = icmp_hdr(skb);
765 				/* The ICMP type and code fields use the 16-bit
766 				 * transport port fields, so we need to store
767 				 * them in 16-bit network byte order. */
768 				key->tp.src = htons(icmp->type);
769 				key->tp.dst = htons(icmp->code);
770 			} else {
771 				memset(&key->tp, 0, sizeof(key->tp));
772 			}
773 		}
774 
775 	} else if (key->eth.type == htons(ETH_P_ARP) ||
776 		   key->eth.type == htons(ETH_P_RARP)) {
777 		struct arp_eth_header *arp;
778 		bool arp_available = arphdr_ok(skb);
779 
780 		arp = (struct arp_eth_header *)skb_network_header(skb);
781 
782 		if (arp_available &&
783 		    arp->ar_hrd == htons(ARPHRD_ETHER) &&
784 		    arp->ar_pro == htons(ETH_P_IP) &&
785 		    arp->ar_hln == ETH_ALEN &&
786 		    arp->ar_pln == 4) {
787 
788 			/* We only match on the lower 8 bits of the opcode. */
789 			if (ntohs(arp->ar_op) <= 0xff)
790 				key->ip.proto = ntohs(arp->ar_op);
791 			else
792 				key->ip.proto = 0;
793 
794 			memcpy(&key->ipv4.addr.src, arp->ar_sip, sizeof(key->ipv4.addr.src));
795 			memcpy(&key->ipv4.addr.dst, arp->ar_tip, sizeof(key->ipv4.addr.dst));
796 			ether_addr_copy(key->ipv4.arp.sha, arp->ar_sha);
797 			ether_addr_copy(key->ipv4.arp.tha, arp->ar_tha);
798 		} else {
799 			memset(&key->ip, 0, sizeof(key->ip));
800 			memset(&key->ipv4, 0, sizeof(key->ipv4));
801 		}
802 	} else if (eth_p_mpls(key->eth.type)) {
803 		size_t label_count = 1;
804 
805 		memset(&key->mpls, 0, sizeof(key->mpls));
806 		skb_set_inner_network_header(skb, skb->mac_len);
807 		while (1) {
808 			__be32 lse;
809 
810 			error = check_header(skb, skb->mac_len +
811 					     label_count * MPLS_HLEN);
812 			if (unlikely(error))
813 				return 0;
814 
815 			memcpy(&lse, skb_inner_network_header(skb), MPLS_HLEN);
816 
817 			if (label_count <= MPLS_LABEL_DEPTH)
818 				memcpy(&key->mpls.lse[label_count - 1], &lse,
819 				       MPLS_HLEN);
820 
821 			skb_set_inner_network_header(skb, skb->mac_len +
822 						     label_count * MPLS_HLEN);
823 			if (lse & htonl(MPLS_LS_S_MASK))
824 				break;
825 
826 			label_count++;
827 		}
828 		if (label_count > MPLS_LABEL_DEPTH)
829 			label_count = MPLS_LABEL_DEPTH;
830 
831 		key->mpls.num_labels_mask = GENMASK(label_count - 1, 0);
832 	} else if (key->eth.type == htons(ETH_P_IPV6)) {
833 		int nh_len;             /* IPv6 Header + Extensions */
834 
835 		nh_len = parse_ipv6hdr(skb, key);
836 		if (unlikely(nh_len < 0)) {
837 			switch (nh_len) {
838 			case -EINVAL:
839 				memset(&key->ip, 0, sizeof(key->ip));
840 				memset(&key->ipv6.addr, 0, sizeof(key->ipv6.addr));
841 				fallthrough;
842 			case -EPROTO:
843 				skb->transport_header = skb->network_header;
844 				error = 0;
845 				break;
846 			default:
847 				error = nh_len;
848 			}
849 			return error;
850 		}
851 
852 		if (key->ip.frag == OVS_FRAG_TYPE_LATER) {
853 			memset(&key->tp, 0, sizeof(key->tp));
854 			return 0;
855 		}
856 		if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP)
857 			key->ip.frag = OVS_FRAG_TYPE_FIRST;
858 
859 		/* Transport layer. */
860 		if (key->ip.proto == NEXTHDR_TCP) {
861 			if (tcphdr_ok(skb)) {
862 				struct tcphdr *tcp = tcp_hdr(skb);
863 				key->tp.src = tcp->source;
864 				key->tp.dst = tcp->dest;
865 				key->tp.flags = TCP_FLAGS_BE16(tcp);
866 			} else {
867 				memset(&key->tp, 0, sizeof(key->tp));
868 			}
869 		} else if (key->ip.proto == NEXTHDR_UDP) {
870 			if (udphdr_ok(skb)) {
871 				struct udphdr *udp = udp_hdr(skb);
872 				key->tp.src = udp->source;
873 				key->tp.dst = udp->dest;
874 			} else {
875 				memset(&key->tp, 0, sizeof(key->tp));
876 			}
877 		} else if (key->ip.proto == NEXTHDR_SCTP) {
878 			if (sctphdr_ok(skb)) {
879 				struct sctphdr *sctp = sctp_hdr(skb);
880 				key->tp.src = sctp->source;
881 				key->tp.dst = sctp->dest;
882 			} else {
883 				memset(&key->tp, 0, sizeof(key->tp));
884 			}
885 		} else if (key->ip.proto == NEXTHDR_ICMP) {
886 			if (icmp6hdr_ok(skb)) {
887 				error = parse_icmpv6(skb, key, nh_len);
888 				if (error)
889 					return error;
890 			} else {
891 				memset(&key->tp, 0, sizeof(key->tp));
892 			}
893 		}
894 	} else if (key->eth.type == htons(ETH_P_NSH)) {
895 		error = parse_nsh(skb, key);
896 		if (error)
897 			return error;
898 	}
899 	return 0;
900 }
901 
902 /**
903  * key_extract - extracts a flow key from an Ethernet frame.
904  * @skb: sk_buff that contains the frame, with skb->data pointing to the
905  * Ethernet header
906  * @key: output flow key
907  *
908  * Initializes @skb header fields as follows:
909  *
910  *    - skb->mac_header: the L2 header.
911  *
912  *    - skb->network_header: just past the L2 header, or just past the
913  *      VLAN header, to the first byte of the L2 payload.
914  *
915  *    - skb->transport_header: If key->eth.type is ETH_P_IP or ETH_P_IPV6
916  *      on output, then just past the IP header, if one is present and
917  *      of a correct length, otherwise the same as skb->network_header.
918  *      For other key->eth.type values it is left untouched.
919  *
920  *    - skb->protocol: the type of the data starting at skb->network_header.
921  *      Equals to key->eth.type.
922  *
923  * Return: %0 if successful, otherwise a negative errno value.
924  */
925 static int key_extract(struct sk_buff *skb, struct sw_flow_key *key)
926 {
927 	/* Flags are always used as part of stats */
928 	key->tp.flags = 0;
929 
930 	skb_reset_mac_header(skb);
931 
932 	/* Link layer. */
933 	clear_vlan(key);
934 	if (ovs_key_mac_proto(key) == MAC_PROTO_NONE) {
935 		if (unlikely(eth_type_vlan(skb->protocol)))
936 			return -EINVAL;
937 
938 		skb_reset_network_header(skb);
939 		key->eth.type = skb->protocol;
940 	} else {
941 		struct ethhdr *eth;
942 		int err;
943 
944 		err = check_header(skb, ETH_HLEN);
945 		if (unlikely(err))
946 			return err;
947 
948 		eth = eth_hdr(skb);
949 		ether_addr_copy(key->eth.src, eth->h_source);
950 		ether_addr_copy(key->eth.dst, eth->h_dest);
951 
952 		__skb_pull(skb, 2 * ETH_ALEN);
953 		/* We are going to push all headers that we pull, so no need to
954 		 * update skb->csum here.
955 		 */
956 
957 		if (unlikely(parse_vlan(skb, key)))
958 			return -ENOMEM;
959 
960 		key->eth.type = parse_ethertype(skb);
961 		if (unlikely(key->eth.type == htons(0)))
962 			return -ENOMEM;
963 
964 		/* Multiple tagged packets need to retain TPID to satisfy
965 		 * skb_vlan_pop(), which will later shift the ethertype into
966 		 * skb->protocol.
967 		 */
968 		if (key->eth.cvlan.tci & htons(VLAN_CFI_MASK))
969 			skb->protocol = key->eth.cvlan.tpid;
970 		else
971 			skb->protocol = key->eth.type;
972 
973 		skb_reset_network_header(skb);
974 		__skb_push(skb, skb->data - skb_mac_header(skb));
975 	}
976 
977 	skb_reset_mac_len(skb);
978 
979 	/* Fill out L3/L4 key info, if any */
980 	return key_extract_l3l4(skb, key);
981 }
982 
983 /* In the case of conntrack fragment handling it expects L3 headers,
984  * add a helper.
985  */
986 int ovs_flow_key_update_l3l4(struct sk_buff *skb, struct sw_flow_key *key)
987 {
988 	return key_extract_l3l4(skb, key);
989 }
990 
991 int ovs_flow_key_update(struct sk_buff *skb, struct sw_flow_key *key)
992 {
993 	int res;
994 
995 	res = key_extract(skb, key);
996 	if (!res)
997 		key->mac_proto &= ~SW_FLOW_KEY_INVALID;
998 
999 	return res;
1000 }
1001 
1002 static int key_extract_mac_proto(struct sk_buff *skb)
1003 {
1004 	switch (skb->dev->type) {
1005 	case ARPHRD_ETHER:
1006 		return MAC_PROTO_ETHERNET;
1007 	case ARPHRD_NONE:
1008 		if (skb->protocol == htons(ETH_P_TEB))
1009 			return MAC_PROTO_ETHERNET;
1010 		return MAC_PROTO_NONE;
1011 	}
1012 	WARN_ON_ONCE(1);
1013 	return -EINVAL;
1014 }
1015 
1016 int ovs_flow_key_extract(const struct ip_tunnel_info *tun_info,
1017 			 struct sk_buff *skb, struct sw_flow_key *key)
1018 {
1019 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
1020 	struct tc_skb_ext *tc_ext;
1021 #endif
1022 	bool post_ct = false, post_ct_snat = false, post_ct_dnat = false;
1023 	int res, err;
1024 	u16 zone = 0;
1025 
1026 	/* Extract metadata from packet. */
1027 	if (tun_info) {
1028 		key->tun_proto = ip_tunnel_info_af(tun_info);
1029 		memcpy(&key->tun_key, &tun_info->key, sizeof(key->tun_key));
1030 
1031 		if (tun_info->options_len) {
1032 			BUILD_BUG_ON((1 << (sizeof(tun_info->options_len) *
1033 						   8)) - 1
1034 					> sizeof(key->tun_opts));
1035 
1036 			ip_tunnel_info_opts_get(TUN_METADATA_OPTS(key, tun_info->options_len),
1037 						tun_info);
1038 			key->tun_opts_len = tun_info->options_len;
1039 		} else {
1040 			key->tun_opts_len = 0;
1041 		}
1042 	} else  {
1043 		key->tun_proto = 0;
1044 		key->tun_opts_len = 0;
1045 		memset(&key->tun_key, 0, sizeof(key->tun_key));
1046 	}
1047 
1048 	key->phy.priority = skb->priority;
1049 	key->phy.in_port = OVS_CB(skb)->input_vport->port_no;
1050 	key->phy.skb_mark = skb->mark;
1051 	key->ovs_flow_hash = 0;
1052 	res = key_extract_mac_proto(skb);
1053 	if (res < 0)
1054 		return res;
1055 	key->mac_proto = res;
1056 
1057 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
1058 	if (tc_skb_ext_tc_enabled()) {
1059 		tc_ext = skb_ext_find(skb, TC_SKB_EXT);
1060 		key->recirc_id = tc_ext && !tc_ext->act_miss ?
1061 				 tc_ext->chain : 0;
1062 		OVS_CB(skb)->mru = tc_ext ? tc_ext->mru : 0;
1063 		post_ct = tc_ext ? tc_ext->post_ct : false;
1064 		post_ct_snat = post_ct ? tc_ext->post_ct_snat : false;
1065 		post_ct_dnat = post_ct ? tc_ext->post_ct_dnat : false;
1066 		zone = post_ct ? tc_ext->zone : 0;
1067 	} else {
1068 		key->recirc_id = 0;
1069 	}
1070 #else
1071 	key->recirc_id = 0;
1072 #endif
1073 
1074 	err = key_extract(skb, key);
1075 	if (!err) {
1076 		ovs_ct_fill_key(skb, key, post_ct);   /* Must be after key_extract(). */
1077 		if (post_ct) {
1078 			if (!skb_get_nfct(skb)) {
1079 				key->ct_zone = zone;
1080 			} else {
1081 				if (!post_ct_dnat)
1082 					key->ct_state &= ~OVS_CS_F_DST_NAT;
1083 				if (!post_ct_snat)
1084 					key->ct_state &= ~OVS_CS_F_SRC_NAT;
1085 			}
1086 		}
1087 	}
1088 	return err;
1089 }
1090 
1091 int ovs_flow_key_extract_userspace(struct net *net, const struct nlattr *attr,
1092 				   struct sk_buff *skb,
1093 				   struct sw_flow_key *key, bool log)
1094 {
1095 	const struct nlattr *a[OVS_KEY_ATTR_MAX + 1];
1096 	u64 attrs = 0;
1097 	int err;
1098 
1099 	err = parse_flow_nlattrs(attr, a, &attrs, log);
1100 	if (err)
1101 		return -EINVAL;
1102 
1103 	/* Extract metadata from netlink attributes. */
1104 	err = ovs_nla_get_flow_metadata(net, a, attrs, key, log);
1105 	if (err)
1106 		return err;
1107 
1108 	/* key_extract assumes that skb->protocol is set-up for
1109 	 * layer 3 packets which is the case for other callers,
1110 	 * in particular packets received from the network stack.
1111 	 * Here the correct value can be set from the metadata
1112 	 * extracted above.
1113 	 * For L2 packet key eth type would be zero. skb protocol
1114 	 * would be set to correct value later during key-extact.
1115 	 */
1116 
1117 	skb->protocol = key->eth.type;
1118 	err = key_extract(skb, key);
1119 	if (err)
1120 		return err;
1121 
1122 	/* Check that we have conntrack original direction tuple metadata only
1123 	 * for packets for which it makes sense.  Otherwise the key may be
1124 	 * corrupted due to overlapping key fields.
1125 	 */
1126 	if (attrs & (1 << OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4) &&
1127 	    key->eth.type != htons(ETH_P_IP))
1128 		return -EINVAL;
1129 	if (attrs & (1 << OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV6) &&
1130 	    (key->eth.type != htons(ETH_P_IPV6) ||
1131 	     sw_flow_key_is_nd(key)))
1132 		return -EINVAL;
1133 
1134 	return 0;
1135 }
1136