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