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