suser_* to priv_* conversion
[games.git] / sys / netinet / tcp_subr.c
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) 1982, 1986, 1988, 1990, 1993, 1995
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed by the University of
49  *      California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *      @(#)tcp_subr.c  8.2 (Berkeley) 5/24/95
67  * $FreeBSD: src/sys/netinet/tcp_subr.c,v 1.73.2.31 2003/01/24 05:11:34 sam Exp $
68  * $DragonFly: src/sys/netinet/tcp_subr.c,v 1.63 2008/11/11 10:46:58 sephe Exp $
69  */
70
71 #include "opt_compat.h"
72 #include "opt_inet6.h"
73 #include "opt_ipsec.h"
74 #include "opt_tcpdebug.h"
75
76 #include <sys/param.h>
77 #include <sys/systm.h>
78 #include <sys/callout.h>
79 #include <sys/kernel.h>
80 #include <sys/sysctl.h>
81 #include <sys/malloc.h>
82 #include <sys/mpipe.h>
83 #include <sys/mbuf.h>
84 #ifdef INET6
85 #include <sys/domain.h>
86 #endif
87 #include <sys/proc.h>
88 #include <sys/priv.h>
89 #include <sys/socket.h>
90 #include <sys/socketvar.h>
91 #include <sys/protosw.h>
92 #include <sys/random.h>
93 #include <sys/in_cksum.h>
94 #include <sys/ktr.h>
95
96 #include <vm/vm_zone.h>
97
98 #include <net/route.h>
99 #include <net/if.h>
100 #include <net/netisr.h>
101
102 #define _IP_VHL
103 #include <netinet/in.h>
104 #include <netinet/in_systm.h>
105 #include <netinet/ip.h>
106 #include <netinet/ip6.h>
107 #include <netinet/in_pcb.h>
108 #include <netinet6/in6_pcb.h>
109 #include <netinet/in_var.h>
110 #include <netinet/ip_var.h>
111 #include <netinet6/ip6_var.h>
112 #include <netinet/ip_icmp.h>
113 #ifdef INET6
114 #include <netinet/icmp6.h>
115 #endif
116 #include <netinet/tcp.h>
117 #include <netinet/tcp_fsm.h>
118 #include <netinet/tcp_seq.h>
119 #include <netinet/tcp_timer.h>
120 #include <netinet/tcp_var.h>
121 #include <netinet6/tcp6_var.h>
122 #include <netinet/tcpip.h>
123 #ifdef TCPDEBUG
124 #include <netinet/tcp_debug.h>
125 #endif
126 #include <netinet6/ip6protosw.h>
127
128 #ifdef IPSEC
129 #include <netinet6/ipsec.h>
130 #ifdef INET6
131 #include <netinet6/ipsec6.h>
132 #endif
133 #endif
134
135 #ifdef FAST_IPSEC
136 #include <netproto/ipsec/ipsec.h>
137 #ifdef INET6
138 #include <netproto/ipsec/ipsec6.h>
139 #endif
140 #define IPSEC
141 #endif
142
143 #include <sys/md5.h>
144 #include <sys/msgport2.h>
145 #include <machine/smp.h>
146
147 #include <net/netmsg2.h>
148
149 #if !defined(KTR_TCP)
150 #define KTR_TCP         KTR_ALL
151 #endif
152 KTR_INFO_MASTER(tcp);
153 KTR_INFO(KTR_TCP, tcp, rxmsg, 0, "tcp getmsg", 0);
154 KTR_INFO(KTR_TCP, tcp, wait, 1, "tcp waitmsg", 0);
155 KTR_INFO(KTR_TCP, tcp, delayed, 2, "tcp execute delayed ops", 0);
156 #define logtcp(name)    KTR_LOG(tcp_ ## name)
157
158 struct inpcbinfo tcbinfo[MAXCPU];
159 struct tcpcbackqhead tcpcbackq[MAXCPU];
160
161 int tcp_mpsafe_proto = 0;
162 TUNABLE_INT("net.inet.tcp.mpsafe_proto", &tcp_mpsafe_proto);
163
164 static int tcp_mpsafe_thread = 0;
165 TUNABLE_INT("net.inet.tcp.mpsafe_thread", &tcp_mpsafe_thread);
166 SYSCTL_INT(_net_inet_tcp, OID_AUTO, mpsafe_thread, CTLFLAG_RW,
167            &tcp_mpsafe_thread, 0,
168            "0:BGL, 1:Adaptive BGL, 2:No BGL(experimental)");
169
170 int tcp_mssdflt = TCP_MSS;
171 SYSCTL_INT(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW,
172     &tcp_mssdflt, 0, "Default TCP Maximum Segment Size");
173
174 #ifdef INET6
175 int tcp_v6mssdflt = TCP6_MSS;
176 SYSCTL_INT(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt, CTLFLAG_RW,
177     &tcp_v6mssdflt, 0, "Default TCP Maximum Segment Size for IPv6");
178 #endif
179
180 #if 0
181 static int tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
182 SYSCTL_INT(_net_inet_tcp, TCPCTL_RTTDFLT, rttdflt, CTLFLAG_RW,
183     &tcp_rttdflt, 0, "Default maximum TCP Round Trip Time");
184 #endif
185
186 int tcp_do_rfc1323 = 1;
187 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW,
188     &tcp_do_rfc1323, 0, "Enable rfc1323 (high performance TCP) extensions");
189
190 int tcp_do_rfc1644 = 0;
191 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1644, rfc1644, CTLFLAG_RW,
192     &tcp_do_rfc1644, 0, "Enable rfc1644 (TTCP) extensions");
193
194 static int tcp_tcbhashsize = 0;
195 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RD,
196      &tcp_tcbhashsize, 0, "Size of TCP control block hashtable");
197
198 static int do_tcpdrain = 1;
199 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
200      "Enable tcp_drain routine for extra help when low on mbufs");
201
202 /* XXX JH */
203 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD,
204     &tcbinfo[0].ipi_count, 0, "Number of active PCBs");
205
206 static int icmp_may_rst = 1;
207 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW, &icmp_may_rst, 0,
208     "Certain ICMP unreachable messages may abort connections in SYN_SENT");
209
210 static int tcp_isn_reseed_interval = 0;
211 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_RW,
212     &tcp_isn_reseed_interval, 0, "Seconds between reseeding of ISN secret");
213
214 /*
215  * TCP bandwidth limiting sysctls.  Note that the default lower bound of
216  * 1024 exists only for debugging.  A good production default would be
217  * something like 6100.
218  */
219 static int tcp_inflight_enable = 0;
220 SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_enable, CTLFLAG_RW,
221     &tcp_inflight_enable, 0, "Enable automatic TCP inflight data limiting");
222
223 static int tcp_inflight_debug = 0;
224 SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_debug, CTLFLAG_RW,
225     &tcp_inflight_debug, 0, "Debug TCP inflight calculations");
226
227 static int tcp_inflight_min = 6144;
228 SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_min, CTLFLAG_RW,
229     &tcp_inflight_min, 0, "Lower bound for TCP inflight window");
230
231 static int tcp_inflight_max = TCP_MAXWIN << TCP_MAX_WINSHIFT;
232 SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_max, CTLFLAG_RW,
233     &tcp_inflight_max, 0, "Upper bound for TCP inflight window");
234
235 static int tcp_inflight_stab = 20;
236 SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_stab, CTLFLAG_RW,
237     &tcp_inflight_stab, 0, "Slop in maximal packets / 10 (20 = 2 packets)");
238
239 static MALLOC_DEFINE(M_TCPTEMP, "tcptemp", "TCP Templates for Keepalives");
240 static struct malloc_pipe tcptemp_mpipe;
241
242 static void tcp_willblock(int);
243 static void tcp_cleartaocache (void);
244 static void tcp_notify (struct inpcb *, int);
245
246 struct tcp_stats tcpstats_percpu[MAXCPU];
247 #ifdef SMP
248 static int
249 sysctl_tcpstats(SYSCTL_HANDLER_ARGS)
250 {
251         int cpu, error = 0;
252
253         for (cpu = 0; cpu < ncpus; ++cpu) {
254                 if ((error = SYSCTL_OUT(req, &tcpstats_percpu[cpu],
255                                         sizeof(struct tcp_stats))))
256                         break;
257                 if ((error = SYSCTL_IN(req, &tcpstats_percpu[cpu],
258                                        sizeof(struct tcp_stats))))
259                         break;
260         }
261
262         return (error);
263 }
264 SYSCTL_PROC(_net_inet_tcp, TCPCTL_STATS, stats, (CTLTYPE_OPAQUE | CTLFLAG_RW),
265     0, 0, sysctl_tcpstats, "S,tcp_stats", "TCP statistics");
266 #else
267 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
268     &tcpstat, tcp_stats, "TCP statistics");
269 #endif
270
271 /*
272  * Target size of TCP PCB hash tables. Must be a power of two.
273  *
274  * Note that this can be overridden by the kernel environment
275  * variable net.inet.tcp.tcbhashsize
276  */
277 #ifndef TCBHASHSIZE
278 #define TCBHASHSIZE     512
279 #endif
280
281 /*
282  * This is the actual shape of what we allocate using the zone
283  * allocator.  Doing it this way allows us to protect both structures
284  * using the same generation count, and also eliminates the overhead
285  * of allocating tcpcbs separately.  By hiding the structure here,
286  * we avoid changing most of the rest of the code (although it needs
287  * to be changed, eventually, for greater efficiency).
288  */
289 #define ALIGNMENT       32
290 #define ALIGNM1         (ALIGNMENT - 1)
291 struct  inp_tp {
292         union {
293                 struct  inpcb inp;
294                 char    align[(sizeof(struct inpcb) + ALIGNM1) & ~ALIGNM1];
295         } inp_tp_u;
296         struct  tcpcb tcb;
297         struct  callout inp_tp_rexmt, inp_tp_persist, inp_tp_keep, inp_tp_2msl;
298         struct  callout inp_tp_delack;
299         struct  netmsg_tcp_timer inp_tp_timermsg;
300 };
301 #undef ALIGNMENT
302 #undef ALIGNM1
303
304 /*
305  * Tcp initialization
306  */
307 void
308 tcp_init(void)
309 {
310         struct inpcbporthead *porthashbase;
311         u_long porthashmask;
312         struct vm_zone *ipi_zone;
313         int hashsize = TCBHASHSIZE;
314         int cpu;
315
316         /*
317          * note: tcptemp is used for keepalives, and it is ok for an
318          * allocation to fail so do not specify MPF_INT.
319          */
320         mpipe_init(&tcptemp_mpipe, M_TCPTEMP, sizeof(struct tcptemp),
321                     25, -1, 0, NULL);
322
323         tcp_ccgen = 1;
324         tcp_cleartaocache();
325
326         tcp_delacktime = TCPTV_DELACK;
327         tcp_keepinit = TCPTV_KEEP_INIT;
328         tcp_keepidle = TCPTV_KEEP_IDLE;
329         tcp_keepintvl = TCPTV_KEEPINTVL;
330         tcp_maxpersistidle = TCPTV_KEEP_IDLE;
331         tcp_msl = TCPTV_MSL;
332         tcp_rexmit_min = TCPTV_MIN;
333         tcp_rexmit_slop = TCPTV_CPU_VAR;
334
335         TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", &hashsize);
336         if (!powerof2(hashsize)) {
337                 kprintf("WARNING: TCB hash size not a power of 2\n");
338                 hashsize = 512; /* safe default */
339         }
340         tcp_tcbhashsize = hashsize;
341         porthashbase = hashinit(hashsize, M_PCB, &porthashmask);
342         ipi_zone = zinit("tcpcb", sizeof(struct inp_tp), maxsockets,
343                          ZONE_INTERRUPT, 0);
344
345         for (cpu = 0; cpu < ncpus2; cpu++) {
346                 in_pcbinfo_init(&tcbinfo[cpu]);
347                 tcbinfo[cpu].cpu = cpu;
348                 tcbinfo[cpu].hashbase = hashinit(hashsize, M_PCB,
349                     &tcbinfo[cpu].hashmask);
350                 tcbinfo[cpu].porthashbase = porthashbase;
351                 tcbinfo[cpu].porthashmask = porthashmask;
352                 tcbinfo[cpu].wildcardhashbase = hashinit(hashsize, M_PCB,
353                     &tcbinfo[cpu].wildcardhashmask);
354                 tcbinfo[cpu].ipi_zone = ipi_zone;
355                 TAILQ_INIT(&tcpcbackq[cpu]);
356         }
357
358         tcp_reass_maxseg = nmbclusters / 16;
359         TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments", &tcp_reass_maxseg);
360
361 #ifdef INET6
362 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
363 #else
364 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
365 #endif
366         if (max_protohdr < TCP_MINPROTOHDR)
367                 max_protohdr = TCP_MINPROTOHDR;
368         if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
369                 panic("tcp_init");
370 #undef TCP_MINPROTOHDR
371
372         /*
373          * Initialize TCP statistics counters for each CPU.
374          */
375 #ifdef SMP
376         for (cpu = 0; cpu < ncpus; ++cpu) {
377                 bzero(&tcpstats_percpu[cpu], sizeof(struct tcp_stats));
378         }
379 #else
380         bzero(&tcpstat, sizeof(struct tcp_stats));
381 #endif
382
383         syncache_init();
384         tcp_thread_init();
385 }
386
387 void
388 tcpmsg_service_loop(void *dummy)
389 {
390         struct netmsg *msg;
391         int mplocked;
392
393         /*
394          * Thread was started with TDF_MPSAFE
395          */
396         mplocked = 0;
397
398         while ((msg = lwkt_waitport(&curthread->td_msgport, 0))) {
399                 do {
400                         logtcp(rxmsg);
401                         mplocked = netmsg_service(msg, tcp_mpsafe_thread,
402                                                   mplocked);
403                 } while ((msg = lwkt_getport(&curthread->td_msgport)) != NULL);
404
405                 logtcp(delayed);
406                 tcp_willblock(mplocked);
407                 logtcp(wait);
408         }
409 }
410
411 static void
412 tcp_willblock(int mplocked)
413 {
414         struct tcpcb *tp;
415         int cpu = mycpu->gd_cpuid;
416         int unlock = 0;
417
418         if (!mplocked && !tcp_mpsafe_proto) {
419                 if (TAILQ_EMPTY(&tcpcbackq[cpu]))
420                         return;
421
422                 get_mplock();
423                 mplocked = 1;
424                 unlock = 1;
425         }
426
427         while ((tp = TAILQ_FIRST(&tcpcbackq[cpu])) != NULL) {
428                 KKASSERT(tp->t_flags & TF_ONOUTPUTQ);
429                 tp->t_flags &= ~TF_ONOUTPUTQ;
430                 TAILQ_REMOVE(&tcpcbackq[cpu], tp, t_outputq);
431                 tcp_output(tp);
432         }
433
434         if (unlock)
435                 rel_mplock();
436 }
437
438
439 /*
440  * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
441  * tcp_template used to store this data in mbufs, but we now recopy it out
442  * of the tcpcb each time to conserve mbufs.
443  */
444 void
445 tcp_fillheaders(struct tcpcb *tp, void *ip_ptr, void *tcp_ptr)
446 {
447         struct inpcb *inp = tp->t_inpcb;
448         struct tcphdr *tcp_hdr = (struct tcphdr *)tcp_ptr;
449
450 #ifdef INET6
451         if (inp->inp_vflag & INP_IPV6) {
452                 struct ip6_hdr *ip6;
453
454                 ip6 = (struct ip6_hdr *)ip_ptr;
455                 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
456                         (inp->in6p_flowinfo & IPV6_FLOWINFO_MASK);
457                 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
458                         (IPV6_VERSION & IPV6_VERSION_MASK);
459                 ip6->ip6_nxt = IPPROTO_TCP;
460                 ip6->ip6_plen = sizeof(struct tcphdr);
461                 ip6->ip6_src = inp->in6p_laddr;
462                 ip6->ip6_dst = inp->in6p_faddr;
463                 tcp_hdr->th_sum = 0;
464         } else
465 #endif
466         {
467                 struct ip *ip = (struct ip *) ip_ptr;
468
469                 ip->ip_vhl = IP_VHL_BORING;
470                 ip->ip_tos = 0;
471                 ip->ip_len = 0;
472                 ip->ip_id = 0;
473                 ip->ip_off = 0;
474                 ip->ip_ttl = 0;
475                 ip->ip_sum = 0;
476                 ip->ip_p = IPPROTO_TCP;
477                 ip->ip_src = inp->inp_laddr;
478                 ip->ip_dst = inp->inp_faddr;
479                 tcp_hdr->th_sum = in_pseudo(ip->ip_src.s_addr,
480                                     ip->ip_dst.s_addr,
481                                     htons(sizeof(struct tcphdr) + IPPROTO_TCP));
482         }
483
484         tcp_hdr->th_sport = inp->inp_lport;
485         tcp_hdr->th_dport = inp->inp_fport;
486         tcp_hdr->th_seq = 0;
487         tcp_hdr->th_ack = 0;
488         tcp_hdr->th_x2 = 0;
489         tcp_hdr->th_off = 5;
490         tcp_hdr->th_flags = 0;
491         tcp_hdr->th_win = 0;
492         tcp_hdr->th_urp = 0;
493 }
494
495 /*
496  * Create template to be used to send tcp packets on a connection.
497  * Allocates an mbuf and fills in a skeletal tcp/ip header.  The only
498  * use for this function is in keepalives, which use tcp_respond.
499  */
500 struct tcptemp *
501 tcp_maketemplate(struct tcpcb *tp)
502 {
503         struct tcptemp *tmp;
504
505         if ((tmp = mpipe_alloc_nowait(&tcptemp_mpipe)) == NULL)
506                 return (NULL);
507         tcp_fillheaders(tp, &tmp->tt_ipgen, &tmp->tt_t);
508         return (tmp);
509 }
510
511 void
512 tcp_freetemplate(struct tcptemp *tmp)
513 {
514         mpipe_free(&tcptemp_mpipe, tmp);
515 }
516
517 /*
518  * Send a single message to the TCP at address specified by
519  * the given TCP/IP header.  If m == NULL, then we make a copy
520  * of the tcpiphdr at ti and send directly to the addressed host.
521  * This is used to force keep alive messages out using the TCP
522  * template for a connection.  If flags are given then we send
523  * a message back to the TCP which originated the * segment ti,
524  * and discard the mbuf containing it and any other attached mbufs.
525  *
526  * In any case the ack and sequence number of the transmitted
527  * segment are as specified by the parameters.
528  *
529  * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
530  */
531 void
532 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
533             tcp_seq ack, tcp_seq seq, int flags)
534 {
535         int tlen;
536         int win = 0;
537         struct route *ro = NULL;
538         struct route sro;
539         struct ip *ip = ipgen;
540         struct tcphdr *nth;
541         int ipflags = 0;
542         struct route_in6 *ro6 = NULL;
543         struct route_in6 sro6;
544         struct ip6_hdr *ip6 = ipgen;
545         boolean_t use_tmpro = TRUE;
546 #ifdef INET6
547         boolean_t isipv6 = (IP_VHL_V(ip->ip_vhl) == 6);
548 #else
549         const boolean_t isipv6 = FALSE;
550 #endif
551
552         if (tp != NULL) {
553                 if (!(flags & TH_RST)) {
554                         win = ssb_space(&tp->t_inpcb->inp_socket->so_rcv);
555                         if (win > (long)TCP_MAXWIN << tp->rcv_scale)
556                                 win = (long)TCP_MAXWIN << tp->rcv_scale;
557                 }
558                 /*
559                  * Don't use the route cache of a listen socket,
560                  * it is not MPSAFE; use temporary route cache.
561                  */
562                 if (tp->t_state != TCPS_LISTEN) {
563                         if (isipv6)
564                                 ro6 = &tp->t_inpcb->in6p_route;
565                         else
566                                 ro = &tp->t_inpcb->inp_route;
567                         use_tmpro = FALSE;
568                 }
569         }
570         if (use_tmpro) {
571                 if (isipv6) {
572                         ro6 = &sro6;
573                         bzero(ro6, sizeof *ro6);
574                 } else {
575                         ro = &sro;
576                         bzero(ro, sizeof *ro);
577                 }
578         }
579         if (m == NULL) {
580                 m = m_gethdr(MB_DONTWAIT, MT_HEADER);
581                 if (m == NULL)
582                         return;
583                 tlen = 0;
584                 m->m_data += max_linkhdr;
585                 if (isipv6) {
586                         bcopy(ip6, mtod(m, caddr_t), sizeof(struct ip6_hdr));
587                         ip6 = mtod(m, struct ip6_hdr *);
588                         nth = (struct tcphdr *)(ip6 + 1);
589                 } else {
590                         bcopy(ip, mtod(m, caddr_t), sizeof(struct ip));
591                         ip = mtod(m, struct ip *);
592                         nth = (struct tcphdr *)(ip + 1);
593                 }
594                 bcopy(th, nth, sizeof(struct tcphdr));
595                 flags = TH_ACK;
596         } else {
597                 m_freem(m->m_next);
598                 m->m_next = NULL;
599                 m->m_data = (caddr_t)ipgen;
600                 /* m_len is set later */
601                 tlen = 0;
602 #define xchg(a, b, type) { type t; t = a; a = b; b = t; }
603                 if (isipv6) {
604                         xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
605                         nth = (struct tcphdr *)(ip6 + 1);
606                 } else {
607                         xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long);
608                         nth = (struct tcphdr *)(ip + 1);
609                 }
610                 if (th != nth) {
611                         /*
612                          * this is usually a case when an extension header
613                          * exists between the IPv6 header and the
614                          * TCP header.
615                          */
616                         nth->th_sport = th->th_sport;
617                         nth->th_dport = th->th_dport;
618                 }
619                 xchg(nth->th_dport, nth->th_sport, n_short);
620 #undef xchg
621         }
622         if (isipv6) {
623                 ip6->ip6_flow = 0;
624                 ip6->ip6_vfc = IPV6_VERSION;
625                 ip6->ip6_nxt = IPPROTO_TCP;
626                 ip6->ip6_plen = htons((u_short)(sizeof(struct tcphdr) + tlen));
627                 tlen += sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
628         } else {
629                 tlen += sizeof(struct tcpiphdr);
630                 ip->ip_len = tlen;
631                 ip->ip_ttl = ip_defttl;
632         }
633         m->m_len = tlen;
634         m->m_pkthdr.len = tlen;
635         m->m_pkthdr.rcvif = (struct ifnet *) NULL;
636         nth->th_seq = htonl(seq);
637         nth->th_ack = htonl(ack);
638         nth->th_x2 = 0;
639         nth->th_off = sizeof(struct tcphdr) >> 2;
640         nth->th_flags = flags;
641         if (tp != NULL)
642                 nth->th_win = htons((u_short) (win >> tp->rcv_scale));
643         else
644                 nth->th_win = htons((u_short)win);
645         nth->th_urp = 0;
646         if (isipv6) {
647                 nth->th_sum = 0;
648                 nth->th_sum = in6_cksum(m, IPPROTO_TCP,
649                                         sizeof(struct ip6_hdr),
650                                         tlen - sizeof(struct ip6_hdr));
651                 ip6->ip6_hlim = in6_selecthlim(tp ? tp->t_inpcb : NULL,
652                                                (ro6 && ro6->ro_rt) ?
653                                                 ro6->ro_rt->rt_ifp : NULL);
654         } else {
655                 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
656                     htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
657                 m->m_pkthdr.csum_flags = CSUM_TCP;
658                 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
659         }
660 #ifdef TCPDEBUG
661         if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
662                 tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
663 #endif
664         if (isipv6) {
665                 ip6_output(m, NULL, ro6, ipflags, NULL, NULL,
666                            tp ? tp->t_inpcb : NULL);
667                 if ((ro6 == &sro6) && (ro6->ro_rt != NULL)) {
668                         RTFREE(ro6->ro_rt);
669                         ro6->ro_rt = NULL;
670                 }
671         } else {
672                 ip_output(m, NULL, ro, ipflags, NULL, tp ? tp->t_inpcb : NULL);
673                 if ((ro == &sro) && (ro->ro_rt != NULL)) {
674                         RTFREE(ro->ro_rt);
675                         ro->ro_rt = NULL;
676                 }
677         }
678 }
679
680 /*
681  * Create a new TCP control block, making an
682  * empty reassembly queue and hooking it to the argument
683  * protocol control block.  The `inp' parameter must have
684  * come from the zone allocator set up in tcp_init().
685  */
686 struct tcpcb *
687 tcp_newtcpcb(struct inpcb *inp)
688 {
689         struct inp_tp *it;
690         struct tcpcb *tp;
691 #ifdef INET6
692         boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) != 0);
693 #else
694         const boolean_t isipv6 = FALSE;
695 #endif
696
697         it = (struct inp_tp *)inp;
698         tp = &it->tcb;
699         bzero(tp, sizeof(struct tcpcb));
700         LIST_INIT(&tp->t_segq);
701         tp->t_maxseg = tp->t_maxopd = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
702
703         /* Set up our timeouts. */
704         callout_init(tp->tt_rexmt = &it->inp_tp_rexmt);
705         callout_init(tp->tt_persist = &it->inp_tp_persist);
706         callout_init(tp->tt_keep = &it->inp_tp_keep);
707         callout_init(tp->tt_2msl = &it->inp_tp_2msl);
708         callout_init(tp->tt_delack = &it->inp_tp_delack);
709
710         tp->tt_msg = &it->inp_tp_timermsg;
711         if (isipv6) {
712                 /* Don't mess with IPv6; always create timer message */
713                 tcp_create_timermsg(tp);
714         } else {
715                 /*
716                  * Zero out timer message.  We don't create it here,
717                  * since the current CPU may not be the owner of this
718                  * inpcb.
719                  */
720                 bzero(tp->tt_msg, sizeof(*tp->tt_msg));
721         }
722
723         if (tcp_do_rfc1323)
724                 tp->t_flags = (TF_REQ_SCALE | TF_REQ_TSTMP);
725         if (tcp_do_rfc1644)
726                 tp->t_flags |= TF_REQ_CC;
727         tp->t_inpcb = inp;      /* XXX */
728         tp->t_state = TCPS_CLOSED;
729         /*
730          * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
731          * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
732          * reasonable initial retransmit time.
733          */
734         tp->t_srtt = TCPTV_SRTTBASE;
735         tp->t_rttvar =
736             ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
737         tp->t_rttmin = tcp_rexmit_min;
738         tp->t_rxtcur = TCPTV_RTOBASE;
739         tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
740         tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
741         tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
742         tp->t_rcvtime = ticks;
743         /*
744          * IPv4 TTL initialization is necessary for an IPv6 socket as well,
745          * because the socket may be bound to an IPv6 wildcard address,
746          * which may match an IPv4-mapped IPv6 address.
747          */
748         inp->inp_ip_ttl = ip_defttl;
749         inp->inp_ppcb = tp;
750         tcp_sack_tcpcb_init(tp);
751         return (tp);            /* XXX */
752 }
753
754 /*
755  * Drop a TCP connection, reporting the specified error.
756  * If connection is synchronized, then send a RST to peer.
757  */
758 struct tcpcb *
759 tcp_drop(struct tcpcb *tp, int error)
760 {
761         struct socket *so = tp->t_inpcb->inp_socket;
762
763         if (TCPS_HAVERCVDSYN(tp->t_state)) {
764                 tp->t_state = TCPS_CLOSED;
765                 tcp_output(tp);
766                 tcpstat.tcps_drops++;
767         } else
768                 tcpstat.tcps_conndrops++;
769         if (error == ETIMEDOUT && tp->t_softerror)
770                 error = tp->t_softerror;
771         so->so_error = error;
772         return (tcp_close(tp));
773 }
774
775 #ifdef SMP
776
777 struct netmsg_remwildcard {
778         struct netmsg           nm_netmsg;
779         struct inpcb            *nm_inp;
780         struct inpcbinfo        *nm_pcbinfo;
781 #if defined(INET6)
782         int                     nm_isinet6;
783 #else
784         int                     nm_unused01;
785 #endif
786 };
787
788 /*
789  * Wildcard inpcb's on SMP boxes must be removed from all cpus before the
790  * inp can be detached.  We do this by cycling through the cpus, ending up
791  * on the cpu controlling the inp last and then doing the disconnect.
792  */
793 static void
794 in_pcbremwildcardhash_handler(struct netmsg *msg0)
795 {
796         struct netmsg_remwildcard *msg = (struct netmsg_remwildcard *)msg0;
797         int cpu;
798
799         cpu = msg->nm_pcbinfo->cpu;
800
801         if (cpu == msg->nm_inp->inp_pcbinfo->cpu) {
802                 /* note: detach removes any wildcard hash entry */
803 #ifdef INET6
804                 if (msg->nm_isinet6)
805                         in6_pcbdetach(msg->nm_inp);
806                 else
807 #endif
808                         in_pcbdetach(msg->nm_inp);
809                 lwkt_replymsg(&msg->nm_netmsg.nm_lmsg, 0);
810         } else {
811                 in_pcbremwildcardhash_oncpu(msg->nm_inp, msg->nm_pcbinfo);
812                 cpu = (cpu + 1) % ncpus2;
813                 msg->nm_pcbinfo = &tcbinfo[cpu];
814                 lwkt_forwardmsg(tcp_cport(cpu), &msg->nm_netmsg.nm_lmsg);
815         }
816 }
817
818 #endif
819
820 /*
821  * Close a TCP control block:
822  *      discard all space held by the tcp
823  *      discard internet protocol block
824  *      wake up any sleepers
825  */
826 struct tcpcb *
827 tcp_close(struct tcpcb *tp)
828 {
829         struct tseg_qent *q;
830         struct inpcb *inp = tp->t_inpcb;
831         struct socket *so = inp->inp_socket;
832         struct rtentry *rt;
833         boolean_t dosavessthresh;
834 #ifdef SMP
835         int cpu;
836 #endif
837 #ifdef INET6
838         boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) != 0);
839         boolean_t isafinet6 = (INP_CHECK_SOCKAF(so, AF_INET6) != 0);
840 #else
841         const boolean_t isipv6 = FALSE;
842 #endif
843
844         /*
845          * The tp is not instantly destroyed in the wildcard case.  Setting
846          * the state to TCPS_TERMINATING will prevent the TCP stack from
847          * messing with it, though it should be noted that this change may
848          * not take effect on other cpus until we have chained the wildcard
849          * hash removal.
850          *
851          * XXX we currently depend on the BGL to synchronize the tp->t_state
852          * update and prevent other tcp protocol threads from accepting new
853          * connections on the listen socket we might be trying to close down.
854          */
855         KKASSERT(tp->t_state != TCPS_TERMINATING);
856         tp->t_state = TCPS_TERMINATING;
857
858         /*
859          * Make sure that all of our timers are stopped before we
860          * delete the PCB.
861          */
862         callout_stop(tp->tt_rexmt);
863         callout_stop(tp->tt_persist);
864         callout_stop(tp->tt_keep);
865         callout_stop(tp->tt_2msl);
866         callout_stop(tp->tt_delack);
867
868         if (tp->t_flags & TF_ONOUTPUTQ) {
869                 KKASSERT(tp->tt_cpu == mycpu->gd_cpuid);
870                 TAILQ_REMOVE(&tcpcbackq[tp->tt_cpu], tp, t_outputq);
871                 tp->t_flags &= ~TF_ONOUTPUTQ;
872         }
873
874         /*
875          * If we got enough samples through the srtt filter,
876          * save the rtt and rttvar in the routing entry.
877          * 'Enough' is arbitrarily defined as the 16 samples.
878          * 16 samples is enough for the srtt filter to converge
879          * to within 5% of the correct value; fewer samples and
880          * we could save a very bogus rtt.
881          *
882          * Don't update the default route's characteristics and don't
883          * update anything that the user "locked".
884          */
885         if (tp->t_rttupdated >= 16) {
886                 u_long i = 0;
887
888                 if (isipv6) {
889                         struct sockaddr_in6 *sin6;
890
891                         if ((rt = inp->in6p_route.ro_rt) == NULL)
892                                 goto no_valid_rt;
893                         sin6 = (struct sockaddr_in6 *)rt_key(rt);
894                         if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
895                                 goto no_valid_rt;
896                 } else
897                         if ((rt = inp->inp_route.ro_rt) == NULL ||
898                             ((struct sockaddr_in *)rt_key(rt))->
899                              sin_addr.s_addr == INADDR_ANY)
900                                 goto no_valid_rt;
901
902                 if (!(rt->rt_rmx.rmx_locks & RTV_RTT)) {
903                         i = tp->t_srtt * (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
904                         if (rt->rt_rmx.rmx_rtt && i)
905                                 /*
906                                  * filter this update to half the old & half
907                                  * the new values, converting scale.
908                                  * See route.h and tcp_var.h for a
909                                  * description of the scaling constants.
910                                  */
911                                 rt->rt_rmx.rmx_rtt =
912                                     (rt->rt_rmx.rmx_rtt + i) / 2;
913                         else
914                                 rt->rt_rmx.rmx_rtt = i;
915                         tcpstat.tcps_cachedrtt++;
916                 }
917                 if (!(rt->rt_rmx.rmx_locks & RTV_RTTVAR)) {
918                         i = tp->t_rttvar *
919                             (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
920                         if (rt->rt_rmx.rmx_rttvar && i)
921                                 rt->rt_rmx.rmx_rttvar =
922                                     (rt->rt_rmx.rmx_rttvar + i) / 2;
923                         else
924                                 rt->rt_rmx.rmx_rttvar = i;
925                         tcpstat.tcps_cachedrttvar++;
926                 }
927                 /*
928                  * The old comment here said:
929                  * update the pipelimit (ssthresh) if it has been updated
930                  * already or if a pipesize was specified & the threshhold
931                  * got below half the pipesize.  I.e., wait for bad news
932                  * before we start updating, then update on both good
933                  * and bad news.
934                  *
935                  * But we want to save the ssthresh even if no pipesize is
936                  * specified explicitly in the route, because such
937                  * connections still have an implicit pipesize specified
938                  * by the global tcp_sendspace.  In the absence of a reliable
939                  * way to calculate the pipesize, it will have to do.
940                  */
941                 i = tp->snd_ssthresh;
942                 if (rt->rt_rmx.rmx_sendpipe != 0)
943                         dosavessthresh = (i < rt->rt_rmx.rmx_sendpipe/2);
944                 else
945                         dosavessthresh = (i < so->so_snd.ssb_hiwat/2);
946                 if (dosavessthresh ||
947                     (!(rt->rt_rmx.rmx_locks & RTV_SSTHRESH) && (i != 0) &&
948                      (rt->rt_rmx.rmx_ssthresh != 0))) {
949                         /*
950                          * convert the limit from user data bytes to
951                          * packets then to packet data bytes.
952                          */
953                         i = (i + tp->t_maxseg / 2) / tp->t_maxseg;
954                         if (i < 2)
955                                 i = 2;
956                         i *= tp->t_maxseg +
957                              (isipv6 ?
958                               sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
959                               sizeof(struct tcpiphdr));
960                         if (rt->rt_rmx.rmx_ssthresh)
961                                 rt->rt_rmx.rmx_ssthresh =
962                                     (rt->rt_rmx.rmx_ssthresh + i) / 2;
963                         else
964                                 rt->rt_rmx.rmx_ssthresh = i;
965                         tcpstat.tcps_cachedssthresh++;
966                 }
967         }
968
969 no_valid_rt:
970         /* free the reassembly queue, if any */
971         while((q = LIST_FIRST(&tp->t_segq)) != NULL) {
972                 LIST_REMOVE(q, tqe_q);
973                 m_freem(q->tqe_m);
974                 FREE(q, M_TSEGQ);
975                 tcp_reass_qsize--;
976         }
977         /* throw away SACK blocks in scoreboard*/
978         if (TCP_DO_SACK(tp))
979                 tcp_sack_cleanup(&tp->scb);
980
981         inp->inp_ppcb = NULL;
982         soisdisconnected(so);
983
984         tcp_destroy_timermsg(tp);
985
986         /*
987          * Discard the inp.  In the SMP case a wildcard inp's hash (created
988          * by a listen socket or an INADDR_ANY udp socket) is replicated
989          * for each protocol thread and must be removed in the context of
990          * that thread.  This is accomplished by chaining the message
991          * through the cpus.
992          *
993          * If the inp is not wildcarded we simply detach, which will remove
994          * the any hashes still present for this inp.
995          */
996 #ifdef SMP
997         if (inp->inp_flags & INP_WILDCARD_MP) {
998                 struct netmsg_remwildcard *msg;
999
1000                 cpu = (inp->inp_pcbinfo->cpu + 1) % ncpus2;
1001                 msg = kmalloc(sizeof(struct netmsg_remwildcard),
1002                               M_LWKTMSG, M_INTWAIT);
1003                 netmsg_init(&msg->nm_netmsg, &netisr_afree_rport, 0,
1004                             in_pcbremwildcardhash_handler);
1005 #ifdef INET6
1006                 msg->nm_isinet6 = isafinet6;
1007 #endif
1008                 msg->nm_inp = inp;
1009                 msg->nm_pcbinfo = &tcbinfo[cpu];
1010                 lwkt_sendmsg(tcp_cport(cpu), &msg->nm_netmsg.nm_lmsg);
1011         } else
1012 #endif
1013         {
1014                 /* note: detach removes any wildcard hash entry */
1015 #ifdef INET6
1016                 if (isafinet6)
1017                         in6_pcbdetach(inp);
1018                 else
1019 #endif
1020                         in_pcbdetach(inp);
1021         }
1022         tcpstat.tcps_closed++;
1023         return (NULL);
1024 }
1025
1026 static __inline void
1027 tcp_drain_oncpu(struct inpcbhead *head)
1028 {
1029         struct inpcb *inpb;
1030         struct tcpcb *tcpb;
1031         struct tseg_qent *te;
1032
1033         LIST_FOREACH(inpb, head, inp_list) {
1034                 if (inpb->inp_flags & INP_PLACEMARKER)
1035                         continue;
1036                 if ((tcpb = intotcpcb(inpb))) {
1037                         while ((te = LIST_FIRST(&tcpb->t_segq)) != NULL) {
1038                                 LIST_REMOVE(te, tqe_q);
1039                                 m_freem(te->tqe_m);
1040                                 FREE(te, M_TSEGQ);
1041                                 tcp_reass_qsize--;
1042                         }
1043                 }
1044         }
1045 }
1046
1047 #ifdef SMP
1048 struct netmsg_tcp_drain {
1049         struct netmsg           nm_netmsg;
1050         struct inpcbhead        *nm_head;
1051 };
1052
1053 static void
1054 tcp_drain_handler(netmsg_t netmsg)
1055 {
1056         struct netmsg_tcp_drain *nm = (void *)netmsg;
1057
1058         tcp_drain_oncpu(nm->nm_head);
1059         lwkt_replymsg(&nm->nm_netmsg.nm_lmsg, 0);
1060 }
1061 #endif
1062
1063 void
1064 tcp_drain(void)
1065 {
1066 #ifdef SMP
1067         int cpu;
1068 #endif
1069
1070         if (!do_tcpdrain)
1071                 return;
1072
1073         /*
1074          * Walk the tcpbs, if existing, and flush the reassembly queue,
1075          * if there is one...
1076          * XXX: The "Net/3" implementation doesn't imply that the TCP
1077          *      reassembly queue should be flushed, but in a situation
1078          *      where we're really low on mbufs, this is potentially
1079          *      useful.
1080          */
1081 #ifdef SMP
1082         for (cpu = 0; cpu < ncpus2; cpu++) {
1083                 struct netmsg_tcp_drain *msg;
1084
1085                 if (cpu == mycpu->gd_cpuid) {
1086                         tcp_drain_oncpu(&tcbinfo[cpu].pcblisthead);
1087                 } else {
1088                         msg = kmalloc(sizeof(struct netmsg_tcp_drain),
1089                                     M_LWKTMSG, M_NOWAIT);
1090                         if (msg == NULL)
1091                                 continue;
1092                         netmsg_init(&msg->nm_netmsg, &netisr_afree_rport, 0,
1093                                     tcp_drain_handler);
1094                         msg->nm_head = &tcbinfo[cpu].pcblisthead;
1095                         lwkt_sendmsg(tcp_cport(cpu), &msg->nm_netmsg.nm_lmsg);
1096                 }
1097         }
1098 #else
1099         tcp_drain_oncpu(&tcbinfo[0].pcblisthead);
1100 #endif
1101 }
1102
1103 /*
1104  * Notify a tcp user of an asynchronous error;
1105  * store error as soft error, but wake up user
1106  * (for now, won't do anything until can select for soft error).
1107  *
1108  * Do not wake up user since there currently is no mechanism for
1109  * reporting soft errors (yet - a kqueue filter may be added).
1110  */
1111 static void
1112 tcp_notify(struct inpcb *inp, int error)
1113 {
1114         struct tcpcb *tp = intotcpcb(inp);
1115
1116         /*
1117          * Ignore some errors if we are hooked up.
1118          * If connection hasn't completed, has retransmitted several times,
1119          * and receives a second error, give up now.  This is better
1120          * than waiting a long time to establish a connection that
1121          * can never complete.
1122          */
1123         if (tp->t_state == TCPS_ESTABLISHED &&
1124              (error == EHOSTUNREACH || error == ENETUNREACH ||
1125               error == EHOSTDOWN)) {
1126                 return;
1127         } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
1128             tp->t_softerror)
1129                 tcp_drop(tp, error);
1130         else
1131                 tp->t_softerror = error;
1132 #if 0
1133         wakeup(&so->so_timeo);
1134         sorwakeup(so);
1135         sowwakeup(so);
1136 #endif
1137 }
1138
1139 static int
1140 tcp_pcblist(SYSCTL_HANDLER_ARGS)
1141 {
1142         int error, i, n;
1143         struct inpcb *marker;
1144         struct inpcb *inp;
1145         inp_gen_t gencnt;
1146         globaldata_t gd;
1147         int origcpu, ccpu;
1148
1149         error = 0;
1150         n = 0;
1151
1152         /*
1153          * The process of preparing the TCB list is too time-consuming and
1154          * resource-intensive to repeat twice on every request.
1155          */
1156         if (req->oldptr == NULL) {
1157                 for (ccpu = 0; ccpu < ncpus; ++ccpu) {
1158                         gd = globaldata_find(ccpu);
1159                         n += tcbinfo[gd->gd_cpuid].ipi_count;
1160                 }
1161                 req->oldidx = (n + n/8 + 10) * sizeof(struct xtcpcb);
1162                 return (0);
1163         }
1164
1165         if (req->newptr != NULL)
1166                 return (EPERM);
1167
1168         marker = kmalloc(sizeof(struct inpcb), M_TEMP, M_WAITOK|M_ZERO);
1169         marker->inp_flags |= INP_PLACEMARKER;
1170
1171         /*
1172          * OK, now we're committed to doing something.  Run the inpcb list
1173          * for each cpu in the system and construct the output.  Use a
1174          * list placemarker to deal with list changes occuring during
1175          * copyout blockages (but otherwise depend on being on the correct
1176          * cpu to avoid races).
1177          */
1178         origcpu = mycpu->gd_cpuid;
1179         for (ccpu = 1; ccpu <= ncpus && error == 0; ++ccpu) {
1180                 globaldata_t rgd;
1181                 caddr_t inp_ppcb;
1182                 struct xtcpcb xt;
1183                 int cpu_id;
1184
1185                 cpu_id = (origcpu + ccpu) % ncpus;
1186                 if ((smp_active_mask & (1 << cpu_id)) == 0)
1187                         continue;
1188                 rgd = globaldata_find(cpu_id);
1189                 lwkt_setcpu_self(rgd);
1190
1191                 gencnt = tcbinfo[cpu_id].ipi_gencnt;
1192                 n = tcbinfo[cpu_id].ipi_count;
1193
1194                 LIST_INSERT_HEAD(&tcbinfo[cpu_id].pcblisthead, marker, inp_list);
1195                 i = 0;
1196                 while ((inp = LIST_NEXT(marker, inp_list)) != NULL && i < n) {
1197                         /*
1198                          * process a snapshot of pcbs, ignoring placemarkers
1199                          * and using our own to allow SYSCTL_OUT to block.
1200                          */
1201                         LIST_REMOVE(marker, inp_list);
1202                         LIST_INSERT_AFTER(inp, marker, inp_list);
1203
1204                         if (inp->inp_flags & INP_PLACEMARKER)
1205                                 continue;
1206                         if (inp->inp_gencnt > gencnt)
1207                                 continue;
1208                         if (prison_xinpcb(req->td, inp))
1209                                 continue;
1210
1211                         xt.xt_len = sizeof xt;
1212                         bcopy(inp, &xt.xt_inp, sizeof *inp);
1213                         inp_ppcb = inp->inp_ppcb;
1214                         if (inp_ppcb != NULL)
1215                                 bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp);
1216                         else
1217                                 bzero(&xt.xt_tp, sizeof xt.xt_tp);
1218                         if (inp->inp_socket)
1219                                 sotoxsocket(inp->inp_socket, &xt.xt_socket);
1220                         if ((error = SYSCTL_OUT(req, &xt, sizeof xt)) != 0)
1221                                 break;
1222                         ++i;
1223                 }
1224                 LIST_REMOVE(marker, inp_list);
1225                 if (error == 0 && i < n) {
1226                         bzero(&xt, sizeof xt);
1227                         xt.xt_len = sizeof xt;
1228                         while (i < n) {
1229                                 error = SYSCTL_OUT(req, &xt, sizeof xt);
1230                                 if (error)
1231                                         break;
1232                                 ++i;
1233                         }
1234                 }
1235         }
1236
1237         /*
1238          * Make sure we are on the same cpu we were on originally, since
1239          * higher level callers expect this.  Also don't pollute caches with
1240          * migrated userland data by (eventually) returning to userland
1241          * on a different cpu.
1242          */
1243         lwkt_setcpu_self(globaldata_find(origcpu));
1244         kfree(marker, M_TEMP);
1245         return (error);
1246 }
1247
1248 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
1249             tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
1250
1251 static int
1252 tcp_getcred(SYSCTL_HANDLER_ARGS)
1253 {
1254         struct sockaddr_in addrs[2];
1255         struct inpcb *inp;
1256         int cpu;
1257         int error;
1258
1259         error = priv_check(req->td, PRIV_ROOT);
1260         if (error != 0)
1261                 return (error);
1262         error = SYSCTL_IN(req, addrs, sizeof addrs);
1263         if (error != 0)
1264                 return (error);
1265         crit_enter();
1266         cpu = tcp_addrcpu(addrs[1].sin_addr.s_addr, addrs[1].sin_port,
1267             addrs[0].sin_addr.s_addr, addrs[0].sin_port);
1268         inp = in_pcblookup_hash(&tcbinfo[cpu], addrs[1].sin_addr,
1269             addrs[1].sin_port, addrs[0].sin_addr, addrs[0].sin_port, 0, NULL);
1270         if (inp == NULL || inp->inp_socket == NULL) {
1271                 error = ENOENT;
1272                 goto out;
1273         }
1274         error = SYSCTL_OUT(req, inp->inp_socket->so_cred, sizeof(struct ucred));
1275 out:
1276         crit_exit();
1277         return (error);
1278 }
1279
1280 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred, (CTLTYPE_OPAQUE | CTLFLAG_RW),
1281     0, 0, tcp_getcred, "S,ucred", "Get the ucred of a TCP connection");
1282
1283 #ifdef INET6
1284 static int
1285 tcp6_getcred(SYSCTL_HANDLER_ARGS)
1286 {
1287         struct sockaddr_in6 addrs[2];
1288         struct inpcb *inp;
1289         int error;
1290         boolean_t mapped = FALSE;
1291
1292         error = priv_check(req->td, PRIV_ROOT);
1293         if (error != 0)
1294                 return (error);
1295         error = SYSCTL_IN(req, addrs, sizeof addrs);
1296         if (error != 0)
1297                 return (error);
1298         if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
1299                 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
1300                         mapped = TRUE;
1301                 else
1302                         return (EINVAL);
1303         }
1304         crit_enter();
1305         if (mapped) {
1306                 inp = in_pcblookup_hash(&tcbinfo[0],
1307                     *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
1308                     addrs[1].sin6_port,
1309                     *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
1310                     addrs[0].sin6_port,
1311                     0, NULL);
1312         } else {
1313                 inp = in6_pcblookup_hash(&tcbinfo[0],
1314                     &addrs[1].sin6_addr, addrs[1].sin6_port,
1315                     &addrs[0].sin6_addr, addrs[0].sin6_port,
1316                     0, NULL);
1317         }
1318         if (inp == NULL || inp->inp_socket == NULL) {
1319                 error = ENOENT;
1320                 goto out;
1321         }
1322         error = SYSCTL_OUT(req, inp->inp_socket->so_cred, sizeof(struct ucred));
1323 out:
1324         crit_exit();
1325         return (error);
1326 }
1327
1328 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred, (CTLTYPE_OPAQUE | CTLFLAG_RW),
1329             0, 0,
1330             tcp6_getcred, "S,ucred", "Get the ucred of a TCP6 connection");
1331 #endif
1332
1333 struct netmsg_tcp_notify {
1334         struct netmsg   nm_nmsg;
1335         void            (*nm_notify)(struct inpcb *, int);
1336         struct in_addr  nm_faddr;
1337         int             nm_arg;
1338 };
1339
1340 static void
1341 tcp_notifyall_oncpu(struct netmsg *netmsg)
1342 {
1343         struct netmsg_tcp_notify *nmsg = (struct netmsg_tcp_notify *)netmsg;
1344         int nextcpu;
1345
1346         in_pcbnotifyall(&tcbinfo[mycpuid].pcblisthead, nmsg->nm_faddr,
1347                         nmsg->nm_arg, nmsg->nm_notify);
1348
1349         nextcpu = mycpuid + 1;
1350         if (nextcpu < ncpus2)
1351                 lwkt_forwardmsg(tcp_cport(nextcpu), &netmsg->nm_lmsg);
1352         else
1353                 lwkt_replymsg(&netmsg->nm_lmsg, 0);
1354 }
1355
1356 void
1357 tcp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
1358 {
1359         struct ip *ip = vip;
1360         struct tcphdr *th;
1361         struct in_addr faddr;
1362         struct inpcb *inp;
1363         struct tcpcb *tp;
1364         void (*notify)(struct inpcb *, int) = tcp_notify;
1365         tcp_seq icmpseq;
1366         int arg, cpu;
1367
1368         if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0) {
1369                 return;
1370         }
1371
1372         faddr = ((struct sockaddr_in *)sa)->sin_addr;
1373         if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
1374                 return;
1375
1376         arg = inetctlerrmap[cmd];
1377         if (cmd == PRC_QUENCH) {
1378                 notify = tcp_quench;
1379         } else if (icmp_may_rst &&
1380                    (cmd == PRC_UNREACH_ADMIN_PROHIB ||
1381                     cmd == PRC_UNREACH_PORT ||
1382                     cmd == PRC_TIMXCEED_INTRANS) &&
1383                    ip != NULL) {
1384                 notify = tcp_drop_syn_sent;
1385         } else if (cmd == PRC_MSGSIZE) {
1386                 struct icmp *icmp = (struct icmp *)
1387                     ((caddr_t)ip - offsetof(struct icmp, icmp_ip));
1388
1389                 arg = ntohs(icmp->icmp_nextmtu);
1390                 notify = tcp_mtudisc;
1391         } else if (PRC_IS_REDIRECT(cmd)) {
1392                 ip = NULL;
1393                 notify = in_rtchange;
1394         } else if (cmd == PRC_HOSTDEAD) {
1395                 ip = NULL;
1396         }
1397
1398         if (ip != NULL) {
1399                 crit_enter();
1400                 th = (struct tcphdr *)((caddr_t)ip +
1401                                        (IP_VHL_HL(ip->ip_vhl) << 2));
1402                 cpu = tcp_addrcpu(faddr.s_addr, th->th_dport,
1403                                   ip->ip_src.s_addr, th->th_sport);
1404                 inp = in_pcblookup_hash(&tcbinfo[cpu], faddr, th->th_dport,
1405                                         ip->ip_src, th->th_sport, 0, NULL);
1406                 if ((inp != NULL) && (inp->inp_socket != NULL)) {
1407                         icmpseq = htonl(th->th_seq);
1408                         tp = intotcpcb(inp);
1409                         if (SEQ_GEQ(icmpseq, tp->snd_una) &&
1410                             SEQ_LT(icmpseq, tp->snd_max))
1411                                 (*notify)(inp, arg);
1412                 } else {
1413                         struct in_conninfo inc;
1414
1415                         inc.inc_fport = th->th_dport;
1416                         inc.inc_lport = th->th_sport;
1417                         inc.inc_faddr = faddr;
1418                         inc.inc_laddr = ip->ip_src;
1419 #ifdef INET6
1420                         inc.inc_isipv6 = 0;
1421 #endif
1422                         syncache_unreach(&inc, th);
1423                 }
1424                 crit_exit();
1425         } else {
1426                 struct netmsg_tcp_notify nmsg;
1427
1428                 KKASSERT(&curthread->td_msgport == cpu_portfn(0));
1429                 netmsg_init(&nmsg.nm_nmsg, &curthread->td_msgport, 0,
1430                             tcp_notifyall_oncpu);
1431                 nmsg.nm_faddr = faddr;
1432                 nmsg.nm_arg = arg;
1433                 nmsg.nm_notify = notify;
1434
1435                 lwkt_domsg(tcp_cport(0), &nmsg.nm_nmsg.nm_lmsg, 0);
1436         }
1437 }
1438
1439 #ifdef INET6
1440 void
1441 tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
1442 {
1443         struct tcphdr th;
1444         void (*notify) (struct inpcb *, int) = tcp_notify;
1445         struct ip6_hdr *ip6;
1446         struct mbuf *m;
1447         struct ip6ctlparam *ip6cp = NULL;
1448         const struct sockaddr_in6 *sa6_src = NULL;
1449         int off;
1450         struct tcp_portonly {
1451                 u_int16_t th_sport;
1452                 u_int16_t th_dport;
1453         } *thp;
1454         int arg;
1455
1456         if (sa->sa_family != AF_INET6 ||
1457             sa->sa_len != sizeof(struct sockaddr_in6))
1458                 return;
1459
1460         arg = 0;
1461         if (cmd == PRC_QUENCH)
1462                 notify = tcp_quench;
1463         else if (cmd == PRC_MSGSIZE) {
1464                 struct ip6ctlparam *ip6cp = d;
1465                 struct icmp6_hdr *icmp6 = ip6cp->ip6c_icmp6;
1466
1467                 arg = ntohl(icmp6->icmp6_mtu);
1468                 notify = tcp_mtudisc;
1469         } else if (!PRC_IS_REDIRECT(cmd) &&
1470                  ((unsigned)cmd > PRC_NCMDS || inet6ctlerrmap[cmd] == 0)) {
1471                 return;
1472         }
1473
1474         /* if the parameter is from icmp6, decode it. */
1475         if (d != NULL) {
1476                 ip6cp = (struct ip6ctlparam *)d;
1477                 m = ip6cp->ip6c_m;
1478                 ip6 = ip6cp->ip6c_ip6;
1479                 off = ip6cp->ip6c_off;
1480                 sa6_src = ip6cp->ip6c_src;
1481         } else {
1482                 m = NULL;
1483                 ip6 = NULL;
1484                 off = 0;        /* fool gcc */
1485                 sa6_src = &sa6_any;
1486         }
1487
1488         if (ip6 != NULL) {
1489                 struct in_conninfo inc;
1490                 /*
1491                  * XXX: We assume that when IPV6 is non NULL,
1492                  * M and OFF are valid.
1493                  */
1494
1495                 /* check if we can safely examine src and dst ports */
1496                 if (m->m_pkthdr.len < off + sizeof *thp)
1497                         return;
1498
1499                 bzero(&th, sizeof th);
1500                 m_copydata(m, off, sizeof *thp, (caddr_t)&th);
1501
1502                 in6_pcbnotify(&tcbinfo[0].pcblisthead, sa, th.th_dport,
1503                     (struct sockaddr *)ip6cp->ip6c_src,
1504                     th.th_sport, cmd, arg, notify);
1505
1506                 inc.inc_fport = th.th_dport;
1507                 inc.inc_lport = th.th_sport;
1508                 inc.inc6_faddr = ((struct sockaddr_in6 *)sa)->sin6_addr;
1509                 inc.inc6_laddr = ip6cp->ip6c_src->sin6_addr;
1510                 inc.inc_isipv6 = 1;
1511                 syncache_unreach(&inc, &th);
1512         } else
1513                 in6_pcbnotify(&tcbinfo[0].pcblisthead, sa, 0,
1514                     (const struct sockaddr *)sa6_src, 0, cmd, arg, notify);
1515 }
1516 #endif
1517
1518 /*
1519  * Following is where TCP initial sequence number generation occurs.
1520  *
1521  * There are two places where we must use initial sequence numbers:
1522  * 1.  In SYN-ACK packets.
1523  * 2.  In SYN packets.
1524  *
1525  * All ISNs for SYN-ACK packets are generated by the syncache.  See
1526  * tcp_syncache.c for details.
1527  *
1528  * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
1529  * depends on this property.  In addition, these ISNs should be
1530  * unguessable so as to prevent connection hijacking.  To satisfy
1531  * the requirements of this situation, the algorithm outlined in
1532  * RFC 1948 is used to generate sequence numbers.
1533  *
1534  * Implementation details:
1535  *
1536  * Time is based off the system timer, and is corrected so that it
1537  * increases by one megabyte per second.  This allows for proper
1538  * recycling on high speed LANs while still leaving over an hour
1539  * before rollover.
1540  *
1541  * net.inet.tcp.isn_reseed_interval controls the number of seconds
1542  * between seeding of isn_secret.  This is normally set to zero,
1543  * as reseeding should not be necessary.
1544  *
1545  */
1546
1547 #define ISN_BYTES_PER_SECOND 1048576
1548
1549 u_char isn_secret[32];
1550 int isn_last_reseed;
1551 MD5_CTX isn_ctx;
1552
1553 tcp_seq
1554 tcp_new_isn(struct tcpcb *tp)
1555 {
1556         u_int32_t md5_buffer[4];
1557         tcp_seq new_isn;
1558
1559         /* Seed if this is the first use, reseed if requested. */
1560         if ((isn_last_reseed == 0) || ((tcp_isn_reseed_interval > 0) &&
1561              (((u_int)isn_last_reseed + (u_int)tcp_isn_reseed_interval*hz)
1562                 < (u_int)ticks))) {
1563                 read_random_unlimited(&isn_secret, sizeof isn_secret);
1564                 isn_last_reseed = ticks;
1565         }
1566
1567         /* Compute the md5 hash and return the ISN. */
1568         MD5Init(&isn_ctx);
1569         MD5Update(&isn_ctx, (u_char *)&tp->t_inpcb->inp_fport, sizeof(u_short));
1570         MD5Update(&isn_ctx, (u_char *)&tp->t_inpcb->inp_lport, sizeof(u_short));
1571 #ifdef INET6
1572         if (tp->t_inpcb->inp_vflag & INP_IPV6) {
1573                 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr,
1574                           sizeof(struct in6_addr));
1575                 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr,
1576                           sizeof(struct in6_addr));
1577         } else
1578 #endif
1579         {
1580                 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr,
1581                           sizeof(struct in_addr));
1582                 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr,
1583                           sizeof(struct in_addr));
1584         }
1585         MD5Update(&isn_ctx, (u_char *) &isn_secret, sizeof(isn_secret));
1586         MD5Final((u_char *) &md5_buffer, &isn_ctx);
1587         new_isn = (tcp_seq) md5_buffer[0];
1588         new_isn += ticks * (ISN_BYTES_PER_SECOND / hz);
1589         return (new_isn);
1590 }
1591
1592 /*
1593  * When a source quench is received, close congestion window
1594  * to one segment.  We will gradually open it again as we proceed.
1595  */
1596 void
1597 tcp_quench(struct inpcb *inp, int error)
1598 {
1599         struct tcpcb *tp = intotcpcb(inp);
1600
1601         if (tp != NULL) {
1602                 tp->snd_cwnd = tp->t_maxseg;
1603                 tp->snd_wacked = 0;
1604         }
1605 }
1606
1607 /*
1608  * When a specific ICMP unreachable message is received and the
1609  * connection state is SYN-SENT, drop the connection.  This behavior
1610  * is controlled by the icmp_may_rst sysctl.
1611  */
1612 void
1613 tcp_drop_syn_sent(struct inpcb *inp, int error)
1614 {
1615         struct tcpcb *tp = intotcpcb(inp);
1616
1617         if ((tp != NULL) && (tp->t_state == TCPS_SYN_SENT))
1618                 tcp_drop(tp, error);
1619 }
1620
1621 /*
1622  * When a `need fragmentation' ICMP is received, update our idea of the MSS
1623  * based on the new value in the route.  Also nudge TCP to send something,
1624  * since we know the packet we just sent was dropped.
1625  * This duplicates some code in the tcp_mss() function in tcp_input.c.
1626  */
1627 void
1628 tcp_mtudisc(struct inpcb *inp, int mtu)
1629 {
1630         struct tcpcb *tp = intotcpcb(inp);
1631         struct rtentry *rt;
1632         struct socket *so = inp->inp_socket;
1633         int maxopd, mss;
1634 #ifdef INET6
1635         boolean_t isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0);
1636 #else
1637         const boolean_t isipv6 = FALSE;
1638 #endif
1639
1640         if (tp == NULL)
1641                 return;
1642
1643         /*
1644          * If no MTU is provided in the ICMP message, use the
1645          * next lower likely value, as specified in RFC 1191.
1646          */
1647         if (mtu == 0) {
1648                 int oldmtu;
1649
1650                 oldmtu = tp->t_maxopd + 
1651                     (isipv6 ?
1652                      sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
1653                      sizeof(struct tcpiphdr));
1654                 mtu = ip_next_mtu(oldmtu, 0);
1655         }
1656
1657         if (isipv6)
1658                 rt = tcp_rtlookup6(&inp->inp_inc);
1659         else
1660                 rt = tcp_rtlookup(&inp->inp_inc);
1661         if (rt != NULL) {
1662                 struct rmxp_tao *taop = rmx_taop(rt->rt_rmx);
1663
1664                 if (rt->rt_rmx.rmx_mtu != 0 && rt->rt_rmx.rmx_mtu < mtu)
1665                         mtu = rt->rt_rmx.rmx_mtu;
1666
1667                 maxopd = mtu -
1668                     (isipv6 ?
1669                      sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
1670                      sizeof(struct tcpiphdr));
1671
1672                 /*
1673                  * XXX - The following conditional probably violates the TCP
1674                  * spec.  The problem is that, since we don't know the
1675                  * other end's MSS, we are supposed to use a conservative
1676                  * default.  But, if we do that, then MTU discovery will
1677                  * never actually take place, because the conservative
1678                  * default is much less than the MTUs typically seen
1679                  * on the Internet today.  For the moment, we'll sweep
1680                  * this under the carpet.
1681                  *
1682                  * The conservative default might not actually be a problem
1683                  * if the only case this occurs is when sending an initial
1684                  * SYN with options and data to a host we've never talked
1685                  * to before.  Then, they will reply with an MSS value which
1686                  * will get recorded and the new parameters should get
1687                  * recomputed.  For Further Study.
1688                  */
1689                 if (taop->tao_mssopt != 0 && taop->tao_mssopt < maxopd)
1690                         maxopd = taop->tao_mssopt;
1691         } else
1692                 maxopd = mtu -
1693                     (isipv6 ?
1694                      sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
1695                      sizeof(struct tcpiphdr));
1696
1697         if (tp->t_maxopd <= maxopd)
1698                 return;
1699         tp->t_maxopd = maxopd;
1700
1701         mss = maxopd;
1702         if ((tp->t_flags & (TF_REQ_TSTMP | TF_RCVD_TSTMP | TF_NOOPT)) ==
1703                            (TF_REQ_TSTMP | TF_RCVD_TSTMP))
1704                 mss -= TCPOLEN_TSTAMP_APPA;
1705
1706         if ((tp->t_flags & (TF_REQ_CC | TF_RCVD_CC | TF_NOOPT)) ==
1707                            (TF_REQ_CC | TF_RCVD_CC))
1708                 mss -= TCPOLEN_CC_APPA;
1709
1710         /* round down to multiple of MCLBYTES */
1711 #if     (MCLBYTES & (MCLBYTES - 1)) == 0    /* test if MCLBYTES power of 2 */
1712         if (mss > MCLBYTES)
1713                 mss &= ~(MCLBYTES - 1); 
1714 #else
1715         if (mss > MCLBYTES)
1716                 mss = (mss / MCLBYTES) * MCLBYTES;
1717 #endif
1718
1719         if (so->so_snd.ssb_hiwat < mss)
1720                 mss = so->so_snd.ssb_hiwat;
1721
1722         tp->t_maxseg = mss;
1723         tp->t_rtttime = 0;
1724         tp->snd_nxt = tp->snd_una;
1725         tcp_output(tp);
1726         tcpstat.tcps_mturesent++;
1727 }
1728
1729 /*
1730  * Look-up the routing entry to the peer of this inpcb.  If no route
1731  * is found and it cannot be allocated the return NULL.  This routine
1732  * is called by TCP routines that access the rmx structure and by tcp_mss
1733  * to get the interface MTU.
1734  */
1735 struct rtentry *
1736 tcp_rtlookup(struct in_conninfo *inc)
1737 {
1738         struct route *ro = &inc->inc_route;
1739
1740         if (ro->ro_rt == NULL || !(ro->ro_rt->rt_flags & RTF_UP)) {
1741                 /* No route yet, so try to acquire one */
1742                 if (inc->inc_faddr.s_addr != INADDR_ANY) {
1743                         /*
1744                          * unused portions of the structure MUST be zero'd
1745                          * out because rtalloc() treats it as opaque data
1746                          */
1747                         bzero(&ro->ro_dst, sizeof(struct sockaddr_in));
1748                         ro->ro_dst.sa_family = AF_INET;
1749                         ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
1750                         ((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
1751                             inc->inc_faddr;
1752                         rtalloc(ro);
1753                 }
1754         }
1755         return (ro->ro_rt);
1756 }
1757
1758 #ifdef INET6
1759 struct rtentry *
1760 tcp_rtlookup6(struct in_conninfo *inc)
1761 {
1762         struct route_in6 *ro6 = &inc->inc6_route;
1763
1764         if (ro6->ro_rt == NULL || !(ro6->ro_rt->rt_flags & RTF_UP)) {
1765                 /* No route yet, so try to acquire one */
1766                 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
1767                         /*
1768                          * unused portions of the structure MUST be zero'd
1769                          * out because rtalloc() treats it as opaque data
1770                          */
1771                         bzero(&ro6->ro_dst, sizeof(struct sockaddr_in6));
1772                         ro6->ro_dst.sin6_family = AF_INET6;
1773                         ro6->ro_dst.sin6_len = sizeof(struct sockaddr_in6);
1774                         ro6->ro_dst.sin6_addr = inc->inc6_faddr;
1775                         rtalloc((struct route *)ro6);
1776                 }
1777         }
1778         return (ro6->ro_rt);
1779 }
1780 #endif
1781
1782 #ifdef IPSEC
1783 /* compute ESP/AH header size for TCP, including outer IP header. */
1784 size_t
1785 ipsec_hdrsiz_tcp(struct tcpcb *tp)
1786 {
1787         struct inpcb *inp;
1788         struct mbuf *m;
1789         size_t hdrsiz;
1790         struct ip *ip;
1791         struct tcphdr *th;
1792
1793         if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL))
1794                 return (0);
1795         MGETHDR(m, MB_DONTWAIT, MT_DATA);
1796         if (!m)
1797                 return (0);
1798
1799 #ifdef INET6
1800         if (inp->inp_vflag & INP_IPV6) {
1801                 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1802
1803                 th = (struct tcphdr *)(ip6 + 1);
1804                 m->m_pkthdr.len = m->m_len =
1805                     sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1806                 tcp_fillheaders(tp, ip6, th);
1807                 hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1808         } else
1809 #endif
1810         {
1811                 ip = mtod(m, struct ip *);
1812                 th = (struct tcphdr *)(ip + 1);
1813                 m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
1814                 tcp_fillheaders(tp, ip, th);
1815                 hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1816         }
1817
1818         m_free(m);
1819         return (hdrsiz);
1820 }
1821 #endif
1822
1823 /*
1824  * Return a pointer to the cached information about the remote host.
1825  * The cached information is stored in the protocol specific part of
1826  * the route metrics.
1827  */
1828 struct rmxp_tao *
1829 tcp_gettaocache(struct in_conninfo *inc)
1830 {
1831         struct rtentry *rt;
1832
1833 #ifdef INET6
1834         if (inc->inc_isipv6)
1835                 rt = tcp_rtlookup6(inc);
1836         else
1837 #endif
1838                 rt = tcp_rtlookup(inc);
1839
1840         /* Make sure this is a host route and is up. */
1841         if (rt == NULL ||
1842             (rt->rt_flags & (RTF_UP | RTF_HOST)) != (RTF_UP | RTF_HOST))
1843                 return (NULL);
1844
1845         return (rmx_taop(rt->rt_rmx));
1846 }
1847
1848 /*
1849  * Clear all the TAO cache entries, called from tcp_init.
1850  *
1851  * XXX
1852  * This routine is just an empty one, because we assume that the routing
1853  * routing tables are initialized at the same time when TCP, so there is
1854  * nothing in the cache left over.
1855  */
1856 static void
1857 tcp_cleartaocache(void)
1858 {
1859 }
1860
1861 /*
1862  * TCP BANDWIDTH DELAY PRODUCT WINDOW LIMITING
1863  *
1864  * This code attempts to calculate the bandwidth-delay product as a
1865  * means of determining the optimal window size to maximize bandwidth,
1866  * minimize RTT, and avoid the over-allocation of buffers on interfaces and
1867  * routers.  This code also does a fairly good job keeping RTTs in check
1868  * across slow links like modems.  We implement an algorithm which is very
1869  * similar (but not meant to be) TCP/Vegas.  The code operates on the
1870  * transmitter side of a TCP connection and so only effects the transmit
1871  * side of the connection.
1872  *
1873  * BACKGROUND:  TCP makes no provision for the management of buffer space
1874  * at the end points or at the intermediate routers and switches.  A TCP
1875  * stream, whether using NewReno or not, will eventually buffer as
1876  * many packets as it is able and the only reason this typically works is
1877  * due to the fairly small default buffers made available for a connection
1878  * (typicaly 16K or 32K).  As machines use larger windows and/or window
1879  * scaling it is now fairly easy for even a single TCP connection to blow-out
1880  * all available buffer space not only on the local interface, but on
1881  * intermediate routers and switches as well.  NewReno makes a misguided
1882  * attempt to 'solve' this problem by waiting for an actual failure to occur,
1883  * then backing off, then steadily increasing the window again until another
1884  * failure occurs, ad-infinitum.  This results in terrible oscillation that
1885  * is only made worse as network loads increase and the idea of intentionally
1886  * blowing out network buffers is, frankly, a terrible way to manage network
1887  * resources.
1888  *
1889  * It is far better to limit the transmit window prior to the failure
1890  * condition being achieved.  There are two general ways to do this:  First
1891  * you can 'scan' through different transmit window sizes and locate the
1892  * point where the RTT stops increasing, indicating that you have filled the
1893  * pipe, then scan backwards until you note that RTT stops decreasing, then
1894  * repeat ad-infinitum.  This method works in principle but has severe
1895  * implementation issues due to RTT variances, timer granularity, and
1896  * instability in the algorithm which can lead to many false positives and
1897  * create oscillations as well as interact badly with other TCP streams
1898  * implementing the same algorithm.
1899  *
1900  * The second method is to limit the window to the bandwidth delay product
1901  * of the link.  This is the method we implement.  RTT variances and our
1902  * own manipulation of the congestion window, bwnd, can potentially
1903  * destabilize the algorithm.  For this reason we have to stabilize the
1904  * elements used to calculate the window.  We do this by using the minimum
1905  * observed RTT, the long term average of the observed bandwidth, and
1906  * by adding two segments worth of slop.  It isn't perfect but it is able
1907  * to react to changing conditions and gives us a very stable basis on
1908  * which to extend the algorithm.
1909  */
1910 void
1911 tcp_xmit_bandwidth_limit(struct tcpcb *tp, tcp_seq ack_seq)
1912 {
1913         u_long bw;
1914         u_long bwnd;
1915         int save_ticks;
1916         int delta_ticks;
1917
1918         /*
1919          * If inflight_enable is disabled in the middle of a tcp connection,
1920          * make sure snd_bwnd is effectively disabled.
1921          */
1922         if (!tcp_inflight_enable) {
1923                 tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
1924                 tp->snd_bandwidth = 0;
1925                 return;
1926         }
1927
1928         /*
1929          * Validate the delta time.  If a connection is new or has been idle
1930          * a long time we have to reset the bandwidth calculator.
1931          */
1932         save_ticks = ticks;
1933         delta_ticks = save_ticks - tp->t_bw_rtttime;
1934         if (tp->t_bw_rtttime == 0 || delta_ticks < 0 || delta_ticks > hz * 10) {
1935                 tp->t_bw_rtttime = ticks;
1936                 tp->t_bw_rtseq = ack_seq;
1937                 if (tp->snd_bandwidth == 0)
1938                         tp->snd_bandwidth = tcp_inflight_min;
1939                 return;
1940         }
1941         if (delta_ticks == 0)
1942                 return;
1943
1944         /*
1945          * Sanity check, plus ignore pure window update acks.
1946          */
1947         if ((int)(ack_seq - tp->t_bw_rtseq) <= 0)
1948                 return;
1949
1950         /*
1951          * Figure out the bandwidth.  Due to the tick granularity this
1952          * is a very rough number and it MUST be averaged over a fairly
1953          * long period of time.  XXX we need to take into account a link
1954          * that is not using all available bandwidth, but for now our
1955          * slop will ramp us up if this case occurs and the bandwidth later
1956          * increases.
1957          */
1958         bw = (int64_t)(ack_seq - tp->t_bw_rtseq) * hz / delta_ticks;
1959         tp->t_bw_rtttime = save_ticks;
1960         tp->t_bw_rtseq = ack_seq;
1961         bw = ((int64_t)tp->snd_bandwidth * 15 + bw) >> 4;
1962
1963         tp->snd_bandwidth = bw;
1964
1965         /*
1966          * Calculate the semi-static bandwidth delay product, plus two maximal
1967          * segments.  The additional slop puts us squarely in the sweet
1968          * spot and also handles the bandwidth run-up case.  Without the
1969          * slop we could be locking ourselves into a lower bandwidth.
1970          *
1971          * Situations Handled:
1972          *      (1) Prevents over-queueing of packets on LANs, especially on
1973          *          high speed LANs, allowing larger TCP buffers to be
1974          *          specified, and also does a good job preventing
1975          *          over-queueing of packets over choke points like modems
1976          *          (at least for the transmit side).
1977          *
1978          *      (2) Is able to handle changing network loads (bandwidth
1979          *          drops so bwnd drops, bandwidth increases so bwnd
1980          *          increases).
1981          *
1982          *      (3) Theoretically should stabilize in the face of multiple
1983          *          connections implementing the same algorithm (this may need
1984          *          a little work).
1985          *
1986          *      (4) Stability value (defaults to 20 = 2 maximal packets) can
1987          *          be adjusted with a sysctl but typically only needs to be on
1988          *          very slow connections.  A value no smaller then 5 should
1989          *          be used, but only reduce this default if you have no other
1990          *          choice.
1991          */
1992
1993 #define USERTT  ((tp->t_srtt + tp->t_rttbest) / 2)
1994         bwnd = (int64_t)bw * USERTT / (hz << TCP_RTT_SHIFT) +
1995                tcp_inflight_stab * (int)tp->t_maxseg / 10;
1996 #undef USERTT
1997
1998         if (tcp_inflight_debug > 0) {
1999                 static int ltime;
2000                 if ((u_int)(ticks - ltime) >= hz / tcp_inflight_debug) {
2001                         ltime = ticks;
2002                         kprintf("%p bw %ld rttbest %d srtt %d bwnd %ld\n",
2003                                 tp, bw, tp->t_rttbest, tp->t_srtt, bwnd);
2004                 }
2005         }
2006         if ((long)bwnd < tcp_inflight_min)
2007                 bwnd = tcp_inflight_min;
2008         if (bwnd > tcp_inflight_max)
2009                 bwnd = tcp_inflight_max;
2010         if ((long)bwnd < tp->t_maxseg * 2)
2011                 bwnd = tp->t_maxseg * 2;
2012         tp->snd_bwnd = bwnd;
2013 }