xref: /dragonfly/sys/netinet/tcp_syncache.c (revision 49781055)
1 /*
2  * Copyright (c) 2003, 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2003, 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Copyright (c) 2003, 2004 Jeffrey M. Hsu.  All rights reserved.
36  *
37  * License terms: all terms for the DragonFly license above plus the following:
38  *
39  * 4. All advertising materials mentioning features or use of this software
40  *    must display the following acknowledgement:
41  *
42  *	This product includes software developed by Jeffrey M. Hsu
43  *	for the DragonFly Project.
44  *
45  *    This requirement may be waived with permission from Jeffrey Hsu.
46  *    This requirement will sunset and may be removed on July 8 2005,
47  *    after which the standard DragonFly license (as shown above) will
48  *    apply.
49  */
50 
51 /*
52  * All advertising materials mentioning features or use of this software
53  * must display the following acknowledgement:
54  *   This product includes software developed by Jeffrey M. Hsu.
55  *
56  * Copyright (c) 2001 Networks Associates Technologies, Inc.
57  * All rights reserved.
58  *
59  * This software was developed for the FreeBSD Project by Jonathan Lemon
60  * and NAI Labs, the Security Research Division of Network Associates, Inc.
61  * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
62  * DARPA CHATS research program.
63  *
64  * Redistribution and use in source and binary forms, with or without
65  * modification, are permitted provided that the following conditions
66  * are met:
67  * 1. Redistributions of source code must retain the above copyright
68  *    notice, this list of conditions and the following disclaimer.
69  * 2. Redistributions in binary form must reproduce the above copyright
70  *    notice, this list of conditions and the following disclaimer in the
71  *    documentation and/or other materials provided with the distribution.
72  * 3. The name of the author may not be used to endorse or promote
73  *    products derived from this software without specific prior written
74  *    permission.
75  *
76  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
77  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
78  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
79  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
80  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
81  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
82  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
83  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
84  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
85  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
86  * SUCH DAMAGE.
87  *
88  * $FreeBSD: src/sys/netinet/tcp_syncache.c,v 1.5.2.14 2003/02/24 04:02:27 silby Exp $
89  * $DragonFly: src/sys/netinet/tcp_syncache.c,v 1.24 2006/01/14 11:33:50 swildner Exp $
90  */
91 
92 #include "opt_inet6.h"
93 #include "opt_ipsec.h"
94 
95 #include <sys/param.h>
96 #include <sys/systm.h>
97 #include <sys/kernel.h>
98 #include <sys/sysctl.h>
99 #include <sys/malloc.h>
100 #include <sys/mbuf.h>
101 #include <sys/md5.h>
102 #include <sys/proc.h>		/* for proc0 declaration */
103 #include <sys/random.h>
104 #include <sys/socket.h>
105 #include <sys/socketvar.h>
106 #include <sys/in_cksum.h>
107 
108 #include <sys/msgport2.h>
109 
110 #include <net/if.h>
111 #include <net/route.h>
112 
113 #include <netinet/in.h>
114 #include <netinet/in_systm.h>
115 #include <netinet/ip.h>
116 #include <netinet/in_var.h>
117 #include <netinet/in_pcb.h>
118 #include <netinet/ip_var.h>
119 #include <netinet/ip6.h>
120 #ifdef INET6
121 #include <netinet/icmp6.h>
122 #include <netinet6/nd6.h>
123 #endif
124 #include <netinet6/ip6_var.h>
125 #include <netinet6/in6_pcb.h>
126 #include <netinet/tcp.h>
127 #include <netinet/tcp_fsm.h>
128 #include <netinet/tcp_seq.h>
129 #include <netinet/tcp_timer.h>
130 #include <netinet/tcp_var.h>
131 #include <netinet6/tcp6_var.h>
132 
133 #ifdef IPSEC
134 #include <netinet6/ipsec.h>
135 #ifdef INET6
136 #include <netinet6/ipsec6.h>
137 #endif
138 #include <netproto/key/key.h>
139 #endif /*IPSEC*/
140 
141 #ifdef FAST_IPSEC
142 #include <netproto/ipsec/ipsec.h>
143 #ifdef INET6
144 #include <netproto/ipsec/ipsec6.h>
145 #endif
146 #include <netproto/ipsec/key.h>
147 #define	IPSEC
148 #endif /*FAST_IPSEC*/
149 
150 #include <vm/vm_zone.h>
151 
152 static int tcp_syncookies = 1;
153 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
154     &tcp_syncookies, 0,
155     "Use TCP SYN cookies if the syncache overflows");
156 
157 static void	 syncache_drop(struct syncache *, struct syncache_head *);
158 static void	 syncache_free(struct syncache *);
159 static void	 syncache_insert(struct syncache *, struct syncache_head *);
160 struct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
161 static int	 syncache_respond(struct syncache *, struct mbuf *);
162 static struct	 socket *syncache_socket(struct syncache *, struct socket *);
163 static void	 syncache_timer(void *);
164 static u_int32_t syncookie_generate(struct syncache *);
165 static struct syncache *syncookie_lookup(struct in_conninfo *,
166 		    struct tcphdr *, struct socket *);
167 
168 /*
169  * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
170  * 3 retransmits corresponds to a timeout of (1 + 2 + 4 + 8 == 15) seconds,
171  * the odds are that the user has given up attempting to connect by then.
172  */
173 #define SYNCACHE_MAXREXMTS		3
174 
175 /* Arbitrary values */
176 #define TCP_SYNCACHE_HASHSIZE		512
177 #define TCP_SYNCACHE_BUCKETLIMIT	30
178 
179 struct netmsg_sc_timer {
180 	struct lwkt_msg nm_lmsg;
181 	struct msgrec *nm_mrec;		/* back pointer to containing msgrec */
182 };
183 
184 struct msgrec {
185 	struct netmsg_sc_timer msg;
186 	lwkt_port_t port;		/* constant after init */
187 	int slot;			/* constant after init */
188 };
189 
190 static int syncache_timer_handler(lwkt_msg_t);
191 
192 struct tcp_syncache {
193 	struct	vm_zone *zone;
194 	u_int	hashsize;
195 	u_int	hashmask;
196 	u_int	bucket_limit;
197 	u_int	cache_limit;
198 	u_int	rexmt_limit;
199 	u_int	hash_secret;
200 };
201 static struct tcp_syncache tcp_syncache;
202 
203 struct tcp_syncache_percpu {
204 	struct syncache_head	*hashbase;
205 	u_int			cache_count;
206 	TAILQ_HEAD(, syncache)	timerq[SYNCACHE_MAXREXMTS + 1];
207 	struct callout		tt_timerq[SYNCACHE_MAXREXMTS + 1];
208 	struct msgrec		mrec[SYNCACHE_MAXREXMTS + 1];
209 };
210 static struct tcp_syncache_percpu tcp_syncache_percpu[MAXCPU];
211 
212 static struct lwkt_port syncache_null_rport;
213 
214 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
215 
216 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RD,
217      &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
218 
219 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RD,
220      &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
221 
222 /* XXX JH */
223 #if 0
224 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
225      &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
226 #endif
227 
228 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RD,
229      &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
230 
231 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
232      &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
233 
234 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
235 
236 #define SYNCACHE_HASH(inc, mask)					\
237 	((tcp_syncache.hash_secret ^					\
238 	  (inc)->inc_faddr.s_addr ^					\
239 	  ((inc)->inc_faddr.s_addr >> 16) ^				\
240 	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
241 
242 #define SYNCACHE_HASH6(inc, mask)					\
243 	((tcp_syncache.hash_secret ^					\
244 	  (inc)->inc6_faddr.s6_addr32[0] ^				\
245 	  (inc)->inc6_faddr.s6_addr32[3] ^				\
246 	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
247 
248 #define ENDPTS_EQ(a, b) (						\
249 	(a)->ie_fport == (b)->ie_fport &&				\
250 	(a)->ie_lport == (b)->ie_lport &&				\
251 	(a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr &&			\
252 	(a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr			\
253 )
254 
255 #define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
256 
257 static __inline void
258 syncache_timeout(struct tcp_syncache_percpu *syncache_percpu,
259 		 struct syncache *sc, int slot)
260 {
261 	sc->sc_rxtslot = slot;
262 	sc->sc_rxttime = ticks + TCPTV_RTOBASE * tcp_backoff[slot];
263 	TAILQ_INSERT_TAIL(&syncache_percpu->timerq[slot], sc, sc_timerq);
264 	if (!callout_active(&syncache_percpu->tt_timerq[slot])) {
265 		callout_reset(&syncache_percpu->tt_timerq[slot],
266 			      TCPTV_RTOBASE * tcp_backoff[slot],
267 			      syncache_timer,
268 			      &syncache_percpu->mrec[slot]);
269 	}
270 }
271 
272 static void
273 syncache_free(struct syncache *sc)
274 {
275 	struct rtentry *rt;
276 #ifdef INET6
277 	const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
278 #else
279 	const boolean_t isipv6 = FALSE;
280 #endif
281 
282 	if (sc->sc_ipopts)
283 		m_free(sc->sc_ipopts);
284 
285 	rt = isipv6 ? sc->sc_route6.ro_rt : sc->sc_route.ro_rt;
286 	if (rt != NULL) {
287 		/*
288 		 * If this is the only reference to a protocol-cloned
289 		 * route, remove it immediately.
290 		 */
291 		if ((rt->rt_flags & RTF_WASCLONED) && rt->rt_refcnt == 1)
292 			rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
293 				  rt_mask(rt), rt->rt_flags, NULL);
294 		RTFREE(rt);
295 	}
296 
297 	zfree(tcp_syncache.zone, sc);
298 }
299 
300 void
301 syncache_init(void)
302 {
303 	int i, cpu;
304 
305 	tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
306 	tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
307 	tcp_syncache.cache_limit =
308 	    tcp_syncache.hashsize * tcp_syncache.bucket_limit;
309 	tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
310 	tcp_syncache.hash_secret = arc4random();
311 
312 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
313 	    &tcp_syncache.hashsize);
314 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
315 	    &tcp_syncache.cache_limit);
316 	TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
317 	    &tcp_syncache.bucket_limit);
318 	if (!powerof2(tcp_syncache.hashsize)) {
319 		printf("WARNING: syncache hash size is not a power of 2.\n");
320 		tcp_syncache.hashsize = 512;	/* safe default */
321 	}
322 	tcp_syncache.hashmask = tcp_syncache.hashsize - 1;
323 
324 	lwkt_initport_null_rport(&syncache_null_rport, NULL);
325 
326 	for (cpu = 0; cpu < ncpus2; cpu++) {
327 		struct tcp_syncache_percpu *syncache_percpu;
328 
329 		syncache_percpu = &tcp_syncache_percpu[cpu];
330 		/* Allocate the hash table. */
331 		MALLOC(syncache_percpu->hashbase, struct syncache_head *,
332 		    tcp_syncache.hashsize * sizeof(struct syncache_head),
333 		    M_SYNCACHE, M_WAITOK);
334 
335 		/* Initialize the hash buckets. */
336 		for (i = 0; i < tcp_syncache.hashsize; i++) {
337 			struct syncache_head *bucket;
338 
339 			bucket = &syncache_percpu->hashbase[i];
340 			TAILQ_INIT(&bucket->sch_bucket);
341 			bucket->sch_length = 0;
342 		}
343 
344 		for (i = 0; i <= SYNCACHE_MAXREXMTS; i++) {
345 			/* Initialize the timer queues. */
346 			TAILQ_INIT(&syncache_percpu->timerq[i]);
347 			callout_init(&syncache_percpu->tt_timerq[i]);
348 
349 			syncache_percpu->mrec[i].slot = i;
350 			syncache_percpu->mrec[i].port = tcp_cport(cpu);
351 			syncache_percpu->mrec[i].msg.nm_mrec =
352 			    &syncache_percpu->mrec[i];
353 			lwkt_initmsg(&syncache_percpu->mrec[i].msg.nm_lmsg,
354 			    &syncache_null_rport, 0,
355 			    lwkt_cmd_func(syncache_timer_handler),
356 			    lwkt_cmd_op_none);
357 		}
358 	}
359 
360 	/*
361 	 * Allocate the syncache entries.  Allow the zone to allocate one
362 	 * more entry than cache limit, so a new entry can bump out an
363 	 * older one.
364 	 */
365 	tcp_syncache.zone = zinit("syncache", sizeof(struct syncache),
366 	    tcp_syncache.cache_limit * ncpus2, ZONE_INTERRUPT, 0);
367 	tcp_syncache.cache_limit -= 1;
368 }
369 
370 static void
371 syncache_insert(struct syncache *sc, struct syncache_head *sch)
372 {
373 	struct tcp_syncache_percpu *syncache_percpu;
374 	struct syncache *sc2;
375 	int i;
376 
377 	syncache_percpu = &tcp_syncache_percpu[mycpu->gd_cpuid];
378 
379 	/*
380 	 * Make sure that we don't overflow the per-bucket
381 	 * limit or the total cache size limit.
382 	 */
383 	if (sch->sch_length >= tcp_syncache.bucket_limit) {
384 		/*
385 		 * The bucket is full, toss the oldest element.
386 		 */
387 		sc2 = TAILQ_FIRST(&sch->sch_bucket);
388 		sc2->sc_tp->ts_recent = ticks;
389 		syncache_drop(sc2, sch);
390 		tcpstat.tcps_sc_bucketoverflow++;
391 	} else if (syncache_percpu->cache_count >= tcp_syncache.cache_limit) {
392 		/*
393 		 * The cache is full.  Toss the oldest entry in the
394 		 * entire cache.  This is the front entry in the
395 		 * first non-empty timer queue with the largest
396 		 * timeout value.
397 		 */
398 		for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
399 			sc2 = TAILQ_FIRST(&syncache_percpu->timerq[i]);
400 			if (sc2 != NULL)
401 				break;
402 		}
403 		sc2->sc_tp->ts_recent = ticks;
404 		syncache_drop(sc2, NULL);
405 		tcpstat.tcps_sc_cacheoverflow++;
406 	}
407 
408 	/* Initialize the entry's timer. */
409 	syncache_timeout(syncache_percpu, sc, 0);
410 
411 	/* Put it into the bucket. */
412 	TAILQ_INSERT_TAIL(&sch->sch_bucket, sc, sc_hash);
413 	sch->sch_length++;
414 	syncache_percpu->cache_count++;
415 	tcpstat.tcps_sc_added++;
416 }
417 
418 static void
419 syncache_drop(struct syncache *sc, struct syncache_head *sch)
420 {
421 	struct tcp_syncache_percpu *syncache_percpu;
422 #ifdef INET6
423 	const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
424 #else
425 	const boolean_t isipv6 = FALSE;
426 #endif
427 
428 	syncache_percpu = &tcp_syncache_percpu[mycpu->gd_cpuid];
429 
430 	if (sch == NULL) {
431 		if (isipv6) {
432 			sch = &syncache_percpu->hashbase[
433 			    SYNCACHE_HASH6(&sc->sc_inc, tcp_syncache.hashmask)];
434 		} else {
435 			sch = &syncache_percpu->hashbase[
436 			    SYNCACHE_HASH(&sc->sc_inc, tcp_syncache.hashmask)];
437 		}
438 	}
439 
440 	TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
441 	sch->sch_length--;
442 	syncache_percpu->cache_count--;
443 
444 	/*
445 	 * Remove the entry from the syncache timer/timeout queue.  Note
446 	 * that we do not try to stop any running timer since we do not know
447 	 * whether the timer's message is in-transit or not.  Since timeouts
448 	 * are fairly long, taking an unneeded callout does not detrimentally
449 	 * effect performance.
450 	 */
451 	TAILQ_REMOVE(&syncache_percpu->timerq[sc->sc_rxtslot], sc, sc_timerq);
452 
453 	syncache_free(sc);
454 }
455 
456 /*
457  * Place a timeout message on the TCP thread's message queue.
458  * This routine runs in soft interrupt context.
459  *
460  * An invariant is for this routine to be called, the callout must
461  * have been active.  Note that the callout is not deactivated until
462  * after the message has been processed in syncache_timer_handler() below.
463  */
464 static void
465 syncache_timer(void *p)
466 {
467 	struct netmsg_sc_timer *msg = p;
468 
469 	lwkt_sendmsg(msg->nm_mrec->port, &msg->nm_lmsg);
470 }
471 
472 /*
473  * Service a timer message queued by timer expiration.
474  * This routine runs in the TCP protocol thread.
475  *
476  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
477  * If we have retransmitted an entry the maximum number of times, expire it.
478  *
479  * When we finish processing timed-out entries, we restart the timer if there
480  * are any entries still on the queue and deactivate it otherwise.  Only after
481  * a timer has been deactivated here can it be restarted by syncache_timeout().
482  */
483 static int
484 syncache_timer_handler(lwkt_msg_t msg)
485 {
486 	struct tcp_syncache_percpu *syncache_percpu;
487 	struct syncache *sc, *nsc;
488 	struct inpcb *inp;
489 	int slot;
490 
491 	slot = ((struct netmsg_sc_timer *)msg)->nm_mrec->slot;
492 	syncache_percpu = &tcp_syncache_percpu[mycpu->gd_cpuid];
493 
494 	nsc = TAILQ_FIRST(&syncache_percpu->timerq[slot]);
495 	while (nsc != NULL) {
496 		if (ticks < nsc->sc_rxttime)
497 			break;	/* finished because timerq sorted by time */
498 		sc = nsc;
499 		inp = sc->sc_tp->t_inpcb;
500 		if (slot == SYNCACHE_MAXREXMTS ||
501 		    slot >= tcp_syncache.rexmt_limit ||
502 		    inp->inp_gencnt != sc->sc_inp_gencnt) {
503 			nsc = TAILQ_NEXT(sc, sc_timerq);
504 			syncache_drop(sc, NULL);
505 			tcpstat.tcps_sc_stale++;
506 			continue;
507 		}
508 		/*
509 		 * syncache_respond() may call back into the syncache to
510 		 * to modify another entry, so do not obtain the next
511 		 * entry on the timer chain until it has completed.
512 		 */
513 		syncache_respond(sc, NULL);
514 		nsc = TAILQ_NEXT(sc, sc_timerq);
515 		tcpstat.tcps_sc_retransmitted++;
516 		TAILQ_REMOVE(&syncache_percpu->timerq[slot], sc, sc_timerq);
517 		syncache_timeout(syncache_percpu, sc, slot + 1);
518 	}
519 	if (nsc != NULL)
520 		callout_reset(&syncache_percpu->tt_timerq[slot],
521 		    nsc->sc_rxttime - ticks, syncache_timer,
522 		    &syncache_percpu->mrec[slot]);
523 	else
524 		callout_deactivate(&syncache_percpu->tt_timerq[slot]);
525 
526 	lwkt_replymsg(msg, 0);
527 	return (EASYNC);
528 }
529 
530 /*
531  * Find an entry in the syncache.
532  */
533 struct syncache *
534 syncache_lookup(struct in_conninfo *inc, struct syncache_head **schp)
535 {
536 	struct tcp_syncache_percpu *syncache_percpu;
537 	struct syncache *sc;
538 	struct syncache_head *sch;
539 
540 	syncache_percpu = &tcp_syncache_percpu[mycpu->gd_cpuid];
541 #ifdef INET6
542 	if (inc->inc_isipv6) {
543 		sch = &syncache_percpu->hashbase[
544 		    SYNCACHE_HASH6(inc, tcp_syncache.hashmask)];
545 		*schp = sch;
546 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash)
547 			if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
548 				return (sc);
549 	} else
550 #endif
551 	{
552 		sch = &syncache_percpu->hashbase[
553 		    SYNCACHE_HASH(inc, tcp_syncache.hashmask)];
554 		*schp = sch;
555 		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
556 #ifdef INET6
557 			if (sc->sc_inc.inc_isipv6)
558 				continue;
559 #endif
560 			if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
561 				return (sc);
562 		}
563 	}
564 	return (NULL);
565 }
566 
567 /*
568  * This function is called when we get a RST for a
569  * non-existent connection, so that we can see if the
570  * connection is in the syn cache.  If it is, zap it.
571  */
572 void
573 syncache_chkrst(struct in_conninfo *inc, struct tcphdr *th)
574 {
575 	struct syncache *sc;
576 	struct syncache_head *sch;
577 
578 	sc = syncache_lookup(inc, &sch);
579 	if (sc == NULL)
580 		return;
581 	/*
582 	 * If the RST bit is set, check the sequence number to see
583 	 * if this is a valid reset segment.
584 	 * RFC 793 page 37:
585 	 *   In all states except SYN-SENT, all reset (RST) segments
586 	 *   are validated by checking their SEQ-fields.  A reset is
587 	 *   valid if its sequence number is in the window.
588 	 *
589 	 *   The sequence number in the reset segment is normally an
590 	 *   echo of our outgoing acknowlegement numbers, but some hosts
591 	 *   send a reset with the sequence number at the rightmost edge
592 	 *   of our receive window, and we have to handle this case.
593 	 */
594 	if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
595 	    SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
596 		syncache_drop(sc, sch);
597 		tcpstat.tcps_sc_reset++;
598 	}
599 }
600 
601 void
602 syncache_badack(struct in_conninfo *inc)
603 {
604 	struct syncache *sc;
605 	struct syncache_head *sch;
606 
607 	sc = syncache_lookup(inc, &sch);
608 	if (sc != NULL) {
609 		syncache_drop(sc, sch);
610 		tcpstat.tcps_sc_badack++;
611 	}
612 }
613 
614 void
615 syncache_unreach(struct in_conninfo *inc, struct tcphdr *th)
616 {
617 	struct syncache *sc;
618 	struct syncache_head *sch;
619 
620 	/* we are called at splnet() here */
621 	sc = syncache_lookup(inc, &sch);
622 	if (sc == NULL)
623 		return;
624 
625 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
626 	if (ntohl(th->th_seq) != sc->sc_iss)
627 		return;
628 
629 	/*
630 	 * If we've rertransmitted 3 times and this is our second error,
631 	 * we remove the entry.  Otherwise, we allow it to continue on.
632 	 * This prevents us from incorrectly nuking an entry during a
633 	 * spurious network outage.
634 	 *
635 	 * See tcp_notify().
636 	 */
637 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtslot < 3) {
638 		sc->sc_flags |= SCF_UNREACH;
639 		return;
640 	}
641 	syncache_drop(sc, sch);
642 	tcpstat.tcps_sc_unreach++;
643 }
644 
645 /*
646  * Build a new TCP socket structure from a syncache entry.
647  */
648 static struct socket *
649 syncache_socket(struct syncache *sc, struct socket *lso)
650 {
651 	struct inpcb *inp = NULL, *linp;
652 	struct socket *so;
653 	struct tcpcb *tp;
654 #ifdef INET6
655 	const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
656 #else
657 	const boolean_t isipv6 = FALSE;
658 #endif
659 
660 	/*
661 	 * Ok, create the full blown connection, and set things up
662 	 * as they would have been set up if we had created the
663 	 * connection when the SYN arrived.  If we can't create
664 	 * the connection, abort it.
665 	 */
666 	so = sonewconn(lso, SS_ISCONNECTED);
667 	if (so == NULL) {
668 		/*
669 		 * Drop the connection; we will send a RST if the peer
670 		 * retransmits the ACK,
671 		 */
672 		tcpstat.tcps_listendrop++;
673 		goto abort;
674 	}
675 
676 	inp = so->so_pcb;
677 
678 	/*
679 	 * Insert new socket into hash list.
680 	 */
681 	inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
682 	if (isipv6) {
683 		inp->in6p_laddr = sc->sc_inc.inc6_laddr;
684 	} else {
685 #ifdef INET6
686 		inp->inp_vflag &= ~INP_IPV6;
687 		inp->inp_vflag |= INP_IPV4;
688 #endif
689 		inp->inp_laddr = sc->sc_inc.inc_laddr;
690 	}
691 	inp->inp_lport = sc->sc_inc.inc_lport;
692 	if (in_pcbinsporthash(inp) != 0) {
693 		/*
694 		 * Undo the assignments above if we failed to
695 		 * put the PCB on the hash lists.
696 		 */
697 		if (isipv6)
698 			inp->in6p_laddr = in6addr_any;
699 		else
700 			inp->inp_laddr.s_addr = INADDR_ANY;
701 		inp->inp_lport = 0;
702 		goto abort;
703 	}
704 	linp = so->so_pcb;
705 #ifdef IPSEC
706 	/* copy old policy into new socket's */
707 	if (ipsec_copy_policy(linp->inp_sp, inp->inp_sp))
708 		printf("syncache_expand: could not copy policy\n");
709 #endif
710 	if (isipv6) {
711 		struct in6_addr laddr6;
712 		struct sockaddr_in6 sin6;
713 		/*
714 		 * Inherit socket options from the listening socket.
715 		 * Note that in6p_inputopts are not (and should not be)
716 		 * copied, since it stores previously received options and is
717 		 * used to detect if each new option is different than the
718 		 * previous one and hence should be passed to a user.
719 		 * If we copied in6p_inputopts, a user would not be able to
720 		 * receive options just after calling the accept system call.
721 		 */
722 		inp->inp_flags |= linp->inp_flags & INP_CONTROLOPTS;
723 		if (linp->in6p_outputopts)
724 			inp->in6p_outputopts =
725 			    ip6_copypktopts(linp->in6p_outputopts, M_INTWAIT);
726 		inp->in6p_route = sc->sc_route6;
727 		sc->sc_route6.ro_rt = NULL;
728 
729 		sin6.sin6_family = AF_INET6;
730 		sin6.sin6_len = sizeof sin6;
731 		sin6.sin6_addr = sc->sc_inc.inc6_faddr;
732 		sin6.sin6_port = sc->sc_inc.inc_fport;
733 		sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
734 		laddr6 = inp->in6p_laddr;
735 		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
736 			inp->in6p_laddr = sc->sc_inc.inc6_laddr;
737 		if (in6_pcbconnect(inp, (struct sockaddr *)&sin6, &thread0)) {
738 			inp->in6p_laddr = laddr6;
739 			goto abort;
740 		}
741 	} else {
742 		struct in_addr laddr;
743 		struct sockaddr_in sin;
744 
745 		inp->inp_options = ip_srcroute();
746 		if (inp->inp_options == NULL) {
747 			inp->inp_options = sc->sc_ipopts;
748 			sc->sc_ipopts = NULL;
749 		}
750 		inp->inp_route = sc->sc_route;
751 		sc->sc_route.ro_rt = NULL;
752 
753 		sin.sin_family = AF_INET;
754 		sin.sin_len = sizeof sin;
755 		sin.sin_addr = sc->sc_inc.inc_faddr;
756 		sin.sin_port = sc->sc_inc.inc_fport;
757 		bzero(sin.sin_zero, sizeof sin.sin_zero);
758 		laddr = inp->inp_laddr;
759 		if (inp->inp_laddr.s_addr == INADDR_ANY)
760 			inp->inp_laddr = sc->sc_inc.inc_laddr;
761 		if (in_pcbconnect(inp, (struct sockaddr *)&sin, &thread0)) {
762 			inp->inp_laddr = laddr;
763 			goto abort;
764 		}
765 	}
766 
767 	tp = intotcpcb(inp);
768 	tp->t_state = TCPS_SYN_RECEIVED;
769 	tp->iss = sc->sc_iss;
770 	tp->irs = sc->sc_irs;
771 	tcp_rcvseqinit(tp);
772 	tcp_sendseqinit(tp);
773 	tp->snd_wl1 = sc->sc_irs;
774 	tp->rcv_up = sc->sc_irs + 1;
775 	tp->rcv_wnd = sc->sc_wnd;
776 	tp->rcv_adv += tp->rcv_wnd;
777 
778 	tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH | TF_NODELAY);
779 	if (sc->sc_flags & SCF_NOOPT)
780 		tp->t_flags |= TF_NOOPT;
781 	if (sc->sc_flags & SCF_WINSCALE) {
782 		tp->t_flags |= TF_REQ_SCALE | TF_RCVD_SCALE;
783 		tp->requested_s_scale = sc->sc_requested_s_scale;
784 		tp->request_r_scale = sc->sc_request_r_scale;
785 	}
786 	if (sc->sc_flags & SCF_TIMESTAMP) {
787 		tp->t_flags |= TF_REQ_TSTMP | TF_RCVD_TSTMP;
788 		tp->ts_recent = sc->sc_tsrecent;
789 		tp->ts_recent_age = ticks;
790 	}
791 	if (sc->sc_flags & SCF_CC) {
792 		/*
793 		 * Initialization of the tcpcb for transaction;
794 		 *   set SND.WND = SEG.WND,
795 		 *   initialize CCsend and CCrecv.
796 		 */
797 		tp->t_flags |= TF_REQ_CC | TF_RCVD_CC;
798 		tp->cc_send = sc->sc_cc_send;
799 		tp->cc_recv = sc->sc_cc_recv;
800 	}
801 	if (sc->sc_flags & SCF_SACK_PERMITTED)
802 		tp->t_flags |= TF_SACK_PERMITTED;
803 
804 	tcp_mss(tp, sc->sc_peer_mss);
805 
806 	/*
807 	 * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
808 	 */
809 	if (sc->sc_rxtslot != 0)
810 		tp->snd_cwnd = tp->t_maxseg;
811 	callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
812 
813 	tcpstat.tcps_accepts++;
814 	return (so);
815 
816 abort:
817 	if (so != NULL)
818 		soabort(so);
819 	return (NULL);
820 }
821 
822 /*
823  * This function gets called when we receive an ACK for a
824  * socket in the LISTEN state.  We look up the connection
825  * in the syncache, and if its there, we pull it out of
826  * the cache and turn it into a full-blown connection in
827  * the SYN-RECEIVED state.
828  */
829 int
830 syncache_expand(struct in_conninfo *inc, struct tcphdr *th, struct socket **sop,
831 		struct mbuf *m)
832 {
833 	struct syncache *sc;
834 	struct syncache_head *sch;
835 	struct socket *so;
836 
837 	sc = syncache_lookup(inc, &sch);
838 	if (sc == NULL) {
839 		/*
840 		 * There is no syncache entry, so see if this ACK is
841 		 * a returning syncookie.  To do this, first:
842 		 *  A. See if this socket has had a syncache entry dropped in
843 		 *     the past.  We don't want to accept a bogus syncookie
844 		 *     if we've never received a SYN.
845 		 *  B. check that the syncookie is valid.  If it is, then
846 		 *     cobble up a fake syncache entry, and return.
847 		 */
848 		if (!tcp_syncookies)
849 			return (0);
850 		sc = syncookie_lookup(inc, th, *sop);
851 		if (sc == NULL)
852 			return (0);
853 		sch = NULL;
854 		tcpstat.tcps_sc_recvcookie++;
855 	}
856 
857 	/*
858 	 * If seg contains an ACK, but not for our SYN/ACK, send a RST.
859 	 */
860 	if (th->th_ack != sc->sc_iss + 1)
861 		return (0);
862 
863 	so = syncache_socket(sc, *sop);
864 	if (so == NULL) {
865 #if 0
866 resetandabort:
867 		/* XXXjlemon check this - is this correct? */
868 		tcp_respond(NULL, m, m, th,
869 		    th->th_seq + tlen, (tcp_seq)0, TH_RST | TH_ACK);
870 #endif
871 		m_freem(m);			/* XXX only needed for above */
872 		tcpstat.tcps_sc_aborted++;
873 	} else {
874 		tcpstat.tcps_sc_completed++;
875 	}
876 	if (sch == NULL)
877 		syncache_free(sc);
878 	else
879 		syncache_drop(sc, sch);
880 	*sop = so;
881 	return (1);
882 }
883 
884 /*
885  * Given a LISTEN socket and an inbound SYN request, add
886  * this to the syn cache, and send back a segment:
887  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
888  * to the source.
889  *
890  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
891  * Doing so would require that we hold onto the data and deliver it
892  * to the application.  However, if we are the target of a SYN-flood
893  * DoS attack, an attacker could send data which would eventually
894  * consume all available buffer space if it were ACKed.  By not ACKing
895  * the data, we avoid this DoS scenario.
896  */
897 int
898 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
899 	     struct socket **sop, struct mbuf *m)
900 {
901 	struct tcp_syncache_percpu *syncache_percpu;
902 	struct tcpcb *tp;
903 	struct socket *so;
904 	struct syncache *sc = NULL;
905 	struct syncache_head *sch;
906 	struct mbuf *ipopts = NULL;
907 	struct rmxp_tao *taop;
908 	int win;
909 
910 	syncache_percpu = &tcp_syncache_percpu[mycpu->gd_cpuid];
911 	so = *sop;
912 	tp = sototcpcb(so);
913 
914 	/*
915 	 * Remember the IP options, if any.
916 	 */
917 #ifdef INET6
918 	if (!inc->inc_isipv6)
919 #endif
920 		ipopts = ip_srcroute();
921 
922 	/*
923 	 * See if we already have an entry for this connection.
924 	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
925 	 *
926 	 * XXX
927 	 * The syncache should be re-initialized with the contents
928 	 * of the new SYN which may have different options.
929 	 */
930 	sc = syncache_lookup(inc, &sch);
931 	if (sc != NULL) {
932 		tcpstat.tcps_sc_dupsyn++;
933 		if (ipopts) {
934 			/*
935 			 * If we were remembering a previous source route,
936 			 * forget it and use the new one we've been given.
937 			 */
938 			if (sc->sc_ipopts)
939 				m_free(sc->sc_ipopts);
940 			sc->sc_ipopts = ipopts;
941 		}
942 		/*
943 		 * Update timestamp if present.
944 		 */
945 		if (sc->sc_flags & SCF_TIMESTAMP)
946 			sc->sc_tsrecent = to->to_tsval;
947 
948 		/* Just update the TOF_SACK_PERMITTED for now. */
949 		if (tcp_do_sack && (to->to_flags & TOF_SACK_PERMITTED))
950 			sc->sc_flags |= SCF_SACK_PERMITTED;
951 		else
952 			sc->sc_flags &= ~SCF_SACK_PERMITTED;
953 
954 		/*
955 		 * PCB may have changed, pick up new values.
956 		 */
957 		sc->sc_tp = tp;
958 		sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
959 		if (syncache_respond(sc, m) == 0) {
960 			TAILQ_REMOVE(&syncache_percpu->timerq[sc->sc_rxtslot],
961 			    sc, sc_timerq);
962 			syncache_timeout(syncache_percpu, sc, sc->sc_rxtslot);
963 			tcpstat.tcps_sndacks++;
964 			tcpstat.tcps_sndtotal++;
965 		}
966 		*sop = NULL;
967 		return (1);
968 	}
969 
970 	/*
971 	 * This allocation is guaranteed to succeed because we
972 	 * preallocate one more syncache entry than cache_limit.
973 	 */
974 	sc = zalloc(tcp_syncache.zone);
975 
976 	/*
977 	 * Fill in the syncache values.
978 	 */
979 	sc->sc_tp = tp;
980 	sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
981 	sc->sc_ipopts = ipopts;
982 	sc->sc_inc.inc_fport = inc->inc_fport;
983 	sc->sc_inc.inc_lport = inc->inc_lport;
984 #ifdef INET6
985 	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
986 	if (inc->inc_isipv6) {
987 		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
988 		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
989 		sc->sc_route6.ro_rt = NULL;
990 	} else
991 #endif
992 	{
993 		sc->sc_inc.inc_faddr = inc->inc_faddr;
994 		sc->sc_inc.inc_laddr = inc->inc_laddr;
995 		sc->sc_route.ro_rt = NULL;
996 	}
997 	sc->sc_irs = th->th_seq;
998 	sc->sc_flags = 0;
999 	sc->sc_peer_mss = to->to_flags & TOF_MSS ? to->to_mss : 0;
1000 	if (tcp_syncookies)
1001 		sc->sc_iss = syncookie_generate(sc);
1002 	else
1003 		sc->sc_iss = arc4random();
1004 
1005 	/* Initial receive window: clip sbspace to [0 .. TCP_MAXWIN] */
1006 	win = sbspace(&so->so_rcv);
1007 	win = imax(win, 0);
1008 	win = imin(win, TCP_MAXWIN);
1009 	sc->sc_wnd = win;
1010 
1011 	if (tcp_do_rfc1323) {
1012 		/*
1013 		 * A timestamp received in a SYN makes
1014 		 * it ok to send timestamp requests and replies.
1015 		 */
1016 		if (to->to_flags & TOF_TS) {
1017 			sc->sc_tsrecent = to->to_tsval;
1018 			sc->sc_flags |= SCF_TIMESTAMP;
1019 		}
1020 		if (to->to_flags & TOF_SCALE) {
1021 			int wscale = 0;
1022 
1023 			/* Compute proper scaling value from buffer space */
1024 			while (wscale < TCP_MAX_WINSHIFT &&
1025 			    (TCP_MAXWIN << wscale) < so->so_rcv.sb_hiwat)
1026 				wscale++;
1027 			sc->sc_request_r_scale = wscale;
1028 			sc->sc_requested_s_scale = to->to_requested_s_scale;
1029 			sc->sc_flags |= SCF_WINSCALE;
1030 		}
1031 	}
1032 	if (tcp_do_rfc1644) {
1033 		/*
1034 		 * A CC or CC.new option received in a SYN makes
1035 		 * it ok to send CC in subsequent segments.
1036 		 */
1037 		if (to->to_flags & (TOF_CC | TOF_CCNEW)) {
1038 			sc->sc_cc_recv = to->to_cc;
1039 			sc->sc_cc_send = CC_INC(tcp_ccgen);
1040 			sc->sc_flags |= SCF_CC;
1041 		}
1042 	}
1043 	if (tcp_do_sack && (to->to_flags & TOF_SACK_PERMITTED))
1044 		sc->sc_flags |= SCF_SACK_PERMITTED;
1045 	if (tp->t_flags & TF_NOOPT)
1046 		sc->sc_flags = SCF_NOOPT;
1047 
1048 	/*
1049 	 * XXX
1050 	 * We have the option here of not doing TAO (even if the segment
1051 	 * qualifies) and instead fall back to a normal 3WHS via the syncache.
1052 	 * This allows us to apply synflood protection to TAO-qualifying SYNs
1053 	 * also. However, there should be a hueristic to determine when to
1054 	 * do this, and is not present at the moment.
1055 	 */
1056 
1057 	/*
1058 	 * Perform TAO test on incoming CC (SEG.CC) option, if any.
1059 	 * - compare SEG.CC against cached CC from the same host, if any.
1060 	 * - if SEG.CC > chached value, SYN must be new and is accepted
1061 	 *	immediately: save new CC in the cache, mark the socket
1062 	 *	connected, enter ESTABLISHED state, turn on flag to
1063 	 *	send a SYN in the next segment.
1064 	 *	A virtual advertised window is set in rcv_adv to
1065 	 *	initialize SWS prevention.  Then enter normal segment
1066 	 *	processing: drop SYN, process data and FIN.
1067 	 * - otherwise do a normal 3-way handshake.
1068 	 */
1069 	taop = tcp_gettaocache(&sc->sc_inc);
1070 	if (to->to_flags & TOF_CC) {
1071 		if ((tp->t_flags & TF_NOPUSH) &&
1072 		    sc->sc_flags & SCF_CC &&
1073 		    taop != NULL && taop->tao_cc != 0 &&
1074 		    CC_GT(to->to_cc, taop->tao_cc)) {
1075 			sc->sc_rxtslot = 0;
1076 			so = syncache_socket(sc, *sop);
1077 			if (so != NULL) {
1078 				taop->tao_cc = to->to_cc;
1079 				*sop = so;
1080 			}
1081 			syncache_free(sc);
1082 			return (so != NULL);
1083 		}
1084 	} else {
1085 		/*
1086 		 * No CC option, but maybe CC.NEW: invalidate cached value.
1087 		 */
1088 		if (taop != NULL)
1089 			taop->tao_cc = 0;
1090 	}
1091 	/*
1092 	 * TAO test failed or there was no CC option,
1093 	 *    do a standard 3-way handshake.
1094 	 */
1095 	if (syncache_respond(sc, m) == 0) {
1096 		syncache_insert(sc, sch);
1097 		tcpstat.tcps_sndacks++;
1098 		tcpstat.tcps_sndtotal++;
1099 	} else {
1100 		syncache_free(sc);
1101 		tcpstat.tcps_sc_dropped++;
1102 	}
1103 	*sop = NULL;
1104 	return (1);
1105 }
1106 
1107 static int
1108 syncache_respond(struct syncache *sc, struct mbuf *m)
1109 {
1110 	u_int8_t *optp;
1111 	int optlen, error;
1112 	u_int16_t tlen, hlen, mssopt;
1113 	struct ip *ip = NULL;
1114 	struct rtentry *rt;
1115 	struct tcphdr *th;
1116 	struct ip6_hdr *ip6 = NULL;
1117 #ifdef INET6
1118 	const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
1119 #else
1120 	const boolean_t isipv6 = FALSE;
1121 #endif
1122 
1123 	if (isipv6) {
1124 		rt = tcp_rtlookup6(&sc->sc_inc);
1125 		if (rt != NULL)
1126 			mssopt = rt->rt_ifp->if_mtu -
1127 			     (sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
1128 		else
1129 			mssopt = tcp_v6mssdflt;
1130 		hlen = sizeof(struct ip6_hdr);
1131 	} else {
1132 		rt = tcp_rtlookup(&sc->sc_inc);
1133 		if (rt != NULL)
1134 			mssopt = rt->rt_ifp->if_mtu -
1135 			     (sizeof(struct ip) + sizeof(struct tcphdr));
1136 		else
1137 			mssopt = tcp_mssdflt;
1138 		hlen = sizeof(struct ip);
1139 	}
1140 
1141 	/* Compute the size of the TCP options. */
1142 	if (sc->sc_flags & SCF_NOOPT) {
1143 		optlen = 0;
1144 	} else {
1145 		optlen = TCPOLEN_MAXSEG +
1146 		    ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
1147 		    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0) +
1148 		    ((sc->sc_flags & SCF_CC) ? TCPOLEN_CC_APPA * 2 : 0) +
1149 		    ((sc->sc_flags & SCF_SACK_PERMITTED) ?
1150 			TCPOLEN_SACK_PERMITTED_ALIGNED : 0);
1151 	}
1152 	tlen = hlen + sizeof(struct tcphdr) + optlen;
1153 
1154 	/*
1155 	 * XXX
1156 	 * assume that the entire packet will fit in a header mbuf
1157 	 */
1158 	KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
1159 
1160 	/*
1161 	 * XXX shouldn't this reuse the mbuf if possible ?
1162 	 * Create the IP+TCP header from scratch.
1163 	 */
1164 	if (m)
1165 		m_freem(m);
1166 
1167 	m = m_gethdr(MB_DONTWAIT, MT_HEADER);
1168 	if (m == NULL)
1169 		return (ENOBUFS);
1170 	m->m_data += max_linkhdr;
1171 	m->m_len = tlen;
1172 	m->m_pkthdr.len = tlen;
1173 	m->m_pkthdr.rcvif = NULL;
1174 
1175 	if (isipv6) {
1176 		ip6 = mtod(m, struct ip6_hdr *);
1177 		ip6->ip6_vfc = IPV6_VERSION;
1178 		ip6->ip6_nxt = IPPROTO_TCP;
1179 		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1180 		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1181 		ip6->ip6_plen = htons(tlen - hlen);
1182 		/* ip6_hlim is set after checksum */
1183 		/* ip6_flow = ??? */
1184 
1185 		th = (struct tcphdr *)(ip6 + 1);
1186 	} else {
1187 		ip = mtod(m, struct ip *);
1188 		ip->ip_v = IPVERSION;
1189 		ip->ip_hl = sizeof(struct ip) >> 2;
1190 		ip->ip_len = tlen;
1191 		ip->ip_id = 0;
1192 		ip->ip_off = 0;
1193 		ip->ip_sum = 0;
1194 		ip->ip_p = IPPROTO_TCP;
1195 		ip->ip_src = sc->sc_inc.inc_laddr;
1196 		ip->ip_dst = sc->sc_inc.inc_faddr;
1197 		ip->ip_ttl = sc->sc_tp->t_inpcb->inp_ip_ttl;   /* XXX */
1198 		ip->ip_tos = sc->sc_tp->t_inpcb->inp_ip_tos;   /* XXX */
1199 
1200 		/*
1201 		 * See if we should do MTU discovery.  Route lookups are
1202 		 * expensive, so we will only unset the DF bit if:
1203 		 *
1204 		 *	1) path_mtu_discovery is disabled
1205 		 *	2) the SCF_UNREACH flag has been set
1206 		 */
1207 		if (path_mtu_discovery
1208 		    && ((sc->sc_flags & SCF_UNREACH) == 0)) {
1209 		       ip->ip_off |= IP_DF;
1210 		}
1211 
1212 		th = (struct tcphdr *)(ip + 1);
1213 	}
1214 	th->th_sport = sc->sc_inc.inc_lport;
1215 	th->th_dport = sc->sc_inc.inc_fport;
1216 
1217 	th->th_seq = htonl(sc->sc_iss);
1218 	th->th_ack = htonl(sc->sc_irs + 1);
1219 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1220 	th->th_x2 = 0;
1221 	th->th_flags = TH_SYN | TH_ACK;
1222 	th->th_win = htons(sc->sc_wnd);
1223 	th->th_urp = 0;
1224 
1225 	/* Tack on the TCP options. */
1226 	if (optlen == 0)
1227 		goto no_options;
1228 	optp = (u_int8_t *)(th + 1);
1229 	*optp++ = TCPOPT_MAXSEG;
1230 	*optp++ = TCPOLEN_MAXSEG;
1231 	*optp++ = (mssopt >> 8) & 0xff;
1232 	*optp++ = mssopt & 0xff;
1233 
1234 	if (sc->sc_flags & SCF_WINSCALE) {
1235 		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
1236 		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
1237 		    sc->sc_request_r_scale);
1238 		optp += 4;
1239 	}
1240 
1241 	if (sc->sc_flags & SCF_TIMESTAMP) {
1242 		u_int32_t *lp = (u_int32_t *)(optp);
1243 
1244 		/* Form timestamp option as shown in appendix A of RFC 1323. */
1245 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
1246 		*lp++ = htonl(ticks);
1247 		*lp   = htonl(sc->sc_tsrecent);
1248 		optp += TCPOLEN_TSTAMP_APPA;
1249 	}
1250 
1251 	/*
1252 	 * Send CC and CC.echo if we received CC from our peer.
1253 	 */
1254 	if (sc->sc_flags & SCF_CC) {
1255 		u_int32_t *lp = (u_int32_t *)(optp);
1256 
1257 		*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CC));
1258 		*lp++ = htonl(sc->sc_cc_send);
1259 		*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CCECHO));
1260 		*lp   = htonl(sc->sc_cc_recv);
1261 		optp += TCPOLEN_CC_APPA * 2;
1262 	}
1263 
1264 	if (sc->sc_flags & SCF_SACK_PERMITTED) {
1265 		*((u_int32_t *)optp) = htonl(TCPOPT_SACK_PERMITTED_ALIGNED);
1266 		optp += TCPOLEN_SACK_PERMITTED_ALIGNED;
1267 	}
1268 
1269 no_options:
1270 	if (isipv6) {
1271 		struct route_in6 *ro6 = &sc->sc_route6;
1272 
1273 		th->th_sum = 0;
1274 		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
1275 		ip6->ip6_hlim = in6_selecthlim(NULL,
1276 		    ro6->ro_rt ? ro6->ro_rt->rt_ifp : NULL);
1277 		error = ip6_output(m, NULL, ro6, 0, NULL, NULL,
1278 				sc->sc_tp->t_inpcb);
1279 	} else {
1280 		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1281 				       htons(tlen - hlen + IPPROTO_TCP));
1282 		m->m_pkthdr.csum_flags = CSUM_TCP;
1283 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1284 		error = ip_output(m, sc->sc_ipopts, &sc->sc_route, 0, NULL,
1285 				sc->sc_tp->t_inpcb);
1286 	}
1287 	return (error);
1288 }
1289 
1290 /*
1291  * cookie layers:
1292  *
1293  *	|. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .|
1294  *	| peer iss                                                      |
1295  *	| MD5(laddr,faddr,secret,lport,fport)             |. . . . . . .|
1296  *	|                     0                       |(A)|             |
1297  * (A): peer mss index
1298  */
1299 
1300 /*
1301  * The values below are chosen to minimize the size of the tcp_secret
1302  * table, as well as providing roughly a 16 second lifetime for the cookie.
1303  */
1304 
1305 #define SYNCOOKIE_WNDBITS	5	/* exposed bits for window indexing */
1306 #define SYNCOOKIE_TIMESHIFT	1	/* scale ticks to window time units */
1307 
1308 #define SYNCOOKIE_WNDMASK	((1 << SYNCOOKIE_WNDBITS) - 1)
1309 #define SYNCOOKIE_NSECRETS	(1 << SYNCOOKIE_WNDBITS)
1310 #define SYNCOOKIE_TIMEOUT \
1311     (hz * (1 << SYNCOOKIE_WNDBITS) / (1 << SYNCOOKIE_TIMESHIFT))
1312 #define SYNCOOKIE_DATAMASK	((3 << SYNCOOKIE_WNDBITS) | SYNCOOKIE_WNDMASK)
1313 
1314 static struct {
1315 	u_int32_t	ts_secbits[4];
1316 	u_int		ts_expire;
1317 } tcp_secret[SYNCOOKIE_NSECRETS];
1318 
1319 static int tcp_msstab[] = { 0, 536, 1460, 8960 };
1320 
1321 static MD5_CTX syn_ctx;
1322 
1323 #define MD5Add(v)	MD5Update(&syn_ctx, (u_char *)&v, sizeof(v))
1324 
1325 struct md5_add {
1326 	u_int32_t laddr, faddr;
1327 	u_int32_t secbits[4];
1328 	u_int16_t lport, fport;
1329 };
1330 
1331 #ifdef CTASSERT
1332 CTASSERT(sizeof(struct md5_add) == 28);
1333 #endif
1334 
1335 /*
1336  * Consider the problem of a recreated (and retransmitted) cookie.  If the
1337  * original SYN was accepted, the connection is established.  The second
1338  * SYN is inflight, and if it arrives with an ISN that falls within the
1339  * receive window, the connection is killed.
1340  *
1341  * However, since cookies have other problems, this may not be worth
1342  * worrying about.
1343  */
1344 
1345 static u_int32_t
1346 syncookie_generate(struct syncache *sc)
1347 {
1348 	u_int32_t md5_buffer[4];
1349 	u_int32_t data;
1350 	int idx, i;
1351 	struct md5_add add;
1352 #ifdef INET6
1353 	const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
1354 #else
1355 	const boolean_t isipv6 = FALSE;
1356 #endif
1357 
1358 	idx = ((ticks << SYNCOOKIE_TIMESHIFT) / hz) & SYNCOOKIE_WNDMASK;
1359 	if (tcp_secret[idx].ts_expire < ticks) {
1360 		for (i = 0; i < 4; i++)
1361 			tcp_secret[idx].ts_secbits[i] = arc4random();
1362 		tcp_secret[idx].ts_expire = ticks + SYNCOOKIE_TIMEOUT;
1363 	}
1364 	for (data = sizeof(tcp_msstab) / sizeof(int) - 1; data > 0; data--)
1365 		if (tcp_msstab[data] <= sc->sc_peer_mss)
1366 			break;
1367 	data = (data << SYNCOOKIE_WNDBITS) | idx;
1368 	data ^= sc->sc_irs;				/* peer's iss */
1369 	MD5Init(&syn_ctx);
1370 	if (isipv6) {
1371 		MD5Add(sc->sc_inc.inc6_laddr);
1372 		MD5Add(sc->sc_inc.inc6_faddr);
1373 		add.laddr = 0;
1374 		add.faddr = 0;
1375 	} else {
1376 		add.laddr = sc->sc_inc.inc_laddr.s_addr;
1377 		add.faddr = sc->sc_inc.inc_faddr.s_addr;
1378 	}
1379 	add.lport = sc->sc_inc.inc_lport;
1380 	add.fport = sc->sc_inc.inc_fport;
1381 	add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1382 	add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1383 	add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1384 	add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1385 	MD5Add(add);
1386 	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1387 	data ^= (md5_buffer[0] & ~SYNCOOKIE_WNDMASK);
1388 	return (data);
1389 }
1390 
1391 static struct syncache *
1392 syncookie_lookup(struct in_conninfo *inc, struct tcphdr *th, struct socket *so)
1393 {
1394 	u_int32_t md5_buffer[4];
1395 	struct syncache *sc;
1396 	u_int32_t data;
1397 	int wnd, idx;
1398 	struct md5_add add;
1399 
1400 	data = (th->th_ack - 1) ^ (th->th_seq - 1);	/* remove ISS */
1401 	idx = data & SYNCOOKIE_WNDMASK;
1402 	if (tcp_secret[idx].ts_expire < ticks ||
1403 	    sototcpcb(so)->ts_recent + SYNCOOKIE_TIMEOUT < ticks)
1404 		return (NULL);
1405 	MD5Init(&syn_ctx);
1406 #ifdef INET6
1407 	if (inc->inc_isipv6) {
1408 		MD5Add(inc->inc6_laddr);
1409 		MD5Add(inc->inc6_faddr);
1410 		add.laddr = 0;
1411 		add.faddr = 0;
1412 	} else
1413 #endif
1414 	{
1415 		add.laddr = inc->inc_laddr.s_addr;
1416 		add.faddr = inc->inc_faddr.s_addr;
1417 	}
1418 	add.lport = inc->inc_lport;
1419 	add.fport = inc->inc_fport;
1420 	add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1421 	add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1422 	add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1423 	add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1424 	MD5Add(add);
1425 	MD5Final((u_char *)&md5_buffer, &syn_ctx);
1426 	data ^= md5_buffer[0];
1427 	if (data & ~SYNCOOKIE_DATAMASK)
1428 		return (NULL);
1429 	data = data >> SYNCOOKIE_WNDBITS;
1430 
1431 	/*
1432 	 * This allocation is guaranteed to succeed because we
1433 	 * preallocate one more syncache entry than cache_limit.
1434 	 */
1435 	sc = zalloc(tcp_syncache.zone);
1436 
1437 	/*
1438 	 * Fill in the syncache values.
1439 	 * XXX duplicate code from syncache_add
1440 	 */
1441 	sc->sc_ipopts = NULL;
1442 	sc->sc_inc.inc_fport = inc->inc_fport;
1443 	sc->sc_inc.inc_lport = inc->inc_lport;
1444 #ifdef INET6
1445 	sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
1446 	if (inc->inc_isipv6) {
1447 		sc->sc_inc.inc6_faddr = inc->inc6_faddr;
1448 		sc->sc_inc.inc6_laddr = inc->inc6_laddr;
1449 		sc->sc_route6.ro_rt = NULL;
1450 	} else
1451 #endif
1452 	{
1453 		sc->sc_inc.inc_faddr = inc->inc_faddr;
1454 		sc->sc_inc.inc_laddr = inc->inc_laddr;
1455 		sc->sc_route.ro_rt = NULL;
1456 	}
1457 	sc->sc_irs = th->th_seq - 1;
1458 	sc->sc_iss = th->th_ack - 1;
1459 	wnd = sbspace(&so->so_rcv);
1460 	wnd = imax(wnd, 0);
1461 	wnd = imin(wnd, TCP_MAXWIN);
1462 	sc->sc_wnd = wnd;
1463 	sc->sc_flags = 0;
1464 	sc->sc_rxtslot = 0;
1465 	sc->sc_peer_mss = tcp_msstab[data];
1466 	return (sc);
1467 }
1468