xref: /freebsd/sys/netinet/tcp_lro.c (revision 2008043f386721d58158e37e0d7e50df8095942d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2007, Myricom Inc.
5  * Copyright (c) 2008, Intel Corporation.
6  * Copyright (c) 2012 The FreeBSD Foundation
7  * Copyright (c) 2016-2021 Mellanox Technologies.
8  * All rights reserved.
9  *
10  * Portions of this software were developed by Bjoern Zeeb
11  * under sponsorship from the FreeBSD Foundation.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/sockbuf.h>
47 #include <sys/sysctl.h>
48 
49 #include <net/if.h>
50 #include <net/if_var.h>
51 #include <net/ethernet.h>
52 #include <net/bpf.h>
53 #include <net/vnet.h>
54 #include <net/if_dl.h>
55 #include <net/if_media.h>
56 #include <net/if_private.h>
57 #include <net/if_types.h>
58 #include <net/infiniband.h>
59 #include <net/if_lagg.h>
60 
61 #include <netinet/in_systm.h>
62 #include <netinet/in.h>
63 #include <netinet/ip6.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_var.h>
66 #include <netinet/in_pcb.h>
67 #include <netinet6/in6_pcb.h>
68 #include <netinet/tcp.h>
69 #include <netinet/tcp_seq.h>
70 #include <netinet/tcp_lro.h>
71 #include <netinet/tcp_var.h>
72 #include <netinet/tcpip.h>
73 #include <netinet/tcp_hpts.h>
74 #include <netinet/tcp_log_buf.h>
75 #include <netinet/tcp_fsm.h>
76 #include <netinet/udp.h>
77 #include <netinet6/ip6_var.h>
78 
79 #include <machine/in_cksum.h>
80 
81 static MALLOC_DEFINE(M_LRO, "LRO", "LRO control structures");
82 
83 #define	TCP_LRO_TS_OPTION \
84     ntohl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
85 	  (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)
86 
87 static void	tcp_lro_rx_done(struct lro_ctrl *lc);
88 static int	tcp_lro_rx_common(struct lro_ctrl *lc, struct mbuf *m,
89 		    uint32_t csum, bool use_hash);
90 
91 #ifdef TCPHPTS
92 static bool	do_bpf_strip_and_compress(struct tcpcb *, struct lro_ctrl *,
93 		struct lro_entry *, struct mbuf **, struct mbuf **, struct mbuf **,
94  		bool *, bool, bool, struct ifnet *, bool);
95 
96 #endif
97 
98 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, lro,  CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
99     "TCP LRO");
100 
101 static long tcplro_stacks_wanting_mbufq;
102 counter_u64_t tcp_inp_lro_direct_queue;
103 counter_u64_t tcp_inp_lro_wokeup_queue;
104 counter_u64_t tcp_inp_lro_compressed;
105 counter_u64_t tcp_inp_lro_locks_taken;
106 counter_u64_t tcp_extra_mbuf;
107 counter_u64_t tcp_would_have_but;
108 counter_u64_t tcp_comp_total;
109 counter_u64_t tcp_uncomp_total;
110 counter_u64_t tcp_bad_csums;
111 
112 static unsigned	tcp_lro_entries = TCP_LRO_ENTRIES;
113 SYSCTL_UINT(_net_inet_tcp_lro, OID_AUTO, entries,
114     CTLFLAG_RDTUN | CTLFLAG_MPSAFE, &tcp_lro_entries, 0,
115     "default number of LRO entries");
116 
117 static uint32_t tcp_lro_cpu_set_thresh = TCP_LRO_CPU_DECLARATION_THRESH;
118 SYSCTL_UINT(_net_inet_tcp_lro, OID_AUTO, lro_cpu_threshold,
119     CTLFLAG_RDTUN | CTLFLAG_MPSAFE, &tcp_lro_cpu_set_thresh, 0,
120     "Number of interrupts in a row on the same CPU that will make us declare an 'affinity' cpu?");
121 
122 static uint32_t tcp_less_accurate_lro_ts = 0;
123 SYSCTL_UINT(_net_inet_tcp_lro, OID_AUTO, lro_less_accurate,
124     CTLFLAG_MPSAFE, &tcp_less_accurate_lro_ts, 0,
125     "Do we trade off efficency by doing less timestamp operations for time accuracy?");
126 
127 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, fullqueue, CTLFLAG_RD,
128     &tcp_inp_lro_direct_queue, "Number of lro's fully queued to transport");
129 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, wokeup, CTLFLAG_RD,
130     &tcp_inp_lro_wokeup_queue, "Number of lro's where we woke up transport via hpts");
131 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, compressed, CTLFLAG_RD,
132     &tcp_inp_lro_compressed, "Number of lro's compressed and sent to transport");
133 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, lockcnt, CTLFLAG_RD,
134     &tcp_inp_lro_locks_taken, "Number of lro's inp_wlocks taken");
135 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, extra_mbuf, CTLFLAG_RD,
136     &tcp_extra_mbuf, "Number of times we had an extra compressed ack dropped into the tp");
137 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, would_have_but, CTLFLAG_RD,
138     &tcp_would_have_but, "Number of times we would have had an extra compressed, but mget failed");
139 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, with_m_ackcmp, CTLFLAG_RD,
140     &tcp_comp_total, "Number of mbufs queued with M_ACKCMP flags set");
141 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, without_m_ackcmp, CTLFLAG_RD,
142     &tcp_uncomp_total, "Number of mbufs queued without M_ACKCMP");
143 SYSCTL_COUNTER_U64(_net_inet_tcp_lro, OID_AUTO, lro_badcsum, CTLFLAG_RD,
144     &tcp_bad_csums, "Number of packets that the common code saw with bad csums");
145 
146 void
147 tcp_lro_reg_mbufq(void)
148 {
149 	atomic_fetchadd_long(&tcplro_stacks_wanting_mbufq, 1);
150 }
151 
152 void
153 tcp_lro_dereg_mbufq(void)
154 {
155 	atomic_fetchadd_long(&tcplro_stacks_wanting_mbufq, -1);
156 }
157 
158 static __inline void
159 tcp_lro_active_insert(struct lro_ctrl *lc, struct lro_head *bucket,
160     struct lro_entry *le)
161 {
162 
163 	LIST_INSERT_HEAD(&lc->lro_active, le, next);
164 	LIST_INSERT_HEAD(bucket, le, hash_next);
165 }
166 
167 static __inline void
168 tcp_lro_active_remove(struct lro_entry *le)
169 {
170 
171 	LIST_REMOVE(le, next);		/* active list */
172 	LIST_REMOVE(le, hash_next);	/* hash bucket */
173 }
174 
175 int
176 tcp_lro_init(struct lro_ctrl *lc)
177 {
178 	return (tcp_lro_init_args(lc, NULL, tcp_lro_entries, 0));
179 }
180 
181 int
182 tcp_lro_init_args(struct lro_ctrl *lc, struct ifnet *ifp,
183     unsigned lro_entries, unsigned lro_mbufs)
184 {
185 	struct lro_entry *le;
186 	size_t size;
187 	unsigned i, elements;
188 
189 	lc->lro_bad_csum = 0;
190 	lc->lro_queued = 0;
191 	lc->lro_flushed = 0;
192 	lc->lro_mbuf_count = 0;
193 	lc->lro_mbuf_max = lro_mbufs;
194 	lc->lro_cnt = lro_entries;
195 	lc->lro_ackcnt_lim = TCP_LRO_ACKCNT_MAX;
196 	lc->lro_length_lim = TCP_LRO_LENGTH_MAX;
197 	lc->ifp = ifp;
198 	LIST_INIT(&lc->lro_free);
199 	LIST_INIT(&lc->lro_active);
200 
201 	/* create hash table to accelerate entry lookup */
202 	if (lro_entries > lro_mbufs)
203 		elements = lro_entries;
204 	else
205 		elements = lro_mbufs;
206 	lc->lro_hash = phashinit_flags(elements, M_LRO, &lc->lro_hashsz,
207 	    HASH_NOWAIT);
208 	if (lc->lro_hash == NULL) {
209 		memset(lc, 0, sizeof(*lc));
210 		return (ENOMEM);
211 	}
212 
213 	/* compute size to allocate */
214 	size = (lro_mbufs * sizeof(struct lro_mbuf_sort)) +
215 	    (lro_entries * sizeof(*le));
216 	lc->lro_mbuf_data = (struct lro_mbuf_sort *)
217 	    malloc(size, M_LRO, M_NOWAIT | M_ZERO);
218 
219 	/* check for out of memory */
220 	if (lc->lro_mbuf_data == NULL) {
221 		free(lc->lro_hash, M_LRO);
222 		memset(lc, 0, sizeof(*lc));
223 		return (ENOMEM);
224 	}
225 	/* compute offset for LRO entries */
226 	le = (struct lro_entry *)
227 	    (lc->lro_mbuf_data + lro_mbufs);
228 
229 	/* setup linked list */
230 	for (i = 0; i != lro_entries; i++)
231 		LIST_INSERT_HEAD(&lc->lro_free, le + i, next);
232 
233 	return (0);
234 }
235 
236 struct vxlan_header {
237 	uint32_t	vxlh_flags;
238 	uint32_t	vxlh_vni;
239 };
240 
241 static inline void *
242 tcp_lro_low_level_parser(void *ptr, struct lro_parser *parser, bool update_data, bool is_vxlan, int mlen)
243 {
244 	const struct ether_vlan_header *eh;
245 	void *old;
246 	uint16_t eth_type;
247 
248 	if (update_data)
249 		memset(parser, 0, sizeof(*parser));
250 
251 	old = ptr;
252 
253 	if (is_vxlan) {
254 		const struct vxlan_header *vxh;
255 		vxh = ptr;
256 		ptr = (uint8_t *)ptr + sizeof(*vxh);
257 		if (update_data) {
258 			parser->data.vxlan_vni =
259 			    vxh->vxlh_vni & htonl(0xffffff00);
260 		}
261 	}
262 
263 	eh = ptr;
264 	if (__predict_false(eh->evl_encap_proto == htons(ETHERTYPE_VLAN))) {
265 		eth_type = eh->evl_proto;
266 		if (update_data) {
267 			/* strip priority and keep VLAN ID only */
268 			parser->data.vlan_id = eh->evl_tag & htons(EVL_VLID_MASK);
269 		}
270 		/* advance to next header */
271 		ptr = (uint8_t *)ptr + ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
272 		mlen -= (ETHER_HDR_LEN  + ETHER_VLAN_ENCAP_LEN);
273 	} else {
274 		eth_type = eh->evl_encap_proto;
275 		/* advance to next header */
276 		mlen -= ETHER_HDR_LEN;
277 		ptr = (uint8_t *)ptr + ETHER_HDR_LEN;
278 	}
279 	if (__predict_false(mlen <= 0))
280 		return (NULL);
281 	switch (eth_type) {
282 #ifdef INET
283 	case htons(ETHERTYPE_IP):
284 		parser->ip4 = ptr;
285 		if (__predict_false(mlen < sizeof(struct ip)))
286 			return (NULL);
287 		/* Ensure there are no IPv4 options. */
288 		if ((parser->ip4->ip_hl << 2) != sizeof (*parser->ip4))
289 			break;
290 		/* .. and the packet is not fragmented. */
291 		if (parser->ip4->ip_off & htons(IP_MF|IP_OFFMASK))
292 			break;
293 		/* .. and the packet has valid src/dst addrs */
294 		if (__predict_false(parser->ip4->ip_src.s_addr == INADDR_ANY ||
295 			parser->ip4->ip_dst.s_addr == INADDR_ANY))
296 			break;
297 		ptr = (uint8_t *)ptr + (parser->ip4->ip_hl << 2);
298 		mlen -= sizeof(struct ip);
299 		if (update_data) {
300 			parser->data.s_addr.v4 = parser->ip4->ip_src;
301 			parser->data.d_addr.v4 = parser->ip4->ip_dst;
302 		}
303 		switch (parser->ip4->ip_p) {
304 		case IPPROTO_UDP:
305 			if (__predict_false(mlen < sizeof(struct udphdr)))
306 				return (NULL);
307 			parser->udp = ptr;
308 			if (update_data) {
309 				parser->data.lro_type = LRO_TYPE_IPV4_UDP;
310 				parser->data.s_port = parser->udp->uh_sport;
311 				parser->data.d_port = parser->udp->uh_dport;
312 			} else {
313 				MPASS(parser->data.lro_type == LRO_TYPE_IPV4_UDP);
314 			}
315 			ptr = ((uint8_t *)ptr + sizeof(*parser->udp));
316 			parser->total_hdr_len = (uint8_t *)ptr - (uint8_t *)old;
317 			return (ptr);
318 		case IPPROTO_TCP:
319 			parser->tcp = ptr;
320 			if (__predict_false(mlen < sizeof(struct tcphdr)))
321 				return (NULL);
322 			if (update_data) {
323 				parser->data.lro_type = LRO_TYPE_IPV4_TCP;
324 				parser->data.s_port = parser->tcp->th_sport;
325 				parser->data.d_port = parser->tcp->th_dport;
326 			} else {
327 				MPASS(parser->data.lro_type == LRO_TYPE_IPV4_TCP);
328 			}
329 			if (__predict_false(mlen < (parser->tcp->th_off << 2)))
330 				return (NULL);
331 			ptr = (uint8_t *)ptr + (parser->tcp->th_off << 2);
332 			parser->total_hdr_len = (uint8_t *)ptr - (uint8_t *)old;
333 			return (ptr);
334 		default:
335 			break;
336 		}
337 		break;
338 #endif
339 #ifdef INET6
340 	case htons(ETHERTYPE_IPV6):
341 		parser->ip6 = ptr;
342 		if (__predict_false(mlen < sizeof(struct ip6_hdr)))
343 			return (NULL);
344 		/* Ensure the packet has valid src/dst addrs */
345 		if (__predict_false(IN6_IS_ADDR_UNSPECIFIED(&parser->ip6->ip6_src) ||
346 			IN6_IS_ADDR_UNSPECIFIED(&parser->ip6->ip6_dst)))
347 			return (NULL);
348 		ptr = (uint8_t *)ptr + sizeof(*parser->ip6);
349 		if (update_data) {
350 			parser->data.s_addr.v6 = parser->ip6->ip6_src;
351 			parser->data.d_addr.v6 = parser->ip6->ip6_dst;
352 		}
353 		mlen -= sizeof(struct ip6_hdr);
354 		switch (parser->ip6->ip6_nxt) {
355 		case IPPROTO_UDP:
356 			if (__predict_false(mlen < sizeof(struct udphdr)))
357 				return (NULL);
358 			parser->udp = ptr;
359 			if (update_data) {
360 				parser->data.lro_type = LRO_TYPE_IPV6_UDP;
361 				parser->data.s_port = parser->udp->uh_sport;
362 				parser->data.d_port = parser->udp->uh_dport;
363 			} else {
364 				MPASS(parser->data.lro_type == LRO_TYPE_IPV6_UDP);
365 			}
366 			ptr = (uint8_t *)ptr + sizeof(*parser->udp);
367 			parser->total_hdr_len = (uint8_t *)ptr - (uint8_t *)old;
368 			return (ptr);
369 		case IPPROTO_TCP:
370 			if (__predict_false(mlen < sizeof(struct tcphdr)))
371 				return (NULL);
372 			parser->tcp = ptr;
373 			if (update_data) {
374 				parser->data.lro_type = LRO_TYPE_IPV6_TCP;
375 				parser->data.s_port = parser->tcp->th_sport;
376 				parser->data.d_port = parser->tcp->th_dport;
377 			} else {
378 				MPASS(parser->data.lro_type == LRO_TYPE_IPV6_TCP);
379 			}
380 			if (__predict_false(mlen < (parser->tcp->th_off << 2)))
381 				return (NULL);
382 			ptr = (uint8_t *)ptr + (parser->tcp->th_off << 2);
383 			parser->total_hdr_len = (uint8_t *)ptr - (uint8_t *)old;
384 			return (ptr);
385 		default:
386 			break;
387 		}
388 		break;
389 #endif
390 	default:
391 		break;
392 	}
393 	/* Invalid packet - cannot parse */
394 	return (NULL);
395 }
396 
397 static const int vxlan_csum = CSUM_INNER_L3_CALC | CSUM_INNER_L3_VALID |
398     CSUM_INNER_L4_CALC | CSUM_INNER_L4_VALID;
399 
400 static inline struct lro_parser *
401 tcp_lro_parser(struct mbuf *m, struct lro_parser *po, struct lro_parser *pi, bool update_data)
402 {
403 	void *data_ptr;
404 
405 	/* Try to parse outer headers first. */
406 	data_ptr = tcp_lro_low_level_parser(m->m_data, po, update_data, false, m->m_len);
407 	if (data_ptr == NULL || po->total_hdr_len > m->m_len)
408 		return (NULL);
409 
410 	if (update_data) {
411 		/* Store VLAN ID, if any. */
412 		if (__predict_false(m->m_flags & M_VLANTAG)) {
413 			po->data.vlan_id =
414 			    htons(m->m_pkthdr.ether_vtag) & htons(EVL_VLID_MASK);
415 		}
416 		/* Store decrypted flag, if any. */
417 		if (__predict_false((m->m_pkthdr.csum_flags &
418 		    CSUM_TLS_MASK) == CSUM_TLS_DECRYPTED))
419 			po->data.lro_flags |= LRO_FLAG_DECRYPTED;
420 	}
421 
422 	switch (po->data.lro_type) {
423 	case LRO_TYPE_IPV4_UDP:
424 	case LRO_TYPE_IPV6_UDP:
425 		/* Check for VXLAN headers. */
426 		if ((m->m_pkthdr.csum_flags & vxlan_csum) != vxlan_csum)
427 			break;
428 
429 		/* Try to parse inner headers. */
430 		data_ptr = tcp_lro_low_level_parser(data_ptr, pi, update_data, true,
431 						    (m->m_len - ((caddr_t)data_ptr - m->m_data)));
432 		if (data_ptr == NULL || (pi->total_hdr_len + po->total_hdr_len) > m->m_len)
433 			break;
434 
435 		/* Verify supported header types. */
436 		switch (pi->data.lro_type) {
437 		case LRO_TYPE_IPV4_TCP:
438 		case LRO_TYPE_IPV6_TCP:
439 			return (pi);
440 		default:
441 			break;
442 		}
443 		break;
444 	case LRO_TYPE_IPV4_TCP:
445 	case LRO_TYPE_IPV6_TCP:
446 		if (update_data)
447 			memset(pi, 0, sizeof(*pi));
448 		return (po);
449 	default:
450 		break;
451 	}
452 	return (NULL);
453 }
454 
455 static inline int
456 tcp_lro_trim_mbuf_chain(struct mbuf *m, const struct lro_parser *po)
457 {
458 	int len;
459 
460 	switch (po->data.lro_type) {
461 #ifdef INET
462 	case LRO_TYPE_IPV4_TCP:
463 		len = ((uint8_t *)po->ip4 - (uint8_t *)m->m_data) +
464 		    ntohs(po->ip4->ip_len);
465 		break;
466 #endif
467 #ifdef INET6
468 	case LRO_TYPE_IPV6_TCP:
469 		len = ((uint8_t *)po->ip6 - (uint8_t *)m->m_data) +
470 		    ntohs(po->ip6->ip6_plen) + sizeof(*po->ip6);
471 		break;
472 #endif
473 	default:
474 		return (TCP_LRO_CANNOT);
475 	}
476 
477 	/*
478 	 * If the frame is padded beyond the end of the IP packet,
479 	 * then trim the extra bytes off:
480 	 */
481 	if (__predict_true(m->m_pkthdr.len == len)) {
482 		return (0);
483 	} else if (m->m_pkthdr.len > len) {
484 		m_adj(m, len - m->m_pkthdr.len);
485 		return (0);
486 	}
487 	return (TCP_LRO_CANNOT);
488 }
489 
490 static struct tcphdr *
491 tcp_lro_get_th(struct mbuf *m)
492 {
493 	return ((struct tcphdr *)((uint8_t *)m->m_data + m->m_pkthdr.lro_tcp_h_off));
494 }
495 
496 static void
497 lro_free_mbuf_chain(struct mbuf *m)
498 {
499 	struct mbuf *save;
500 
501 	while (m) {
502 		save = m->m_nextpkt;
503 		m->m_nextpkt = NULL;
504 		m_freem(m);
505 		m = save;
506 	}
507 }
508 
509 void
510 tcp_lro_free(struct lro_ctrl *lc)
511 {
512 	struct lro_entry *le;
513 	unsigned x;
514 
515 	/* reset LRO free list */
516 	LIST_INIT(&lc->lro_free);
517 
518 	/* free active mbufs, if any */
519 	while ((le = LIST_FIRST(&lc->lro_active)) != NULL) {
520 		tcp_lro_active_remove(le);
521 		lro_free_mbuf_chain(le->m_head);
522 	}
523 
524 	/* free hash table */
525 	free(lc->lro_hash, M_LRO);
526 	lc->lro_hash = NULL;
527 	lc->lro_hashsz = 0;
528 
529 	/* free mbuf array, if any */
530 	for (x = 0; x != lc->lro_mbuf_count; x++)
531 		m_freem(lc->lro_mbuf_data[x].mb);
532 	lc->lro_mbuf_count = 0;
533 
534 	/* free allocated memory, if any */
535 	free(lc->lro_mbuf_data, M_LRO);
536 	lc->lro_mbuf_data = NULL;
537 }
538 
539 static uint16_t
540 tcp_lro_rx_csum_tcphdr(const struct tcphdr *th)
541 {
542 	const uint16_t *ptr;
543 	uint32_t csum;
544 	uint16_t len;
545 
546 	csum = -th->th_sum;	/* exclude checksum field */
547 	len = th->th_off;
548 	ptr = (const uint16_t *)th;
549 	while (len--) {
550 		csum += *ptr;
551 		ptr++;
552 		csum += *ptr;
553 		ptr++;
554 	}
555 	while (csum > 0xffff)
556 		csum = (csum >> 16) + (csum & 0xffff);
557 
558 	return (csum);
559 }
560 
561 static uint16_t
562 tcp_lro_rx_csum_data(const struct lro_parser *pa, uint16_t tcp_csum)
563 {
564 	uint32_t c;
565 	uint16_t cs;
566 
567 	c = tcp_csum;
568 
569 	switch (pa->data.lro_type) {
570 #ifdef INET6
571 	case LRO_TYPE_IPV6_TCP:
572 		/* Compute full pseudo IPv6 header checksum. */
573 		cs = in6_cksum_pseudo(pa->ip6, ntohs(pa->ip6->ip6_plen), pa->ip6->ip6_nxt, 0);
574 		break;
575 #endif
576 #ifdef INET
577 	case LRO_TYPE_IPV4_TCP:
578 		/* Compute full pseudo IPv4 header checsum. */
579 		cs = in_addword(ntohs(pa->ip4->ip_len) - sizeof(*pa->ip4), IPPROTO_TCP);
580 		cs = in_pseudo(pa->ip4->ip_src.s_addr, pa->ip4->ip_dst.s_addr, htons(cs));
581 		break;
582 #endif
583 	default:
584 		cs = 0;		/* Keep compiler happy. */
585 		break;
586 	}
587 
588 	/* Complement checksum. */
589 	cs = ~cs;
590 	c += cs;
591 
592 	/* Remove TCP header checksum. */
593 	cs = ~tcp_lro_rx_csum_tcphdr(pa->tcp);
594 	c += cs;
595 
596 	/* Compute checksum remainder. */
597 	while (c > 0xffff)
598 		c = (c >> 16) + (c & 0xffff);
599 
600 	return (c);
601 }
602 
603 static void
604 tcp_lro_rx_done(struct lro_ctrl *lc)
605 {
606 	struct lro_entry *le;
607 
608 	while ((le = LIST_FIRST(&lc->lro_active)) != NULL) {
609 		tcp_lro_active_remove(le);
610 		tcp_lro_flush(lc, le);
611 	}
612 }
613 
614 static void
615 tcp_lro_flush_active(struct lro_ctrl *lc)
616 {
617 	struct lro_entry *le;
618 
619 	/*
620 	 * Walk through the list of le entries, and
621 	 * any one that does have packets flush. This
622 	 * is called because we have an inbound packet
623 	 * (e.g. SYN) that has to have all others flushed
624 	 * in front of it. Note we have to do the remove
625 	 * because tcp_lro_flush() assumes that the entry
626 	 * is being freed. This is ok it will just get
627 	 * reallocated again like it was new.
628 	 */
629 	LIST_FOREACH(le, &lc->lro_active, next) {
630 		if (le->m_head != NULL) {
631 			tcp_lro_active_remove(le);
632 			tcp_lro_flush(lc, le);
633 		}
634 	}
635 }
636 
637 void
638 tcp_lro_flush_inactive(struct lro_ctrl *lc, const struct timeval *timeout)
639 {
640 	struct lro_entry *le, *le_tmp;
641 	uint64_t now, tov;
642 	struct bintime bt;
643 
644 	NET_EPOCH_ASSERT();
645 	if (LIST_EMPTY(&lc->lro_active))
646 		return;
647 
648 	/* get timeout time and current time in ns */
649 	binuptime(&bt);
650 	now = bintime2ns(&bt);
651 	tov = ((timeout->tv_sec * 1000000000) + (timeout->tv_usec * 1000));
652 	LIST_FOREACH_SAFE(le, &lc->lro_active, next, le_tmp) {
653 		if (now >= (bintime2ns(&le->alloc_time) + tov)) {
654 			tcp_lro_active_remove(le);
655 			tcp_lro_flush(lc, le);
656 		}
657 	}
658 }
659 
660 #ifdef INET
661 static int
662 tcp_lro_rx_ipv4(struct lro_ctrl *lc, struct mbuf *m, struct ip *ip4)
663 {
664 	uint16_t csum;
665 
666 	/* Legacy IP has a header checksum that needs to be correct. */
667 	if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
668 		if (__predict_false((m->m_pkthdr.csum_flags & CSUM_IP_VALID) == 0)) {
669 			lc->lro_bad_csum++;
670 			return (TCP_LRO_CANNOT);
671 		}
672 	} else {
673 		csum = in_cksum_hdr(ip4);
674 		if (__predict_false(csum != 0)) {
675 			lc->lro_bad_csum++;
676 			return (TCP_LRO_CANNOT);
677 		}
678 	}
679 	return (0);
680 }
681 #endif
682 
683 #ifdef TCPHPTS
684 static void
685 tcp_lro_log(struct tcpcb *tp, const struct lro_ctrl *lc,
686     const struct lro_entry *le, const struct mbuf *m,
687     int frm, int32_t tcp_data_len, uint32_t th_seq,
688     uint32_t th_ack, uint16_t th_win)
689 {
690 	if (tcp_bblogging_on(tp)) {
691 		union tcp_log_stackspecific log;
692 		struct timeval tv, btv;
693 		uint32_t cts;
694 
695 		cts = tcp_get_usecs(&tv);
696 		memset(&log, 0, sizeof(union tcp_log_stackspecific));
697 		log.u_bbr.flex8 = frm;
698 		log.u_bbr.flex1 = tcp_data_len;
699 		if (m)
700 			log.u_bbr.flex2 = m->m_pkthdr.len;
701 		else
702 			log.u_bbr.flex2 = 0;
703 		if (le->m_head) {
704 			log.u_bbr.flex3 = le->m_head->m_pkthdr.lro_nsegs;
705 			log.u_bbr.flex4 = le->m_head->m_pkthdr.lro_tcp_d_len;
706 			log.u_bbr.flex5 = le->m_head->m_pkthdr.len;
707 			log.u_bbr.delRate = le->m_head->m_flags;
708 			log.u_bbr.rttProp = le->m_head->m_pkthdr.rcv_tstmp;
709 		}
710 		log.u_bbr.inflight = th_seq;
711 		log.u_bbr.delivered = th_ack;
712 		log.u_bbr.timeStamp = cts;
713 		log.u_bbr.epoch = le->next_seq;
714 		log.u_bbr.lt_epoch = le->ack_seq;
715 		log.u_bbr.pacing_gain = th_win;
716 		log.u_bbr.cwnd_gain = le->window;
717 		log.u_bbr.lost = curcpu;
718 		log.u_bbr.cur_del_rate = (uintptr_t)m;
719 		log.u_bbr.bw_inuse = (uintptr_t)le->m_head;
720 		bintime2timeval(&lc->lro_last_queue_time, &btv);
721 		log.u_bbr.flex6 = tcp_tv_to_usectick(&btv);
722 		log.u_bbr.flex7 = le->compressed;
723 		log.u_bbr.pacing_gain = le->uncompressed;
724 		if (in_epoch(net_epoch_preempt))
725 			log.u_bbr.inhpts = 1;
726 		else
727 			log.u_bbr.inhpts = 0;
728 		TCP_LOG_EVENTP(tp, NULL, &tptosocket(tp)->so_rcv,
729 		    &tptosocket(tp)->so_snd,
730 		    TCP_LOG_LRO, 0, 0, &log, false, &tv);
731 	}
732 }
733 #endif
734 
735 static inline void
736 tcp_lro_assign_and_checksum_16(uint16_t *ptr, uint16_t value, uint16_t *psum)
737 {
738 	uint32_t csum;
739 
740 	csum = 0xffff - *ptr + value;
741 	while (csum > 0xffff)
742 		csum = (csum >> 16) + (csum & 0xffff);
743 	*ptr = value;
744 	*psum = csum;
745 }
746 
747 static uint16_t
748 tcp_lro_update_checksum(const struct lro_parser *pa, const struct lro_entry *le,
749     uint16_t payload_len, uint16_t delta_sum)
750 {
751 	uint32_t csum;
752 	uint16_t tlen;
753 	uint16_t temp[5] = {};
754 
755 	switch (pa->data.lro_type) {
756 	case LRO_TYPE_IPV4_TCP:
757 		/* Compute new IPv4 length. */
758 		tlen = (pa->ip4->ip_hl << 2) + (pa->tcp->th_off << 2) + payload_len;
759 		tcp_lro_assign_and_checksum_16(&pa->ip4->ip_len, htons(tlen), &temp[0]);
760 
761 		/* Subtract delta from current IPv4 checksum. */
762 		csum = pa->ip4->ip_sum + 0xffff - temp[0];
763 		while (csum > 0xffff)
764 			csum = (csum >> 16) + (csum & 0xffff);
765 		tcp_lro_assign_and_checksum_16(&pa->ip4->ip_sum, csum, &temp[1]);
766 		goto update_tcp_header;
767 
768 	case LRO_TYPE_IPV6_TCP:
769 		/* Compute new IPv6 length. */
770 		tlen = (pa->tcp->th_off << 2) + payload_len;
771 		tcp_lro_assign_and_checksum_16(&pa->ip6->ip6_plen, htons(tlen), &temp[0]);
772 		goto update_tcp_header;
773 
774 	case LRO_TYPE_IPV4_UDP:
775 		/* Compute new IPv4 length. */
776 		tlen = (pa->ip4->ip_hl << 2) + sizeof(*pa->udp) + payload_len;
777 		tcp_lro_assign_and_checksum_16(&pa->ip4->ip_len, htons(tlen), &temp[0]);
778 
779 		/* Subtract delta from current IPv4 checksum. */
780 		csum = pa->ip4->ip_sum + 0xffff - temp[0];
781 		while (csum > 0xffff)
782 			csum = (csum >> 16) + (csum & 0xffff);
783 		tcp_lro_assign_and_checksum_16(&pa->ip4->ip_sum, csum, &temp[1]);
784 		goto update_udp_header;
785 
786 	case LRO_TYPE_IPV6_UDP:
787 		/* Compute new IPv6 length. */
788 		tlen = sizeof(*pa->udp) + payload_len;
789 		tcp_lro_assign_and_checksum_16(&pa->ip6->ip6_plen, htons(tlen), &temp[0]);
790 		goto update_udp_header;
791 
792 	default:
793 		return (0);
794 	}
795 
796 update_tcp_header:
797 	/* Compute current TCP header checksum. */
798 	temp[2] = tcp_lro_rx_csum_tcphdr(pa->tcp);
799 
800 	/* Incorporate the latest ACK into the TCP header. */
801 	pa->tcp->th_ack = le->ack_seq;
802 	pa->tcp->th_win = le->window;
803 
804 	/* Incorporate latest timestamp into the TCP header. */
805 	if (le->timestamp != 0) {
806 		uint32_t *ts_ptr;
807 
808 		ts_ptr = (uint32_t *)(pa->tcp + 1);
809 		ts_ptr[1] = htonl(le->tsval);
810 		ts_ptr[2] = le->tsecr;
811 	}
812 
813 	/* Compute new TCP header checksum. */
814 	temp[3] = tcp_lro_rx_csum_tcphdr(pa->tcp);
815 
816 	/* Compute new TCP checksum. */
817 	csum = pa->tcp->th_sum + 0xffff - delta_sum +
818 	    0xffff - temp[0] + 0xffff - temp[3] + temp[2];
819 	while (csum > 0xffff)
820 		csum = (csum >> 16) + (csum & 0xffff);
821 
822 	/* Assign new TCP checksum. */
823 	tcp_lro_assign_and_checksum_16(&pa->tcp->th_sum, csum, &temp[4]);
824 
825 	/* Compute all modififications affecting next checksum. */
826 	csum = temp[0] + temp[1] + 0xffff - temp[2] +
827 	    temp[3] + temp[4] + delta_sum;
828 	while (csum > 0xffff)
829 		csum = (csum >> 16) + (csum & 0xffff);
830 
831 	/* Return delta checksum to next stage, if any. */
832 	return (csum);
833 
834 update_udp_header:
835 	tlen = sizeof(*pa->udp) + payload_len;
836 	/* Assign new UDP length and compute checksum delta. */
837 	tcp_lro_assign_and_checksum_16(&pa->udp->uh_ulen, htons(tlen), &temp[2]);
838 
839 	/* Check if there is a UDP checksum. */
840 	if (__predict_false(pa->udp->uh_sum != 0)) {
841 		/* Compute new UDP checksum. */
842 		csum = pa->udp->uh_sum + 0xffff - delta_sum +
843 		    0xffff - temp[0] + 0xffff - temp[2];
844 		while (csum > 0xffff)
845 			csum = (csum >> 16) + (csum & 0xffff);
846 		/* Assign new UDP checksum. */
847 		tcp_lro_assign_and_checksum_16(&pa->udp->uh_sum, csum, &temp[3]);
848 	}
849 
850 	/* Compute all modififications affecting next checksum. */
851 	csum = temp[0] + temp[1] + temp[2] + temp[3] + delta_sum;
852 	while (csum > 0xffff)
853 		csum = (csum >> 16) + (csum & 0xffff);
854 
855 	/* Return delta checksum to next stage, if any. */
856 	return (csum);
857 }
858 
859 static void
860 tcp_flush_out_entry(struct lro_ctrl *lc, struct lro_entry *le)
861 {
862 	/* Check if we need to recompute any checksums. */
863 	if (le->needs_merge) {
864 		uint16_t csum;
865 
866 		switch (le->inner.data.lro_type) {
867 		case LRO_TYPE_IPV4_TCP:
868 			csum = tcp_lro_update_checksum(&le->inner, le,
869 			    le->m_head->m_pkthdr.lro_tcp_d_len,
870 			    le->m_head->m_pkthdr.lro_tcp_d_csum);
871 			csum = tcp_lro_update_checksum(&le->outer, NULL,
872 			    le->m_head->m_pkthdr.lro_tcp_d_len +
873 			    le->inner.total_hdr_len, csum);
874 			le->m_head->m_pkthdr.csum_flags = CSUM_DATA_VALID |
875 			    CSUM_PSEUDO_HDR | CSUM_IP_CHECKED | CSUM_IP_VALID;
876 			le->m_head->m_pkthdr.csum_data = 0xffff;
877 			if (__predict_false(le->outer.data.lro_flags & LRO_FLAG_DECRYPTED))
878 				le->m_head->m_pkthdr.csum_flags |= CSUM_TLS_DECRYPTED;
879 			break;
880 		case LRO_TYPE_IPV6_TCP:
881 			csum = tcp_lro_update_checksum(&le->inner, le,
882 			    le->m_head->m_pkthdr.lro_tcp_d_len,
883 			    le->m_head->m_pkthdr.lro_tcp_d_csum);
884 			csum = tcp_lro_update_checksum(&le->outer, NULL,
885 			    le->m_head->m_pkthdr.lro_tcp_d_len +
886 			    le->inner.total_hdr_len, csum);
887 			le->m_head->m_pkthdr.csum_flags = CSUM_DATA_VALID |
888 			    CSUM_PSEUDO_HDR;
889 			le->m_head->m_pkthdr.csum_data = 0xffff;
890 			if (__predict_false(le->outer.data.lro_flags & LRO_FLAG_DECRYPTED))
891 				le->m_head->m_pkthdr.csum_flags |= CSUM_TLS_DECRYPTED;
892 			break;
893 		case LRO_TYPE_NONE:
894 			switch (le->outer.data.lro_type) {
895 			case LRO_TYPE_IPV4_TCP:
896 				csum = tcp_lro_update_checksum(&le->outer, le,
897 				    le->m_head->m_pkthdr.lro_tcp_d_len,
898 				    le->m_head->m_pkthdr.lro_tcp_d_csum);
899 				le->m_head->m_pkthdr.csum_flags = CSUM_DATA_VALID |
900 				    CSUM_PSEUDO_HDR | CSUM_IP_CHECKED | CSUM_IP_VALID;
901 				le->m_head->m_pkthdr.csum_data = 0xffff;
902 				if (__predict_false(le->outer.data.lro_flags & LRO_FLAG_DECRYPTED))
903 					le->m_head->m_pkthdr.csum_flags |= CSUM_TLS_DECRYPTED;
904 				break;
905 			case LRO_TYPE_IPV6_TCP:
906 				csum = tcp_lro_update_checksum(&le->outer, le,
907 				    le->m_head->m_pkthdr.lro_tcp_d_len,
908 				    le->m_head->m_pkthdr.lro_tcp_d_csum);
909 				le->m_head->m_pkthdr.csum_flags = CSUM_DATA_VALID |
910 				    CSUM_PSEUDO_HDR;
911 				le->m_head->m_pkthdr.csum_data = 0xffff;
912 				if (__predict_false(le->outer.data.lro_flags & LRO_FLAG_DECRYPTED))
913 					le->m_head->m_pkthdr.csum_flags |= CSUM_TLS_DECRYPTED;
914 				break;
915 			default:
916 				break;
917 			}
918 			break;
919 		default:
920 			break;
921 		}
922 	}
923 
924 	/*
925 	 * Break any chain, this is not set to NULL on the singleton
926 	 * case m_nextpkt points to m_head. Other case set them
927 	 * m_nextpkt to NULL in push_and_replace.
928 	 */
929 	le->m_head->m_nextpkt = NULL;
930 	lc->lro_queued += le->m_head->m_pkthdr.lro_nsegs;
931 	(*lc->ifp->if_input)(lc->ifp, le->m_head);
932 }
933 
934 static void
935 tcp_set_entry_to_mbuf(struct lro_ctrl *lc, struct lro_entry *le,
936     struct mbuf *m, struct tcphdr *th)
937 {
938 	uint32_t *ts_ptr;
939 	uint16_t tcp_data_len;
940 	uint16_t tcp_opt_len;
941 
942 	ts_ptr = (uint32_t *)(th + 1);
943 	tcp_opt_len = (th->th_off << 2);
944 	tcp_opt_len -= sizeof(*th);
945 
946 	/* Check if there is a timestamp option. */
947 	if (tcp_opt_len == 0 ||
948 	    __predict_false(tcp_opt_len != TCPOLEN_TSTAMP_APPA ||
949 	    *ts_ptr != TCP_LRO_TS_OPTION)) {
950 		/* We failed to find the timestamp option. */
951 		le->timestamp = 0;
952 	} else {
953 		le->timestamp = 1;
954 		le->tsval = ntohl(*(ts_ptr + 1));
955 		le->tsecr = *(ts_ptr + 2);
956 	}
957 
958 	tcp_data_len = m->m_pkthdr.lro_tcp_d_len;
959 
960 	/* Pull out TCP sequence numbers and window size. */
961 	le->next_seq = ntohl(th->th_seq) + tcp_data_len;
962 	le->ack_seq = th->th_ack;
963 	le->window = th->th_win;
964 	le->flags = tcp_get_flags(th);
965 	le->needs_merge = 0;
966 
967 	/* Setup new data pointers. */
968 	le->m_head = m;
969 	le->m_tail = m_last(m);
970 }
971 
972 static void
973 tcp_push_and_replace(struct lro_ctrl *lc, struct lro_entry *le, struct mbuf *m)
974 {
975 	struct lro_parser *pa;
976 
977 	/*
978 	 * Push up the stack of the current entry
979 	 * and replace it with "m".
980 	 */
981 	struct mbuf *msave;
982 
983 	/* Grab off the next and save it */
984 	msave = le->m_head->m_nextpkt;
985 	le->m_head->m_nextpkt = NULL;
986 
987 	/* Now push out the old entry */
988 	tcp_flush_out_entry(lc, le);
989 
990 	/* Re-parse new header, should not fail. */
991 	pa = tcp_lro_parser(m, &le->outer, &le->inner, false);
992 	KASSERT(pa != NULL,
993 	    ("tcp_push_and_replace: LRO parser failed on m=%p\n", m));
994 
995 	/*
996 	 * Now to replace the data properly in the entry
997 	 * we have to reset the TCP header and
998 	 * other fields.
999 	 */
1000 	tcp_set_entry_to_mbuf(lc, le, m, pa->tcp);
1001 
1002 	/* Restore the next list */
1003 	m->m_nextpkt = msave;
1004 }
1005 
1006 static void
1007 tcp_lro_mbuf_append_pkthdr(struct lro_entry *le, const struct mbuf *p)
1008 {
1009 	struct mbuf *m;
1010 	uint32_t csum;
1011 
1012 	m = le->m_head;
1013 	if (m->m_pkthdr.lro_nsegs == 1) {
1014 		/* Compute relative checksum. */
1015 		csum = p->m_pkthdr.lro_tcp_d_csum;
1016 	} else {
1017 		/* Merge TCP data checksums. */
1018 		csum = (uint32_t)m->m_pkthdr.lro_tcp_d_csum +
1019 		    (uint32_t)p->m_pkthdr.lro_tcp_d_csum;
1020 		while (csum > 0xffff)
1021 			csum = (csum >> 16) + (csum & 0xffff);
1022 	}
1023 
1024 	/* Update various counters. */
1025 	m->m_pkthdr.len += p->m_pkthdr.lro_tcp_d_len;
1026 	m->m_pkthdr.lro_tcp_d_csum = csum;
1027 	m->m_pkthdr.lro_tcp_d_len += p->m_pkthdr.lro_tcp_d_len;
1028 	m->m_pkthdr.lro_nsegs += p->m_pkthdr.lro_nsegs;
1029 	le->needs_merge = 1;
1030 }
1031 
1032 static void
1033 tcp_lro_condense(struct lro_ctrl *lc, struct lro_entry *le)
1034 {
1035 	/*
1036 	 * Walk through the mbuf chain we
1037 	 * have on tap and compress/condense
1038 	 * as required.
1039 	 */
1040 	uint32_t *ts_ptr;
1041 	struct mbuf *m;
1042 	struct tcphdr *th;
1043 	uint32_t tcp_data_len_total;
1044 	uint32_t tcp_data_seg_total;
1045 	uint16_t tcp_data_len;
1046 	uint16_t tcp_opt_len;
1047 
1048 	/*
1049 	 * First we must check the lead (m_head)
1050 	 * we must make sure that it is *not*
1051 	 * something that should be sent up
1052 	 * right away (sack etc).
1053 	 */
1054 again:
1055 	m = le->m_head->m_nextpkt;
1056 	if (m == NULL) {
1057 		/* Just one left. */
1058 		return;
1059 	}
1060 
1061 	th = tcp_lro_get_th(m);
1062 	tcp_opt_len = (th->th_off << 2);
1063 	tcp_opt_len -= sizeof(*th);
1064 	ts_ptr = (uint32_t *)(th + 1);
1065 
1066 	if (tcp_opt_len != 0 && __predict_false(tcp_opt_len != TCPOLEN_TSTAMP_APPA ||
1067 	    *ts_ptr != TCP_LRO_TS_OPTION)) {
1068 		/*
1069 		 * Its not the timestamp. We can't
1070 		 * use this guy as the head.
1071 		 */
1072 		le->m_head->m_nextpkt = m->m_nextpkt;
1073 		tcp_push_and_replace(lc, le, m);
1074 		goto again;
1075 	}
1076 	if ((tcp_get_flags(th) & ~(TH_ACK | TH_PUSH)) != 0) {
1077 		/*
1078 		 * Make sure that previously seen segments/ACKs are delivered
1079 		 * before this segment, e.g. FIN.
1080 		 */
1081 		le->m_head->m_nextpkt = m->m_nextpkt;
1082 		tcp_push_and_replace(lc, le, m);
1083 		goto again;
1084 	}
1085 	while((m = le->m_head->m_nextpkt) != NULL) {
1086 		/*
1087 		 * condense m into le, first
1088 		 * pull m out of the list.
1089 		 */
1090 		le->m_head->m_nextpkt = m->m_nextpkt;
1091 		m->m_nextpkt = NULL;
1092 		/* Setup my data */
1093 		tcp_data_len = m->m_pkthdr.lro_tcp_d_len;
1094 		th = tcp_lro_get_th(m);
1095 		ts_ptr = (uint32_t *)(th + 1);
1096 		tcp_opt_len = (th->th_off << 2);
1097 		tcp_opt_len -= sizeof(*th);
1098 		tcp_data_len_total = le->m_head->m_pkthdr.lro_tcp_d_len + tcp_data_len;
1099 		tcp_data_seg_total = le->m_head->m_pkthdr.lro_nsegs + m->m_pkthdr.lro_nsegs;
1100 
1101 		if (tcp_data_seg_total >= lc->lro_ackcnt_lim ||
1102 		    tcp_data_len_total >= lc->lro_length_lim) {
1103 			/* Flush now if appending will result in overflow. */
1104 			tcp_push_and_replace(lc, le, m);
1105 			goto again;
1106 		}
1107 		if (tcp_opt_len != 0 &&
1108 		    __predict_false(tcp_opt_len != TCPOLEN_TSTAMP_APPA ||
1109 		    *ts_ptr != TCP_LRO_TS_OPTION)) {
1110 			/*
1111 			 * Maybe a sack in the new one? We need to
1112 			 * start all over after flushing the
1113 			 * current le. We will go up to the beginning
1114 			 * and flush it (calling the replace again possibly
1115 			 * or just returning).
1116 			 */
1117 			tcp_push_and_replace(lc, le, m);
1118 			goto again;
1119 		}
1120 		if ((tcp_get_flags(th) & ~(TH_ACK | TH_PUSH)) != 0) {
1121 			tcp_push_and_replace(lc, le, m);
1122 			goto again;
1123 		}
1124 		if (tcp_opt_len != 0) {
1125 			uint32_t tsval = ntohl(*(ts_ptr + 1));
1126 			/* Make sure timestamp values are increasing. */
1127 			if (TSTMP_GT(le->tsval, tsval))  {
1128 				tcp_push_and_replace(lc, le, m);
1129 				goto again;
1130 			}
1131 			le->tsval = tsval;
1132 			le->tsecr = *(ts_ptr + 2);
1133 		}
1134 		/* Try to append the new segment. */
1135 		if (__predict_false(ntohl(th->th_seq) != le->next_seq ||
1136 				    ((tcp_get_flags(th) & TH_ACK) !=
1137 				      (le->flags & TH_ACK)) ||
1138 				    (tcp_data_len == 0 &&
1139 				     le->ack_seq == th->th_ack &&
1140 				     le->window == th->th_win))) {
1141 			/* Out of order packet, non-ACK + ACK or dup ACK. */
1142 			tcp_push_and_replace(lc, le, m);
1143 			goto again;
1144 		}
1145 		if (tcp_data_len != 0 ||
1146 		    SEQ_GT(ntohl(th->th_ack), ntohl(le->ack_seq))) {
1147 			le->next_seq += tcp_data_len;
1148 			le->ack_seq = th->th_ack;
1149 			le->window = th->th_win;
1150 			le->needs_merge = 1;
1151 		} else if (th->th_ack == le->ack_seq) {
1152 			if (WIN_GT(th->th_win, le->window)) {
1153 				le->window = th->th_win;
1154 				le->needs_merge = 1;
1155 			}
1156 		}
1157 
1158 		if (tcp_data_len == 0) {
1159 			m_freem(m);
1160 			continue;
1161 		}
1162 
1163 		/* Merge TCP data checksum and length to head mbuf. */
1164 		tcp_lro_mbuf_append_pkthdr(le, m);
1165 
1166 		/*
1167 		 * Adjust the mbuf so that m_data points to the first byte of
1168 		 * the ULP payload.  Adjust the mbuf to avoid complications and
1169 		 * append new segment to existing mbuf chain.
1170 		 */
1171 		m_adj(m, m->m_pkthdr.len - tcp_data_len);
1172 		m_demote_pkthdr(m);
1173 		le->m_tail->m_next = m;
1174 		le->m_tail = m_last(m);
1175 	}
1176 }
1177 
1178 #ifdef TCPHPTS
1179 static void
1180 tcp_queue_pkts(struct tcpcb *tp, struct lro_entry *le)
1181 {
1182 
1183 	INP_WLOCK_ASSERT(tptoinpcb(tp));
1184 
1185 	STAILQ_HEAD(, mbuf) q = { le->m_head,
1186 	    &STAILQ_NEXT(le->m_last_mbuf, m_stailqpkt) };
1187 	STAILQ_CONCAT(&tp->t_inqueue, &q);
1188 	le->m_head = NULL;
1189 	le->m_last_mbuf = NULL;
1190 }
1191 
1192 static bool
1193 tcp_lro_check_wake_status(struct tcpcb *tp)
1194 {
1195 
1196 	if (tp->t_fb->tfb_early_wake_check != NULL)
1197 		return ((tp->t_fb->tfb_early_wake_check)(tp));
1198 	return (false);
1199 }
1200 
1201 static struct mbuf *
1202 tcp_lro_get_last_if_ackcmp(struct lro_ctrl *lc, struct lro_entry *le,
1203     struct tcpcb *tp, int32_t *new_m, bool can_append_old_cmp)
1204 {
1205 	struct mbuf *m;
1206 
1207 	/* Look at the last mbuf if any in queue */
1208  	if (can_append_old_cmp) {
1209 		m = STAILQ_LAST(&tp->t_inqueue, mbuf, m_stailqpkt);
1210 		if (m != NULL && (m->m_flags & M_ACKCMP) != 0) {
1211 			if (M_TRAILINGSPACE(m) >= sizeof(struct tcp_ackent)) {
1212 				tcp_lro_log(tp, lc, le, NULL, 23, 0, 0, 0, 0);
1213 				*new_m = 0;
1214 				counter_u64_add(tcp_extra_mbuf, 1);
1215 				return (m);
1216 			} else {
1217 				/* Mark we ran out of space */
1218 				tp->t_flags2 |= TF2_MBUF_L_ACKS;
1219 			}
1220 		}
1221 	}
1222 	/* Decide mbuf size. */
1223 	tcp_lro_log(tp, lc, le, NULL, 21, 0, 0, 0, 0);
1224 	if (tp->t_flags2 & TF2_MBUF_L_ACKS)
1225 		m = m_getcl(M_NOWAIT, MT_DATA, M_ACKCMP | M_PKTHDR);
1226 	else
1227 		m = m_gethdr(M_NOWAIT, MT_DATA);
1228 
1229 	if (__predict_false(m == NULL)) {
1230 		counter_u64_add(tcp_would_have_but, 1);
1231 		return (NULL);
1232 	}
1233 	counter_u64_add(tcp_comp_total, 1);
1234  	m->m_pkthdr.rcvif = lc->ifp;
1235 	m->m_flags |= M_ACKCMP;
1236 	*new_m = 1;
1237 	return (m);
1238 }
1239 
1240 static struct tcpcb *
1241 tcp_lro_lookup(struct ifnet *ifp, struct lro_parser *pa)
1242 {
1243 	struct inpcb *inp;
1244 
1245 	switch (pa->data.lro_type) {
1246 #ifdef INET6
1247 	case LRO_TYPE_IPV6_TCP:
1248 		inp = in6_pcblookup(&V_tcbinfo,
1249 		    &pa->data.s_addr.v6,
1250 		    pa->data.s_port,
1251 		    &pa->data.d_addr.v6,
1252 		    pa->data.d_port,
1253 		    INPLOOKUP_WLOCKPCB,
1254 		    ifp);
1255 		break;
1256 #endif
1257 #ifdef INET
1258 	case LRO_TYPE_IPV4_TCP:
1259 		inp = in_pcblookup(&V_tcbinfo,
1260 		    pa->data.s_addr.v4,
1261 		    pa->data.s_port,
1262 		    pa->data.d_addr.v4,
1263 		    pa->data.d_port,
1264 		    INPLOOKUP_WLOCKPCB,
1265 		    ifp);
1266 		break;
1267 #endif
1268 	default:
1269 		return (NULL);
1270 	}
1271 
1272 	return (intotcpcb(inp));
1273 }
1274 
1275 static inline bool
1276 tcp_lro_ack_valid(struct mbuf *m, struct tcphdr *th, uint32_t **ppts, bool *other_opts)
1277 {
1278 	/*
1279 	 * This function returns two bits of valuable information.
1280 	 * a) Is what is present capable of being ack-compressed,
1281 	 *    we can ack-compress if there is no options or just
1282 	 *    a timestamp option, and of course the th_flags must
1283 	 *    be correct as well.
1284 	 * b) Our other options present such as SACK. This is
1285 	 *    used to determine if we want to wakeup or not.
1286 	 */
1287 	bool ret = true;
1288 
1289 	switch (th->th_off << 2) {
1290 	case (sizeof(*th) + TCPOLEN_TSTAMP_APPA):
1291 		*ppts = (uint32_t *)(th + 1);
1292 		/* Check if we have only one timestamp option. */
1293 		if (**ppts == TCP_LRO_TS_OPTION)
1294 			*other_opts = false;
1295 		else {
1296 			*other_opts = true;
1297 			ret = false;
1298 		}
1299 		break;
1300 	case (sizeof(*th)):
1301 		/* No options. */
1302 		*ppts = NULL;
1303 		*other_opts = false;
1304 		break;
1305 	default:
1306 		*ppts = NULL;
1307 		*other_opts = true;
1308 		ret = false;
1309 		break;
1310 	}
1311 	/* For ACKCMP we only accept ACK, PUSH, ECE and CWR. */
1312 	if ((tcp_get_flags(th) & ~(TH_ACK | TH_PUSH | TH_ECE | TH_CWR)) != 0)
1313 		ret = false;
1314 	/* If it has data on it we cannot compress it */
1315 	if (m->m_pkthdr.lro_tcp_d_len)
1316 		ret = false;
1317 
1318 	/* ACK flag must be set. */
1319 	if (!(tcp_get_flags(th) & TH_ACK))
1320 		ret = false;
1321 	return (ret);
1322 }
1323 
1324 static int
1325 tcp_lro_flush_tcphpts(struct lro_ctrl *lc, struct lro_entry *le)
1326 {
1327 	struct tcpcb *tp;
1328 	struct mbuf **pp, *cmp, *mv_to;
1329 	struct ifnet *lagg_ifp;
1330  	bool bpf_req, lagg_bpf_req, should_wake, can_append_old_cmp;
1331 
1332 	/* Check if packet doesn't belongs to our network interface. */
1333 	if ((tcplro_stacks_wanting_mbufq == 0) ||
1334 	    (le->outer.data.vlan_id != 0) ||
1335 	    (le->inner.data.lro_type != LRO_TYPE_NONE))
1336 		return (TCP_LRO_CANNOT);
1337 
1338 #ifdef INET6
1339 	/*
1340 	 * Be proactive about unspecified IPv6 address in source. As
1341 	 * we use all-zero to indicate unbounded/unconnected pcb,
1342 	 * unspecified IPv6 address can be used to confuse us.
1343 	 *
1344 	 * Note that packets with unspecified IPv6 destination is
1345 	 * already dropped in ip6_input.
1346 	 */
1347 	if (__predict_false(le->outer.data.lro_type == LRO_TYPE_IPV6_TCP &&
1348 	    IN6_IS_ADDR_UNSPECIFIED(&le->outer.data.s_addr.v6)))
1349 		return (TCP_LRO_CANNOT);
1350 
1351 	if (__predict_false(le->inner.data.lro_type == LRO_TYPE_IPV6_TCP &&
1352 	    IN6_IS_ADDR_UNSPECIFIED(&le->inner.data.s_addr.v6)))
1353 		return (TCP_LRO_CANNOT);
1354 #endif
1355 	/* Lookup inp, if any.  Returns locked TCP inpcb. */
1356 	tp = tcp_lro_lookup(lc->ifp,
1357 	    (le->inner.data.lro_type == LRO_TYPE_NONE) ? &le->outer : &le->inner);
1358 	if (tp == NULL)
1359 		return (TCP_LRO_CANNOT);
1360 
1361 	counter_u64_add(tcp_inp_lro_locks_taken, 1);
1362 
1363 	/* Check if the inp is dead, Jim. */
1364 	if (tp->t_state == TCPS_TIME_WAIT) {
1365 		INP_WUNLOCK(tptoinpcb(tp));
1366 		return (TCP_LRO_CANNOT);
1367 	}
1368 	if (tp->t_lro_cpu == HPTS_CPU_NONE && lc->lro_cpu_is_set == 1)
1369 		tp->t_lro_cpu = lc->lro_last_cpu;
1370 	/* Check if the transport doesn't support the needed optimizations. */
1371 	if ((tp->t_flags2 & (TF2_SUPPORTS_MBUFQ | TF2_MBUF_ACKCMP)) == 0) {
1372 		INP_WUNLOCK(tptoinpcb(tp));
1373 		return (TCP_LRO_CANNOT);
1374 	}
1375 
1376 	if (tp->t_flags2 & TF2_MBUF_QUEUE_READY)
1377 		should_wake = false;
1378 	else
1379 		should_wake = true;
1380 	/* Check if packets should be tapped to BPF. */
1381 	bpf_req = bpf_peers_present(lc->ifp->if_bpf);
1382 	lagg_bpf_req = false;
1383 	lagg_ifp = NULL;
1384 	if (lc->ifp->if_type == IFT_IEEE8023ADLAG ||
1385 	    lc->ifp->if_type == IFT_INFINIBANDLAG) {
1386 		struct lagg_port *lp = lc->ifp->if_lagg;
1387 		struct lagg_softc *sc = lp->lp_softc;
1388 
1389 		lagg_ifp = sc->sc_ifp;
1390 		if (lagg_ifp != NULL)
1391 			lagg_bpf_req = bpf_peers_present(lagg_ifp->if_bpf);
1392 	}
1393 
1394 	/* Strip and compress all the incoming packets. */
1395  	can_append_old_cmp = true;
1396 	cmp = NULL;
1397 	for (pp = &le->m_head; *pp != NULL; ) {
1398 		mv_to = NULL;
1399 		if (do_bpf_strip_and_compress(tp, lc, le, pp,
1400 			&cmp, &mv_to, &should_wake, bpf_req,
1401  			lagg_bpf_req, lagg_ifp, can_append_old_cmp) == false) {
1402 			/* Advance to next mbuf. */
1403 			pp = &(*pp)->m_nextpkt;
1404  			/*
1405  			 * Once we have appended we can't look in the pending
1406  			 * inbound packets for a compressed ack to append to.
1407  			 */
1408  			can_append_old_cmp = false;
1409  			/*
1410  			 * Once we append we also need to stop adding to any
1411  			 * compressed ack we were remembering. A new cmp
1412  			 * ack will be required.
1413  			 */
1414  			cmp = NULL;
1415  			tcp_lro_log(tp, lc, le, NULL, 25, 0, 0, 0, 0);
1416 		} else if (mv_to != NULL) {
1417 			/* We are asked to move pp up */
1418 			pp = &mv_to->m_nextpkt;
1419  			tcp_lro_log(tp, lc, le, NULL, 24, 0, 0, 0, 0);
1420 		} else
1421  			tcp_lro_log(tp, lc, le, NULL, 26, 0, 0, 0, 0);
1422 	}
1423 	/* Update "m_last_mbuf", if any. */
1424 	if (pp == &le->m_head)
1425 		le->m_last_mbuf = *pp;
1426 	else
1427 		le->m_last_mbuf = __containerof(pp, struct mbuf, m_nextpkt);
1428 
1429 	/* Check if any data mbufs left. */
1430 	if (le->m_head != NULL) {
1431 		counter_u64_add(tcp_inp_lro_direct_queue, 1);
1432 		tcp_lro_log(tp, lc, le, NULL, 22, 1, tp->t_flags2, 0, 1);
1433 		tcp_queue_pkts(tp, le);
1434 	}
1435 	if (should_wake) {
1436 		/* Wakeup */
1437 		counter_u64_add(tcp_inp_lro_wokeup_queue, 1);
1438 		if ((*tp->t_fb->tfb_do_queued_segments)(tp, 0))
1439 			/* TCP cb gone and unlocked. */
1440 			return (0);
1441 	}
1442 	INP_WUNLOCK(tptoinpcb(tp));
1443 
1444 	return (0);	/* Success. */
1445 }
1446 #endif
1447 
1448 void
1449 tcp_lro_flush(struct lro_ctrl *lc, struct lro_entry *le)
1450 {
1451 	/* Only optimise if there are multiple packets waiting. */
1452 #ifdef TCPHPTS
1453 	int error;
1454 #endif
1455 
1456 	NET_EPOCH_ASSERT();
1457 #ifdef TCPHPTS
1458 	CURVNET_SET(lc->ifp->if_vnet);
1459 	error = tcp_lro_flush_tcphpts(lc, le);
1460 	CURVNET_RESTORE();
1461 	if (error != 0) {
1462 #endif
1463 		tcp_lro_condense(lc, le);
1464 		tcp_flush_out_entry(lc, le);
1465 #ifdef TCPHPTS
1466 	}
1467 #endif
1468 	lc->lro_flushed++;
1469 	bzero(le, sizeof(*le));
1470 	LIST_INSERT_HEAD(&lc->lro_free, le, next);
1471 }
1472 
1473 #define	tcp_lro_msb_64(x) (1ULL << (flsll(x) - 1))
1474 
1475 /*
1476  * The tcp_lro_sort() routine is comparable to qsort(), except it has
1477  * a worst case complexity limit of O(MIN(N,64)*N), where N is the
1478  * number of elements to sort and 64 is the number of sequence bits
1479  * available. The algorithm is bit-slicing the 64-bit sequence number,
1480  * sorting one bit at a time from the most significant bit until the
1481  * least significant one, skipping the constant bits. This is
1482  * typically called a radix sort.
1483  */
1484 static void
1485 tcp_lro_sort(struct lro_mbuf_sort *parray, uint32_t size)
1486 {
1487 	struct lro_mbuf_sort temp;
1488 	uint64_t ones;
1489 	uint64_t zeros;
1490 	uint32_t x;
1491 	uint32_t y;
1492 
1493 repeat:
1494 	/* for small arrays insertion sort is faster */
1495 	if (size <= 12) {
1496 		for (x = 1; x < size; x++) {
1497 			temp = parray[x];
1498 			for (y = x; y > 0 && temp.seq < parray[y - 1].seq; y--)
1499 				parray[y] = parray[y - 1];
1500 			parray[y] = temp;
1501 		}
1502 		return;
1503 	}
1504 
1505 	/* compute sequence bits which are constant */
1506 	ones = 0;
1507 	zeros = 0;
1508 	for (x = 0; x != size; x++) {
1509 		ones |= parray[x].seq;
1510 		zeros |= ~parray[x].seq;
1511 	}
1512 
1513 	/* compute bits which are not constant into "ones" */
1514 	ones &= zeros;
1515 	if (ones == 0)
1516 		return;
1517 
1518 	/* pick the most significant bit which is not constant */
1519 	ones = tcp_lro_msb_64(ones);
1520 
1521 	/*
1522 	 * Move entries having cleared sequence bits to the beginning
1523 	 * of the array:
1524 	 */
1525 	for (x = y = 0; y != size; y++) {
1526 		/* skip set bits */
1527 		if (parray[y].seq & ones)
1528 			continue;
1529 		/* swap entries */
1530 		temp = parray[x];
1531 		parray[x] = parray[y];
1532 		parray[y] = temp;
1533 		x++;
1534 	}
1535 
1536 	KASSERT(x != 0 && x != size, ("Memory is corrupted\n"));
1537 
1538 	/* sort zeros */
1539 	tcp_lro_sort(parray, x);
1540 
1541 	/* sort ones */
1542 	parray += x;
1543 	size -= x;
1544 	goto repeat;
1545 }
1546 
1547 void
1548 tcp_lro_flush_all(struct lro_ctrl *lc)
1549 {
1550 	uint64_t seq;
1551 	uint64_t nseq;
1552 	unsigned x;
1553 
1554 	NET_EPOCH_ASSERT();
1555 	/* check if no mbufs to flush */
1556 	if (lc->lro_mbuf_count == 0)
1557 		goto done;
1558 	if (lc->lro_cpu_is_set == 0) {
1559 		if (lc->lro_last_cpu == curcpu) {
1560 			lc->lro_cnt_of_same_cpu++;
1561 			/* Have we reached the threshold to declare a cpu? */
1562 			if (lc->lro_cnt_of_same_cpu > tcp_lro_cpu_set_thresh)
1563 				lc->lro_cpu_is_set = 1;
1564 		} else {
1565 			lc->lro_last_cpu = curcpu;
1566 			lc->lro_cnt_of_same_cpu = 0;
1567 		}
1568 	}
1569 	CURVNET_SET(lc->ifp->if_vnet);
1570 
1571 	/* get current time */
1572 	binuptime(&lc->lro_last_queue_time);
1573 
1574 	/* sort all mbufs according to stream */
1575 	tcp_lro_sort(lc->lro_mbuf_data, lc->lro_mbuf_count);
1576 
1577 	/* input data into LRO engine, stream by stream */
1578 	seq = 0;
1579 	for (x = 0; x != lc->lro_mbuf_count; x++) {
1580 		struct mbuf *mb;
1581 
1582 		/* get mbuf */
1583 		mb = lc->lro_mbuf_data[x].mb;
1584 
1585 		/* get sequence number, masking away the packet index */
1586 		nseq = lc->lro_mbuf_data[x].seq & (-1ULL << 24);
1587 
1588 		/* check for new stream */
1589 		if (seq != nseq) {
1590 			seq = nseq;
1591 
1592 			/* flush active streams */
1593 			tcp_lro_rx_done(lc);
1594 		}
1595 
1596 		/* add packet to LRO engine */
1597 		if (tcp_lro_rx_common(lc, mb, 0, false) != 0) {
1598  			/* Flush anything we have acummulated */
1599  			tcp_lro_flush_active(lc);
1600 			/* input packet to network layer */
1601 			(*lc->ifp->if_input)(lc->ifp, mb);
1602 			lc->lro_queued++;
1603 			lc->lro_flushed++;
1604 		}
1605 	}
1606 	CURVNET_RESTORE();
1607 done:
1608 	/* flush active streams */
1609 	tcp_lro_rx_done(lc);
1610 
1611 #ifdef TCPHPTS
1612 	tcp_run_hpts();
1613 #endif
1614 	lc->lro_mbuf_count = 0;
1615 }
1616 
1617 #ifdef TCPHPTS
1618 static void
1619 build_ack_entry(struct tcp_ackent *ae, struct tcphdr *th, struct mbuf *m,
1620     uint32_t *ts_ptr, uint16_t iptos)
1621 {
1622 	/*
1623 	 * Given a TCP ACK, summarize it down into the small TCP ACK
1624 	 * entry.
1625 	 */
1626 	ae->timestamp = m->m_pkthdr.rcv_tstmp;
1627 	ae->flags = 0;
1628 	if (m->m_flags & M_TSTMP_LRO)
1629 		ae->flags |= TSTMP_LRO;
1630 	else if (m->m_flags & M_TSTMP)
1631 		ae->flags |= TSTMP_HDWR;
1632 	ae->seq = ntohl(th->th_seq);
1633 	ae->ack = ntohl(th->th_ack);
1634 	ae->flags |= tcp_get_flags(th);
1635 	if (ts_ptr != NULL) {
1636 		ae->ts_value = ntohl(ts_ptr[1]);
1637 		ae->ts_echo = ntohl(ts_ptr[2]);
1638 		ae->flags |= HAS_TSTMP;
1639 	}
1640 	ae->win = ntohs(th->th_win);
1641 	ae->codepoint = iptos;
1642 }
1643 
1644 /*
1645  * Do BPF tap for either ACK_CMP packets or MBUF QUEUE type packets
1646  * and strip all, but the IPv4/IPv6 header.
1647  */
1648 static bool
1649 do_bpf_strip_and_compress(struct tcpcb *tp, struct lro_ctrl *lc,
1650     struct lro_entry *le, struct mbuf **pp, struct mbuf **cmp, struct mbuf **mv_to,
1651     bool *should_wake, bool bpf_req, bool lagg_bpf_req, struct ifnet *lagg_ifp, bool can_append_old_cmp)
1652 {
1653 	union {
1654 		void *ptr;
1655 		struct ip *ip4;
1656 		struct ip6_hdr *ip6;
1657 	} l3;
1658 	struct mbuf *m;
1659 	struct mbuf *nm;
1660 	struct tcphdr *th;
1661 	struct tcp_ackent *ack_ent;
1662 	uint32_t *ts_ptr;
1663 	int32_t n_mbuf;
1664 	bool other_opts, can_compress;
1665 	uint8_t lro_type;
1666 	uint16_t iptos;
1667 	int tcp_hdr_offset;
1668 	int idx;
1669 
1670 	/* Get current mbuf. */
1671 	m = *pp;
1672 
1673 	/* Let the BPF see the packet */
1674 	if (__predict_false(bpf_req))
1675 		ETHER_BPF_MTAP(lc->ifp, m);
1676 
1677 	if (__predict_false(lagg_bpf_req))
1678 		ETHER_BPF_MTAP(lagg_ifp, m);
1679 
1680 	tcp_hdr_offset = m->m_pkthdr.lro_tcp_h_off;
1681 	lro_type = le->inner.data.lro_type;
1682 	switch (lro_type) {
1683 	case LRO_TYPE_NONE:
1684 		lro_type = le->outer.data.lro_type;
1685 		switch (lro_type) {
1686 		case LRO_TYPE_IPV4_TCP:
1687 			tcp_hdr_offset -= sizeof(*le->outer.ip4);
1688 			m->m_pkthdr.lro_etype = ETHERTYPE_IP;
1689 			break;
1690 		case LRO_TYPE_IPV6_TCP:
1691 			tcp_hdr_offset -= sizeof(*le->outer.ip6);
1692 			m->m_pkthdr.lro_etype = ETHERTYPE_IPV6;
1693 			break;
1694 		default:
1695 			goto compressed;
1696 		}
1697 		break;
1698 	case LRO_TYPE_IPV4_TCP:
1699 		tcp_hdr_offset -= sizeof(*le->outer.ip4);
1700 		m->m_pkthdr.lro_etype = ETHERTYPE_IP;
1701 		break;
1702 	case LRO_TYPE_IPV6_TCP:
1703 		tcp_hdr_offset -= sizeof(*le->outer.ip6);
1704 		m->m_pkthdr.lro_etype = ETHERTYPE_IPV6;
1705 		break;
1706 	default:
1707 		goto compressed;
1708 	}
1709 
1710 	MPASS(tcp_hdr_offset >= 0);
1711 
1712 	m_adj(m, tcp_hdr_offset);
1713 	m->m_flags |= M_LRO_EHDRSTRP;
1714 	m->m_flags &= ~M_ACKCMP;
1715 	m->m_pkthdr.lro_tcp_h_off -= tcp_hdr_offset;
1716 
1717 	th = tcp_lro_get_th(m);
1718 
1719 	th->th_sum = 0;		/* TCP checksum is valid. */
1720 
1721 	/* Check if ACK can be compressed */
1722 	can_compress = tcp_lro_ack_valid(m, th, &ts_ptr, &other_opts);
1723 
1724 	/* Now lets look at the should wake states */
1725 	if ((other_opts == true) &&
1726 	    ((tp->t_flags2 & TF2_DONT_SACK_QUEUE) == 0)) {
1727 		/*
1728 		 * If there are other options (SACK?) and the
1729 		 * tcp endpoint has not expressly told us it does
1730 		 * not care about SACKS, then we should wake up.
1731 		 */
1732 		*should_wake = true;
1733 	} else if (*should_wake == false) {
1734 		/* Wakeup override check if we are false here  */
1735 		*should_wake = tcp_lro_check_wake_status(tp);
1736 	}
1737 	/* Is the ack compressable? */
1738 	if (can_compress == false)
1739 		goto done;
1740 	/* Does the TCP endpoint support ACK compression? */
1741 	if ((tp->t_flags2 & TF2_MBUF_ACKCMP) == 0)
1742 		goto done;
1743 
1744 	/* Lets get the TOS/traffic class field */
1745 	l3.ptr = mtod(m, void *);
1746 	switch (lro_type) {
1747 	case LRO_TYPE_IPV4_TCP:
1748 		iptos = l3.ip4->ip_tos;
1749 		break;
1750 	case LRO_TYPE_IPV6_TCP:
1751 		iptos = IPV6_TRAFFIC_CLASS(l3.ip6);
1752 		break;
1753 	default:
1754 		iptos = 0;	/* Keep compiler happy. */
1755 		break;
1756 	}
1757 	/* Now lets get space if we don't have some already */
1758 	if (*cmp == NULL) {
1759 new_one:
1760 		nm = tcp_lro_get_last_if_ackcmp(lc, le, tp, &n_mbuf,
1761 		    can_append_old_cmp);
1762 		if (__predict_false(nm == NULL))
1763 			goto done;
1764 		*cmp = nm;
1765 		if (n_mbuf) {
1766 			/*
1767 			 *  Link in the new cmp ack to our in-order place,
1768 			 * first set our cmp ack's next to where we are.
1769 			 */
1770 			nm->m_nextpkt = m;
1771 			(*pp) = nm;
1772 			/*
1773 			 * Set it up so mv_to is advanced to our
1774 			 * compressed ack. This way the caller can
1775 			 * advance pp to the right place.
1776 			 */
1777 			*mv_to = nm;
1778 			/*
1779 			 * Advance it here locally as well.
1780 			 */
1781 			pp = &nm->m_nextpkt;
1782 		}
1783 	} else {
1784 		/* We have one already we are working on */
1785 		nm = *cmp;
1786 		if (M_TRAILINGSPACE(nm) < sizeof(struct tcp_ackent)) {
1787 			/* We ran out of space */
1788 			tp->t_flags2 |= TF2_MBUF_L_ACKS;
1789 			goto new_one;
1790 		}
1791 	}
1792 	MPASS(M_TRAILINGSPACE(nm) >= sizeof(struct tcp_ackent));
1793 	counter_u64_add(tcp_inp_lro_compressed, 1);
1794 	le->compressed++;
1795 	/* We can add in to the one on the tail */
1796 	ack_ent = mtod(nm, struct tcp_ackent *);
1797 	idx = (nm->m_len / sizeof(struct tcp_ackent));
1798 	build_ack_entry(&ack_ent[idx], th, m, ts_ptr, iptos);
1799 
1800 	/* Bump the size of both pkt-hdr and len */
1801 	nm->m_len += sizeof(struct tcp_ackent);
1802 	nm->m_pkthdr.len += sizeof(struct tcp_ackent);
1803 compressed:
1804 	/* Advance to next mbuf before freeing. */
1805 	*pp = m->m_nextpkt;
1806 	m->m_nextpkt = NULL;
1807 	m_freem(m);
1808 	return (true);
1809 done:
1810 	counter_u64_add(tcp_uncomp_total, 1);
1811 	le->uncompressed++;
1812 	return (false);
1813 }
1814 #endif
1815 
1816 static struct lro_head *
1817 tcp_lro_rx_get_bucket(struct lro_ctrl *lc, struct mbuf *m, struct lro_parser *parser)
1818 {
1819 	u_long hash;
1820 
1821 	if (M_HASHTYPE_ISHASH(m)) {
1822 		hash = m->m_pkthdr.flowid;
1823 	} else {
1824 		for (unsigned i = hash = 0; i != LRO_RAW_ADDRESS_MAX; i++)
1825 			hash += parser->data.raw[i];
1826 	}
1827 	return (&lc->lro_hash[hash % lc->lro_hashsz]);
1828 }
1829 
1830 static int
1831 tcp_lro_rx_common(struct lro_ctrl *lc, struct mbuf *m, uint32_t csum, bool use_hash)
1832 {
1833 	struct lro_parser pi;	/* inner address data */
1834 	struct lro_parser po;	/* outer address data */
1835 	struct lro_parser *pa;	/* current parser for TCP stream */
1836 	struct lro_entry *le;
1837 	struct lro_head *bucket;
1838 	struct tcphdr *th;
1839 	int tcp_data_len;
1840 	int tcp_opt_len;
1841 	int error;
1842 	uint16_t tcp_data_sum;
1843 
1844 #ifdef INET
1845 	/* Quickly decide if packet cannot be LRO'ed */
1846 	if (__predict_false(V_ipforwarding != 0))
1847 		return (TCP_LRO_CANNOT);
1848 #endif
1849 #ifdef INET6
1850 	/* Quickly decide if packet cannot be LRO'ed */
1851 	if (__predict_false(V_ip6_forwarding != 0))
1852 		return (TCP_LRO_CANNOT);
1853 #endif
1854 	if (((m->m_pkthdr.csum_flags & (CSUM_DATA_VALID | CSUM_PSEUDO_HDR)) !=
1855 	     ((CSUM_DATA_VALID | CSUM_PSEUDO_HDR))) ||
1856 	    (m->m_pkthdr.csum_data != 0xffff)) {
1857 		/*
1858 		 * The checksum either did not have hardware offload
1859 		 * or it was a bad checksum. We can't LRO such
1860 		 * a packet.
1861 		 */
1862 		counter_u64_add(tcp_bad_csums, 1);
1863 		return (TCP_LRO_CANNOT);
1864 	}
1865 	/* We expect a contiguous header [eh, ip, tcp]. */
1866 	pa = tcp_lro_parser(m, &po, &pi, true);
1867 	if (__predict_false(pa == NULL))
1868 		return (TCP_LRO_NOT_SUPPORTED);
1869 
1870 	/* We don't expect any padding. */
1871 	error = tcp_lro_trim_mbuf_chain(m, pa);
1872 	if (__predict_false(error != 0))
1873 		return (error);
1874 
1875 #ifdef INET
1876 	switch (pa->data.lro_type) {
1877 	case LRO_TYPE_IPV4_TCP:
1878 		error = tcp_lro_rx_ipv4(lc, m, pa->ip4);
1879 		if (__predict_false(error != 0))
1880 			return (error);
1881 		break;
1882 	default:
1883 		break;
1884 	}
1885 #endif
1886 	/* If no hardware or arrival stamp on the packet add timestamp */
1887 	if ((m->m_flags & (M_TSTMP_LRO | M_TSTMP)) == 0) {
1888 		m->m_pkthdr.rcv_tstmp = bintime2ns(&lc->lro_last_queue_time);
1889 		m->m_flags |= M_TSTMP_LRO;
1890 	}
1891 
1892 	/* Get pointer to TCP header. */
1893 	th = pa->tcp;
1894 
1895 	/* Don't process SYN packets. */
1896 	if (__predict_false(tcp_get_flags(th) & TH_SYN))
1897 		return (TCP_LRO_CANNOT);
1898 
1899 	/* Get total TCP header length and compute payload length. */
1900 	tcp_opt_len = (th->th_off << 2);
1901 	tcp_data_len = m->m_pkthdr.len - ((uint8_t *)th -
1902 	    (uint8_t *)m->m_data) - tcp_opt_len;
1903 	tcp_opt_len -= sizeof(*th);
1904 
1905 	/* Don't process invalid TCP headers. */
1906 	if (__predict_false(tcp_opt_len < 0 || tcp_data_len < 0))
1907 		return (TCP_LRO_CANNOT);
1908 
1909 	/* Compute TCP data only checksum. */
1910 	if (tcp_data_len == 0)
1911 		tcp_data_sum = 0;	/* no data, no checksum */
1912 	else if (__predict_false(csum != 0))
1913 		tcp_data_sum = tcp_lro_rx_csum_data(pa, ~csum);
1914 	else
1915 		tcp_data_sum = tcp_lro_rx_csum_data(pa, ~th->th_sum);
1916 
1917 	/* Save TCP info in mbuf. */
1918 	m->m_nextpkt = NULL;
1919 	m->m_pkthdr.rcvif = lc->ifp;
1920 	m->m_pkthdr.lro_tcp_d_csum = tcp_data_sum;
1921 	m->m_pkthdr.lro_tcp_d_len = tcp_data_len;
1922 	m->m_pkthdr.lro_tcp_h_off = ((uint8_t *)th - (uint8_t *)m->m_data);
1923 	m->m_pkthdr.lro_nsegs = 1;
1924 
1925 	/* Get hash bucket. */
1926 	if (!use_hash) {
1927 		bucket = &lc->lro_hash[0];
1928 	} else {
1929 		bucket = tcp_lro_rx_get_bucket(lc, m, pa);
1930 	}
1931 
1932 	/* Try to find a matching previous segment. */
1933 	LIST_FOREACH(le, bucket, hash_next) {
1934 		/* Compare addresses and ports. */
1935 		if (lro_address_compare(&po.data, &le->outer.data) == false ||
1936 		    lro_address_compare(&pi.data, &le->inner.data) == false)
1937 			continue;
1938 
1939 		/* Check if no data and old ACK. */
1940 		if (tcp_data_len == 0 &&
1941 		    SEQ_LT(ntohl(th->th_ack), ntohl(le->ack_seq))) {
1942 			m_freem(m);
1943 			return (0);
1944 		}
1945 
1946 		/* Mark "m" in the last spot. */
1947 		le->m_last_mbuf->m_nextpkt = m;
1948 		/* Now set the tail to "m". */
1949 		le->m_last_mbuf = m;
1950 		return (0);
1951 	}
1952 
1953 	/* Try to find an empty slot. */
1954 	if (LIST_EMPTY(&lc->lro_free))
1955 		return (TCP_LRO_NO_ENTRIES);
1956 
1957 	/* Start a new segment chain. */
1958 	le = LIST_FIRST(&lc->lro_free);
1959 	LIST_REMOVE(le, next);
1960 	tcp_lro_active_insert(lc, bucket, le);
1961 
1962 	/* Make sure the headers are set. */
1963 	le->inner = pi;
1964 	le->outer = po;
1965 
1966 	/* Store time this entry was allocated. */
1967 	le->alloc_time = lc->lro_last_queue_time;
1968 
1969 	tcp_set_entry_to_mbuf(lc, le, m, th);
1970 
1971 	/* Now set the tail to "m". */
1972 	le->m_last_mbuf = m;
1973 
1974 	return (0);
1975 }
1976 
1977 int
1978 tcp_lro_rx(struct lro_ctrl *lc, struct mbuf *m, uint32_t csum)
1979 {
1980 	int error;
1981 
1982 	if (((m->m_pkthdr.csum_flags & (CSUM_DATA_VALID | CSUM_PSEUDO_HDR)) !=
1983 	     ((CSUM_DATA_VALID | CSUM_PSEUDO_HDR))) ||
1984 	    (m->m_pkthdr.csum_data != 0xffff)) {
1985 		/*
1986 		 * The checksum either did not have hardware offload
1987 		 * or it was a bad checksum. We can't LRO such
1988 		 * a packet.
1989 		 */
1990 		counter_u64_add(tcp_bad_csums, 1);
1991 		return (TCP_LRO_CANNOT);
1992 	}
1993 	/* get current time */
1994 	binuptime(&lc->lro_last_queue_time);
1995 	CURVNET_SET(lc->ifp->if_vnet);
1996 	error = tcp_lro_rx_common(lc, m, csum, true);
1997 	if (__predict_false(error != 0)) {
1998 		/*
1999 		 * Flush anything we have acummulated
2000 		 * ahead of this packet that can't
2001 		 * be LRO'd. This preserves order.
2002 		 */
2003 		tcp_lro_flush_active(lc);
2004 	}
2005 	CURVNET_RESTORE();
2006 
2007 	return (error);
2008 }
2009 
2010 void
2011 tcp_lro_queue_mbuf(struct lro_ctrl *lc, struct mbuf *mb)
2012 {
2013 	NET_EPOCH_ASSERT();
2014 	/* sanity checks */
2015 	if (__predict_false(lc->ifp == NULL || lc->lro_mbuf_data == NULL ||
2016 	    lc->lro_mbuf_max == 0)) {
2017 		/* packet drop */
2018 		m_freem(mb);
2019 		return;
2020 	}
2021 
2022 	/* check if packet is not LRO capable */
2023 	if (__predict_false((lc->ifp->if_capenable & IFCAP_LRO) == 0)) {
2024 		/* input packet to network layer */
2025 		(*lc->ifp->if_input) (lc->ifp, mb);
2026 		return;
2027 	}
2028 
2029  	/* If no hardware or arrival stamp on the packet add timestamp */
2030  	if ((tcplro_stacks_wanting_mbufq > 0) &&
2031  	    (tcp_less_accurate_lro_ts == 0) &&
2032  	    ((mb->m_flags & M_TSTMP) == 0)) {
2033  		/* Add in an LRO time since no hardware */
2034  		binuptime(&lc->lro_last_queue_time);
2035  		mb->m_pkthdr.rcv_tstmp = bintime2ns(&lc->lro_last_queue_time);
2036  		mb->m_flags |= M_TSTMP_LRO;
2037  	}
2038 
2039 	/* create sequence number */
2040 	lc->lro_mbuf_data[lc->lro_mbuf_count].seq =
2041 	    (((uint64_t)M_HASHTYPE_GET(mb)) << 56) |
2042 	    (((uint64_t)mb->m_pkthdr.flowid) << 24) |
2043 	    ((uint64_t)lc->lro_mbuf_count);
2044 
2045 	/* enter mbuf */
2046 	lc->lro_mbuf_data[lc->lro_mbuf_count].mb = mb;
2047 
2048 	/* flush if array is full */
2049 	if (__predict_false(++lc->lro_mbuf_count == lc->lro_mbuf_max))
2050 		tcp_lro_flush_all(lc);
2051 }
2052 
2053 /* end */
2054