tcp_output.c revision 1.208.2.1 1 /* $NetBSD: tcp_output.c,v 1.208.2.1 2019/06/10 22:09:47 christos Exp $ */
2
3 /*
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the project nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 /*
33 * @(#)COPYRIGHT 1.1 (NRL) 17 January 1995
34 *
35 * NRL grants permission for redistribution and use in source and binary
36 * forms, with or without modification, of the software and documentation
37 * created at NRL provided that the following conditions are met:
38 *
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. All advertising materials mentioning features or use of this software
45 * must display the following acknowledgements:
46 * This product includes software developed by the University of
47 * California, Berkeley and its contributors.
48 * This product includes software developed at the Information
49 * Technology Division, US Naval Research Laboratory.
50 * 4. Neither the name of the NRL 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 * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
55 * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
56 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
57 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NRL OR
58 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
59 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
60 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
61 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
62 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
63 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
64 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
65 *
66 * The views and conclusions contained in the software and documentation
67 * are those of the authors and should not be interpreted as representing
68 * official policies, either expressed or implied, of the US Naval
69 * Research Laboratory (NRL).
70 */
71
72 /*-
73 * Copyright (c) 1997, 1998, 2001, 2005, 2006 The NetBSD Foundation, Inc.
74 * All rights reserved.
75 *
76 * This code is derived from software contributed to The NetBSD Foundation
77 * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
78 * Facility, NASA Ames Research Center.
79 * This code is derived from software contributed to The NetBSD Foundation
80 * by Charles M. Hannum.
81 * This code is derived from software contributed to The NetBSD Foundation
82 * by Rui Paulo.
83 *
84 * Redistribution and use in source and binary forms, with or without
85 * modification, are permitted provided that the following conditions
86 * are met:
87 * 1. Redistributions of source code must retain the above copyright
88 * notice, this list of conditions and the following disclaimer.
89 * 2. Redistributions in binary form must reproduce the above copyright
90 * notice, this list of conditions and the following disclaimer in the
91 * documentation and/or other materials provided with the distribution.
92 *
93 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
94 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
95 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
96 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
97 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
98 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
99 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
100 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
101 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
103 * POSSIBILITY OF SUCH DAMAGE.
104 */
105
106 /*
107 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
108 * The Regents of the University of California. All rights reserved.
109 *
110 * Redistribution and use in source and binary forms, with or without
111 * modification, are permitted provided that the following conditions
112 * are met:
113 * 1. Redistributions of source code must retain the above copyright
114 * notice, this list of conditions and the following disclaimer.
115 * 2. Redistributions in binary form must reproduce the above copyright
116 * notice, this list of conditions and the following disclaimer in the
117 * documentation and/or other materials provided with the distribution.
118 * 3. Neither the name of the University nor the names of its contributors
119 * may be used to endorse or promote products derived from this software
120 * without specific prior written permission.
121 *
122 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
123 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
124 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
125 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
126 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
127 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
128 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
129 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
130 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
131 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
132 * SUCH DAMAGE.
133 *
134 * @(#)tcp_output.c 8.4 (Berkeley) 5/24/95
135 */
136
137 #include <sys/cdefs.h>
138 __KERNEL_RCSID(0, "$NetBSD: tcp_output.c,v 1.208.2.1 2019/06/10 22:09:47 christos Exp $");
139
140 #ifdef _KERNEL_OPT
141 #include "opt_inet.h"
142 #include "opt_ipsec.h"
143 #include "opt_tcp_debug.h"
144 #endif
145
146 #include <sys/param.h>
147 #include <sys/systm.h>
148 #include <sys/mbuf.h>
149 #include <sys/protosw.h>
150 #include <sys/socket.h>
151 #include <sys/socketvar.h>
152 #include <sys/errno.h>
153 #include <sys/domain.h>
154 #include <sys/kernel.h>
155 #ifdef TCP_SIGNATURE
156 #include <sys/md5.h>
157 #endif
158
159 #include <net/if.h>
160 #include <net/route.h>
161
162 #include <netinet/in.h>
163 #include <netinet/in_systm.h>
164 #include <netinet/ip.h>
165 #include <netinet/in_pcb.h>
166 #include <netinet/ip_var.h>
167
168 #ifdef INET6
169 #include <netinet/ip6.h>
170 #include <netinet6/in6_var.h>
171 #include <netinet6/ip6_var.h>
172 #include <netinet6/in6_pcb.h>
173 #include <netinet6/nd6.h>
174 #endif
175
176 #ifdef IPSEC
177 #include <netipsec/ipsec.h>
178 #include <netipsec/key.h>
179 #ifdef INET6
180 #include <netipsec/ipsec6.h>
181 #endif
182 #endif
183
184 #include <netinet/tcp.h>
185 #define TCPOUTFLAGS
186 #include <netinet/tcp_fsm.h>
187 #include <netinet/tcp_seq.h>
188 #include <netinet/tcp_timer.h>
189 #include <netinet/tcp_var.h>
190 #include <netinet/tcp_private.h>
191 #include <netinet/tcp_congctl.h>
192 #include <netinet/tcp_debug.h>
193 #include <netinet/in_offload.h>
194 #include <netinet6/in6_offload.h>
195
196 /*
197 * Knob to enable Congestion Window Monitoring, and control
198 * the burst size it allows. Default burst is 4 packets, per
199 * the Internet draft.
200 */
201 int tcp_cwm = 0;
202 int tcp_cwm_burstsize = 4;
203
204 int tcp_do_autosndbuf = 1;
205 int tcp_autosndbuf_inc = 8 * 1024;
206 int tcp_autosndbuf_max = 256 * 1024;
207
208 #ifdef TCP_OUTPUT_COUNTERS
209 #include <sys/device.h>
210
211 extern struct evcnt tcp_output_bigheader;
212 extern struct evcnt tcp_output_predict_hit;
213 extern struct evcnt tcp_output_predict_miss;
214 extern struct evcnt tcp_output_copysmall;
215 extern struct evcnt tcp_output_copybig;
216 extern struct evcnt tcp_output_refbig;
217
218 #define TCP_OUTPUT_COUNTER_INCR(ev) (ev)->ev_count++
219 #else
220
221 #define TCP_OUTPUT_COUNTER_INCR(ev) /* nothing */
222
223 #endif /* TCP_OUTPUT_COUNTERS */
224
225 static int
226 tcp_segsize(struct tcpcb *tp, int *txsegsizep, int *rxsegsizep,
227 bool *alwaysfragp)
228 {
229 struct inpcb *inp = tp->t_inpcb;
230 #ifdef INET6
231 struct in6pcb *in6p = tp->t_in6pcb;
232 #endif
233 struct socket *so = NULL;
234 struct rtentry *rt;
235 struct ifnet *ifp;
236 int size;
237 int hdrlen;
238 int optlen;
239
240 *alwaysfragp = false;
241 size = tcp_mssdflt;
242
243 KASSERT(!(tp->t_inpcb && tp->t_in6pcb));
244
245 switch (tp->t_family) {
246 case AF_INET:
247 hdrlen = sizeof(struct ip) + sizeof(struct tcphdr);
248 break;
249 #ifdef INET6
250 case AF_INET6:
251 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
252 break;
253 #endif
254 default:
255 goto out;
256 }
257
258 rt = NULL;
259 if (inp) {
260 rt = in_pcbrtentry(inp);
261 so = inp->inp_socket;
262 }
263 #ifdef INET6
264 if (in6p) {
265 rt = in6_pcbrtentry(in6p);
266 so = in6p->in6p_socket;
267 }
268 #endif
269 if (rt == NULL) {
270 goto out;
271 }
272
273 ifp = rt->rt_ifp;
274
275 if (tp->t_mtudisc && rt->rt_rmx.rmx_mtu != 0) {
276 #ifdef INET6
277 if (in6p && rt->rt_rmx.rmx_mtu < IPV6_MMTU) {
278 /*
279 * RFC2460 section 5, last paragraph: if path MTU is
280 * smaller than 1280, use 1280 as packet size and
281 * attach fragment header.
282 */
283 size = IPV6_MMTU - hdrlen - sizeof(struct ip6_frag);
284 *alwaysfragp = true;
285 } else
286 size = rt->rt_rmx.rmx_mtu - hdrlen;
287 #else
288 size = rt->rt_rmx.rmx_mtu - hdrlen;
289 #endif
290 } else if (ifp->if_flags & IFF_LOOPBACK)
291 size = ifp->if_mtu - hdrlen;
292 else if (inp && tp->t_mtudisc)
293 size = ifp->if_mtu - hdrlen;
294 else if (inp && in_localaddr(inp->inp_faddr))
295 size = ifp->if_mtu - hdrlen;
296 #ifdef INET6
297 else if (in6p) {
298 if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr)) {
299 /* mapped addr case */
300 struct in_addr d;
301 memcpy(&d, &in6p->in6p_faddr.s6_addr32[3], sizeof(d));
302 if (tp->t_mtudisc || in_localaddr(d))
303 size = ifp->if_mtu - hdrlen;
304 } else {
305 /*
306 * for IPv6, path MTU discovery is always turned on,
307 * or the node must use packet size <= 1280.
308 */
309 size = tp->t_mtudisc ? IN6_LINKMTU(ifp) : IPV6_MMTU;
310 size -= hdrlen;
311 }
312 }
313 #endif
314 if (inp)
315 in_pcbrtentry_unref(rt, inp);
316 #ifdef INET6
317 if (in6p)
318 in6_pcbrtentry_unref(rt, in6p);
319 #endif
320 out:
321 /*
322 * Now we must make room for whatever extra TCP/IP options are in
323 * the packet.
324 */
325 optlen = tcp_optlen(tp);
326
327 /*
328 * XXX tp->t_ourmss should have the right size, but without this code
329 * fragmentation will occur... need more investigation
330 */
331
332 if (inp) {
333 #if defined(IPSEC)
334 if (ipsec_used &&
335 !ipsec_pcb_skip_ipsec(inp->inp_sp, IPSEC_DIR_OUTBOUND))
336 optlen += ipsec4_hdrsiz_tcp(tp);
337 #endif
338 optlen += ip_optlen(inp);
339 }
340
341 #ifdef INET6
342 if (in6p && tp->t_family == AF_INET) {
343 #if defined(IPSEC)
344 if (ipsec_used &&
345 !ipsec_pcb_skip_ipsec(in6p->in6p_sp, IPSEC_DIR_OUTBOUND))
346 optlen += ipsec4_hdrsiz_tcp(tp);
347 #endif
348 /* XXX size -= ip_optlen(in6p); */
349 } else if (in6p && tp->t_family == AF_INET6) {
350 #if defined(IPSEC)
351 if (ipsec_used &&
352 !ipsec_pcb_skip_ipsec(in6p->in6p_sp, IPSEC_DIR_OUTBOUND))
353 optlen += ipsec6_hdrsiz_tcp(tp);
354 #endif
355 optlen += ip6_optlen(in6p);
356 }
357 #endif
358 size -= optlen;
359
360 /*
361 * There may not be any room for data if mtu is too small. This
362 * includes zero-sized.
363 */
364 if (size <= 0) {
365 return EMSGSIZE;
366 }
367
368 /*
369 * *rxsegsizep holds *estimated* inbound segment size (estimation
370 * assumes that path MTU is the same for both ways). this is only
371 * for silly window avoidance, do not use the value for other purposes.
372 *
373 * ipseclen is subtracted from both sides, this may not be right.
374 * I'm not quite sure about this (could someone comment).
375 */
376 *txsegsizep = uimin(tp->t_peermss - optlen, size);
377 *rxsegsizep = uimin(tp->t_ourmss - optlen, size);
378
379 /*
380 * Never send more than half a buffer full. This insures that we can
381 * always keep 2 packets on the wire, no matter what SO_SNDBUF is, and
382 * therefore acks will never be delayed unless we run out of data to
383 * transmit.
384 */
385 if (so) {
386 *txsegsizep = uimin(so->so_snd.sb_hiwat >> 1, *txsegsizep);
387 }
388
389 if (*txsegsizep != tp->t_segsz) {
390 /*
391 * If the new segment size is larger, we don't want to
392 * mess up the congestion window, but if it is smaller
393 * we'll have to reduce the congestion window to ensure
394 * that we don't get into trouble with initial windows
395 * and the rest. In any case, if the segment size
396 * has changed, chances are the path has, too, and
397 * our congestion window will be different.
398 */
399 if (*txsegsizep < tp->t_segsz) {
400 tp->snd_cwnd = uimax((tp->snd_cwnd / tp->t_segsz)
401 * *txsegsizep, *txsegsizep);
402 tp->snd_ssthresh = uimax((tp->snd_ssthresh / tp->t_segsz)
403 * *txsegsizep, *txsegsizep);
404 }
405 tp->t_segsz = *txsegsizep;
406 }
407
408 return 0;
409 }
410
411 static int
412 tcp_build_datapkt(struct tcpcb *tp, struct socket *so, int off,
413 long len, int hdrlen, struct mbuf **mp)
414 {
415 struct mbuf *m, *m0;
416 uint64_t *tcps;
417
418 tcps = TCP_STAT_GETREF();
419 if (tp->t_force && len == 1)
420 tcps[TCP_STAT_SNDPROBE]++;
421 else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
422 tp->t_sndrexmitpack++;
423 tcps[TCP_STAT_SNDREXMITPACK]++;
424 tcps[TCP_STAT_SNDREXMITBYTE] += len;
425 } else {
426 tcps[TCP_STAT_SNDPACK]++;
427 tcps[TCP_STAT_SNDBYTE] += len;
428 }
429 TCP_STAT_PUTREF();
430
431 MGETHDR(m, M_DONTWAIT, MT_HEADER);
432 if (__predict_false(m == NULL))
433 return ENOBUFS;
434 MCLAIM(m, &tcp_tx_mowner);
435
436 /*
437 * XXX Because other code assumes headers will fit in
438 * XXX one header mbuf.
439 *
440 * (This code should almost *never* be run.)
441 */
442 if (__predict_false((max_linkhdr + hdrlen) > MHLEN)) {
443 TCP_OUTPUT_COUNTER_INCR(&tcp_output_bigheader);
444 MCLGET(m, M_DONTWAIT);
445 if ((m->m_flags & M_EXT) == 0) {
446 m_freem(m);
447 return ENOBUFS;
448 }
449 }
450
451 m->m_data += max_linkhdr;
452 m->m_len = hdrlen;
453
454 /*
455 * To avoid traversing the whole sb_mb chain for correct
456 * data to send, remember last sent mbuf, its offset and
457 * the sent size. When called the next time, see if the
458 * data to send is directly following the previous transfer.
459 * This is important for large TCP windows.
460 */
461 if (off == 0 || tp->t_lastm == NULL ||
462 (tp->t_lastoff + tp->t_lastlen) != off) {
463 TCP_OUTPUT_COUNTER_INCR(&tcp_output_predict_miss);
464 /*
465 * Either a new packet or a retransmit.
466 * Start from the beginning.
467 */
468 tp->t_lastm = so->so_snd.sb_mb;
469 tp->t_inoff = off;
470 } else {
471 TCP_OUTPUT_COUNTER_INCR(&tcp_output_predict_hit);
472 tp->t_inoff += tp->t_lastlen;
473 }
474
475 /* Traverse forward to next packet */
476 while (tp->t_inoff > 0) {
477 if (tp->t_lastm == NULL)
478 panic("tp->t_lastm == NULL");
479 if (tp->t_inoff < tp->t_lastm->m_len)
480 break;
481 tp->t_inoff -= tp->t_lastm->m_len;
482 tp->t_lastm = tp->t_lastm->m_next;
483 }
484
485 tp->t_lastoff = off;
486 tp->t_lastlen = len;
487 m0 = tp->t_lastm;
488 off = tp->t_inoff;
489
490 if (len <= M_TRAILINGSPACE(m)) {
491 m_copydata(m0, off, (int)len, mtod(m, char *) + hdrlen);
492 m->m_len += len;
493 TCP_OUTPUT_COUNTER_INCR(&tcp_output_copysmall);
494 } else {
495 m->m_next = m_copym(m0, off, (int)len, M_DONTWAIT);
496 if (m->m_next == NULL) {
497 m_freem(m);
498 return ENOBUFS;
499 }
500 #ifdef TCP_OUTPUT_COUNTERS
501 if (m->m_next->m_flags & M_EXT)
502 TCP_OUTPUT_COUNTER_INCR(&tcp_output_refbig);
503 else
504 TCP_OUTPUT_COUNTER_INCR(&tcp_output_copybig);
505 #endif
506 }
507
508 *mp = m;
509 return 0;
510 }
511
512 /*
513 * Tcp output routine: figure out what should be sent and send it.
514 */
515 int
516 tcp_output(struct tcpcb *tp)
517 {
518 struct rtentry *rt = NULL;
519 struct socket *so;
520 struct route *ro;
521 long len, win;
522 int off, flags, error;
523 struct mbuf *m;
524 struct ip *ip;
525 #ifdef INET6
526 struct ip6_hdr *ip6;
527 #endif
528 struct tcphdr *th;
529 u_char opt[MAX_TCPOPTLEN], *optp;
530 #define OPT_FITS(more) ((optlen + (more)) <= sizeof(opt))
531 unsigned optlen, hdrlen, packetlen;
532 unsigned int sack_numblks;
533 int idle, sendalot, txsegsize, rxsegsize;
534 int txsegsize_nosack;
535 int maxburst = TCP_MAXBURST;
536 int af; /* address family on the wire */
537 int iphdrlen;
538 int has_tso4, has_tso6;
539 int has_tso, use_tso;
540 bool alwaysfrag;
541 int sack_rxmit;
542 int sack_bytes_rxmt;
543 int ecn_tos;
544 struct sackhole *p;
545 #ifdef TCP_SIGNATURE
546 int sigoff = 0;
547 #endif
548 uint64_t *tcps;
549
550 KASSERT(!(tp->t_inpcb && tp->t_in6pcb));
551
552 so = NULL;
553 ro = NULL;
554 if (tp->t_inpcb) {
555 so = tp->t_inpcb->inp_socket;
556 ro = &tp->t_inpcb->inp_route;
557 }
558 #ifdef INET6
559 else if (tp->t_in6pcb) {
560 so = tp->t_in6pcb->in6p_socket;
561 ro = &tp->t_in6pcb->in6p_route;
562 }
563 #endif
564
565 switch (af = tp->t_family) {
566 case AF_INET:
567 if (tp->t_inpcb)
568 break;
569 #ifdef INET6
570 /* mapped addr case */
571 if (tp->t_in6pcb)
572 break;
573 #endif
574 return EINVAL;
575 #ifdef INET6
576 case AF_INET6:
577 if (tp->t_in6pcb)
578 break;
579 return EINVAL;
580 #endif
581 default:
582 return EAFNOSUPPORT;
583 }
584
585 if (tcp_segsize(tp, &txsegsize, &rxsegsize, &alwaysfrag))
586 return EMSGSIZE;
587
588 idle = (tp->snd_max == tp->snd_una);
589
590 /*
591 * Determine if we can use TCP segmentation offload:
592 * - If we're using IPv4
593 * - If there is not an IPsec policy that prevents it
594 * - If the interface can do it
595 */
596 has_tso4 = has_tso6 = false;
597
598 has_tso4 = tp->t_inpcb != NULL &&
599 #if defined(IPSEC)
600 (!ipsec_used || ipsec_pcb_skip_ipsec(tp->t_inpcb->inp_sp,
601 IPSEC_DIR_OUTBOUND)) &&
602 #endif
603 (rt = rtcache_validate(&tp->t_inpcb->inp_route)) != NULL &&
604 (rt->rt_ifp->if_capenable & IFCAP_TSOv4) != 0;
605 if (rt != NULL) {
606 rtcache_unref(rt, &tp->t_inpcb->inp_route);
607 rt = NULL;
608 }
609
610 #if defined(INET6)
611 has_tso6 = tp->t_in6pcb != NULL &&
612 #if defined(IPSEC)
613 (!ipsec_used || ipsec_pcb_skip_ipsec(tp->t_in6pcb->in6p_sp,
614 IPSEC_DIR_OUTBOUND)) &&
615 #endif
616 (rt = rtcache_validate(&tp->t_in6pcb->in6p_route)) != NULL &&
617 (rt->rt_ifp->if_capenable & IFCAP_TSOv6) != 0;
618 if (rt != NULL)
619 rtcache_unref(rt, &tp->t_in6pcb->in6p_route);
620 #endif /* defined(INET6) */
621 has_tso = (has_tso4 || has_tso6) && !alwaysfrag;
622
623 /*
624 * Restart Window computation. From draft-floyd-incr-init-win-03:
625 *
626 * Optionally, a TCP MAY set the restart window to the
627 * minimum of the value used for the initial window and
628 * the current value of cwnd (in other words, using a
629 * larger value for the restart window should never increase
630 * the size of cwnd).
631 */
632 if (tcp_cwm) {
633 /*
634 * Hughes/Touch/Heidemann Congestion Window Monitoring.
635 * Count the number of packets currently pending
636 * acknowledgement, and limit our congestion window
637 * to a pre-determined allowed burst size plus that count.
638 * This prevents bursting once all pending packets have
639 * been acknowledged (i.e. transmission is idle).
640 *
641 * XXX Link this to Initial Window?
642 */
643 tp->snd_cwnd = uimin(tp->snd_cwnd,
644 (tcp_cwm_burstsize * txsegsize) +
645 (tp->snd_nxt - tp->snd_una));
646 } else {
647 if (idle && (tcp_now - tp->t_rcvtime) >= tp->t_rxtcur) {
648 /*
649 * We have been idle for "a while" and no acks are
650 * expected to clock out any data we send --
651 * slow start to get ack "clock" running again.
652 */
653 int ss = tcp_init_win;
654 if (tp->t_inpcb &&
655 in_localaddr(tp->t_inpcb->inp_faddr))
656 ss = tcp_init_win_local;
657 #ifdef INET6
658 if (tp->t_in6pcb &&
659 in6_localaddr(&tp->t_in6pcb->in6p_faddr))
660 ss = tcp_init_win_local;
661 #endif
662 tp->snd_cwnd = uimin(tp->snd_cwnd,
663 TCP_INITIAL_WINDOW(ss, txsegsize));
664 }
665 }
666
667 txsegsize_nosack = txsegsize;
668 again:
669 ecn_tos = 0;
670 use_tso = has_tso;
671 if ((tp->t_flags & (TF_ECN_SND_CWR|TF_ECN_SND_ECE)) != 0) {
672 /* don't duplicate CWR/ECE. */
673 use_tso = 0;
674 }
675 TCP_REASS_LOCK(tp);
676 sack_numblks = tcp_sack_numblks(tp);
677 if (sack_numblks) {
678 int sackoptlen;
679
680 sackoptlen = TCP_SACK_OPTLEN(sack_numblks);
681 if (sackoptlen > txsegsize_nosack) {
682 sack_numblks = 0; /* give up SACK */
683 txsegsize = txsegsize_nosack;
684 } else {
685 if ((tp->rcv_sack_flags & TCPSACK_HAVED) != 0) {
686 /* don't duplicate D-SACK. */
687 use_tso = 0;
688 }
689 txsegsize = txsegsize_nosack - sackoptlen;
690 }
691 } else {
692 txsegsize = txsegsize_nosack;
693 }
694
695 /*
696 * Determine length of data that should be transmitted, and
697 * flags that should be used. If there is some data or critical
698 * controls (SYN, RST) to send, then transmit; otherwise,
699 * investigate further.
700 *
701 * Readjust SACK information to avoid resending duplicate data.
702 */
703 if (TCP_SACK_ENABLED(tp) && SEQ_LT(tp->snd_nxt, tp->snd_max))
704 tcp_sack_adjust(tp);
705 sendalot = 0;
706 off = tp->snd_nxt - tp->snd_una;
707 win = uimin(tp->snd_wnd, tp->snd_cwnd);
708
709 flags = tcp_outflags[tp->t_state];
710
711 /*
712 * Send any SACK-generated retransmissions. If we're explicitly trying
713 * to send out new data (when sendalot is 1), bypass this function.
714 * If we retransmit in fast recovery mode, decrement snd_cwnd, since
715 * we're replacing a (future) new transmission with a retransmission
716 * now, and we previously incremented snd_cwnd in tcp_input().
717 */
718 /*
719 * Still in sack recovery, reset rxmit flag to zero.
720 */
721 sack_rxmit = 0;
722 sack_bytes_rxmt = 0;
723 len = 0;
724 p = NULL;
725 do {
726 long cwin;
727 if (!TCP_SACK_ENABLED(tp))
728 break;
729 if (tp->t_partialacks < 0)
730 break;
731 p = tcp_sack_output(tp, &sack_bytes_rxmt);
732 if (p == NULL)
733 break;
734
735 cwin = uimin(tp->snd_wnd, tp->snd_cwnd) - sack_bytes_rxmt;
736 if (cwin < 0)
737 cwin = 0;
738 /* Do not retransmit SACK segments beyond snd_recover */
739 if (SEQ_GT(p->end, tp->snd_recover)) {
740 /*
741 * (At least) part of sack hole extends beyond
742 * snd_recover. Check to see if we can rexmit data
743 * for this hole.
744 */
745 if (SEQ_GEQ(p->rxmit, tp->snd_recover)) {
746 /*
747 * Can't rexmit any more data for this hole.
748 * That data will be rexmitted in the next
749 * sack recovery episode, when snd_recover
750 * moves past p->rxmit.
751 */
752 p = NULL;
753 break;
754 }
755 /* Can rexmit part of the current hole */
756 len = ((long)ulmin(cwin, tp->snd_recover - p->rxmit));
757 } else
758 len = ((long)ulmin(cwin, p->end - p->rxmit));
759 off = p->rxmit - tp->snd_una;
760 if (off + len > so->so_snd.sb_cc) {
761 /* 1 for TH_FIN */
762 KASSERT(off + len == so->so_snd.sb_cc + 1);
763 KASSERT(p->rxmit + len == tp->snd_max);
764 len = so->so_snd.sb_cc - off;
765 }
766 if (len > 0) {
767 sack_rxmit = 1;
768 sendalot = 1;
769 }
770 } while (/*CONSTCOND*/0);
771
772 /*
773 * If in persist timeout with window of 0, send 1 byte.
774 * Otherwise, if window is small but nonzero
775 * and timer expired, we will send what we can
776 * and go to transmit state.
777 */
778 if (tp->t_force) {
779 if (win == 0) {
780 /*
781 * If we still have some data to send, then
782 * clear the FIN bit. Usually this would
783 * happen below when it realizes that we
784 * aren't sending all the data. However,
785 * if we have exactly 1 byte of unset data,
786 * then it won't clear the FIN bit below,
787 * and if we are in persist state, we wind
788 * up sending the packet without recording
789 * that we sent the FIN bit.
790 *
791 * We can't just blindly clear the FIN bit,
792 * because if we don't have any more data
793 * to send then the probe will be the FIN
794 * itself.
795 */
796 if (off < so->so_snd.sb_cc)
797 flags &= ~TH_FIN;
798 win = 1;
799 } else {
800 TCP_TIMER_DISARM(tp, TCPT_PERSIST);
801 tp->t_rxtshift = 0;
802 }
803 }
804
805 if (sack_rxmit == 0) {
806 if (TCP_SACK_ENABLED(tp) && tp->t_partialacks >= 0) {
807 long cwin;
808
809 /*
810 * We are inside of a SACK recovery episode and are
811 * sending new data, having retransmitted all the
812 * data possible in the scoreboard.
813 */
814 if (tp->snd_wnd < so->so_snd.sb_cc) {
815 len = tp->snd_wnd - off;
816 flags &= ~TH_FIN;
817 } else {
818 len = so->so_snd.sb_cc - off;
819 }
820
821 /*
822 * From FreeBSD:
823 * Don't remove this (len > 0) check !
824 * We explicitly check for len > 0 here (although it
825 * isn't really necessary), to work around a gcc
826 * optimization issue - to force gcc to compute
827 * len above. Without this check, the computation
828 * of len is bungled by the optimizer.
829 */
830 if (len > 0) {
831 cwin = tp->snd_cwnd -
832 (tp->snd_nxt - tp->sack_newdata) -
833 sack_bytes_rxmt;
834 if (cwin < 0)
835 cwin = 0;
836 if (cwin < len) {
837 len = cwin;
838 flags &= ~TH_FIN;
839 }
840 }
841 } else if (win < so->so_snd.sb_cc) {
842 len = win - off;
843 flags &= ~TH_FIN;
844 } else {
845 len = so->so_snd.sb_cc - off;
846 }
847 }
848
849 if (len < 0) {
850 /*
851 * If FIN has been sent but not acked,
852 * but we haven't been called to retransmit,
853 * len will be -1. Otherwise, window shrank
854 * after we sent into it. If window shrank to 0,
855 * cancel pending retransmit, pull snd_nxt back
856 * to (closed) window, and set the persist timer
857 * if it isn't already going. If the window didn't
858 * close completely, just wait for an ACK.
859 *
860 * If we have a pending FIN, either it has already been
861 * transmitted or it is outside the window, so drop it.
862 * If the FIN has been transmitted, but this is not a
863 * retransmission, then len must be -1. Therefore we also
864 * prevent here the sending of `gratuitous FINs'. This
865 * eliminates the need to check for that case below (e.g.
866 * to back up snd_nxt before the FIN so that the sequence
867 * number is correct).
868 */
869 len = 0;
870 flags &= ~TH_FIN;
871 if (win == 0) {
872 TCP_TIMER_DISARM(tp, TCPT_REXMT);
873 tp->t_rxtshift = 0;
874 tp->snd_nxt = tp->snd_una;
875 if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
876 tcp_setpersist(tp);
877 }
878 }
879
880 /*
881 * Automatic sizing enables the performance of large buffers
882 * and most of the efficiency of small ones by only allocating
883 * space when it is needed.
884 *
885 * The criteria to step up the send buffer one notch are:
886 * 1. receive window of remote host is larger than send buffer
887 * (with a fudge factor of 5/4th);
888 * 2. send buffer is filled to 7/8th with data (so we actually
889 * have data to make use of it);
890 * 3. send buffer fill has not hit maximal automatic size;
891 * 4. our send window (slow start and cogestion controlled) is
892 * larger than sent but unacknowledged data in send buffer.
893 *
894 * The remote host receive window scaling factor may limit the
895 * growing of the send buffer before it reaches its allowed
896 * maximum.
897 *
898 * It scales directly with slow start or congestion window
899 * and does at most one step per received ACK. This fast
900 * scaling has the drawback of growing the send buffer beyond
901 * what is strictly necessary to make full use of a given
902 * delay*bandwith product. However testing has shown this not
903 * to be much of an problem. At worst we are trading wasting
904 * of available bandwith (the non-use of it) for wasting some
905 * socket buffer memory.
906 *
907 * TODO: Shrink send buffer during idle periods together
908 * with congestion window. Requires another timer.
909 */
910 if (tcp_do_autosndbuf && so->so_snd.sb_flags & SB_AUTOSIZE) {
911 if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat &&
912 so->so_snd.sb_cc >= (so->so_snd.sb_hiwat / 8 * 7) &&
913 so->so_snd.sb_cc < tcp_autosndbuf_max &&
914 win >= (so->so_snd.sb_cc - (tp->snd_nxt - tp->snd_una))) {
915 if (!sbreserve(&so->so_snd,
916 uimin(so->so_snd.sb_hiwat + tcp_autosndbuf_inc,
917 tcp_autosndbuf_max), so))
918 so->so_snd.sb_flags &= ~SB_AUTOSIZE;
919 }
920 }
921
922 if (len > txsegsize) {
923 if (use_tso) {
924 /*
925 * Truncate TSO transfers to IP_MAXPACKET, and make
926 * sure that we send equal size transfers down the
927 * stack (rather than big-small-big-small-...).
928 */
929 #ifdef INET6
930 CTASSERT(IPV6_MAXPACKET == IP_MAXPACKET);
931 #endif
932 len = (uimin(len, IP_MAXPACKET) / txsegsize) * txsegsize;
933 if (len <= txsegsize) {
934 use_tso = 0;
935 }
936 } else
937 len = txsegsize;
938 flags &= ~TH_FIN;
939 sendalot = 1;
940 } else
941 use_tso = 0;
942 if (sack_rxmit) {
943 if (SEQ_LT(p->rxmit + len, tp->snd_una + so->so_snd.sb_cc))
944 flags &= ~TH_FIN;
945 }
946
947 win = sbspace(&so->so_rcv);
948
949 /*
950 * Sender silly window avoidance. If connection is idle
951 * and can send all data, a maximum segment,
952 * at least a maximum default-size segment do it,
953 * or are forced, do it; otherwise don't bother.
954 * If peer's buffer is tiny, then send
955 * when window is at least half open.
956 * If retransmitting (possibly after persist timer forced us
957 * to send into a small window), then must resend.
958 */
959 if (len) {
960 if (len >= txsegsize)
961 goto send;
962 if ((so->so_state & SS_MORETOCOME) == 0 &&
963 ((idle || tp->t_flags & TF_NODELAY) &&
964 len + off >= so->so_snd.sb_cc))
965 goto send;
966 if (tp->t_force)
967 goto send;
968 if (len >= tp->max_sndwnd / 2)
969 goto send;
970 if (SEQ_LT(tp->snd_nxt, tp->snd_max))
971 goto send;
972 if (sack_rxmit)
973 goto send;
974 }
975
976 /*
977 * Compare available window to amount of window known to peer
978 * (as advertised window less next expected input). If the
979 * difference is at least twice the size of the largest segment
980 * we expect to receive (i.e. two segments) or at least 50% of
981 * the maximum possible window, then want to send a window update
982 * to peer.
983 */
984 if (win > 0) {
985 /*
986 * "adv" is the amount we can increase the window,
987 * taking into account that we are limited by
988 * TCP_MAXWIN << tp->rcv_scale.
989 */
990 long recwin = uimin(win, (long)TCP_MAXWIN << tp->rcv_scale);
991 long oldwin, adv;
992
993 /*
994 * rcv_nxt may overtake rcv_adv when we accept a
995 * zero-window probe.
996 */
997 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
998 oldwin = tp->rcv_adv - tp->rcv_nxt;
999 else
1000 oldwin = 0;
1001
1002 /*
1003 * If the new window size ends up being the same as or
1004 * less than the old size when it is scaled, then
1005 * don't force a window update.
1006 */
1007 if (recwin >> tp->rcv_scale <= oldwin >> tp->rcv_scale)
1008 goto dontupdate;
1009
1010 adv = recwin - oldwin;
1011 if (adv >= (long) (2 * rxsegsize))
1012 goto send;
1013 if (2 * adv >= (long) so->so_rcv.sb_hiwat)
1014 goto send;
1015 }
1016 dontupdate:
1017
1018 /*
1019 * Send if we owe peer an ACK.
1020 */
1021 if (tp->t_flags & TF_ACKNOW)
1022 goto send;
1023 if (flags & (TH_SYN|TH_FIN|TH_RST))
1024 goto send;
1025 if (SEQ_GT(tp->snd_up, tp->snd_una))
1026 goto send;
1027 /*
1028 * In SACK, it is possible for tcp_output to fail to send a segment
1029 * after the retransmission timer has been turned off. Make sure
1030 * that the retransmission timer is set.
1031 */
1032 if (TCP_SACK_ENABLED(tp) && SEQ_GT(tp->snd_max, tp->snd_una) &&
1033 !TCP_TIMER_ISARMED(tp, TCPT_REXMT) &&
1034 !TCP_TIMER_ISARMED(tp, TCPT_PERSIST)) {
1035 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
1036 goto just_return;
1037 }
1038
1039 /*
1040 * TCP window updates are not reliable, rather a polling protocol
1041 * using ``persist'' packets is used to insure receipt of window
1042 * updates. The three ``states'' for the output side are:
1043 * idle not doing retransmits or persists
1044 * persisting to move a small or zero window
1045 * (re)transmitting and thereby not persisting
1046 *
1047 * tp->t_timer[TCPT_PERSIST]
1048 * is set when we are in persist state.
1049 * tp->t_force
1050 * is set when we are called to send a persist packet.
1051 * tp->t_timer[TCPT_REXMT]
1052 * is set when we are retransmitting
1053 * The output side is idle when both timers are zero.
1054 *
1055 * If send window is too small, there is data to transmit, and no
1056 * retransmit or persist is pending, then go to persist state.
1057 * If nothing happens soon, send when timer expires:
1058 * if window is nonzero, transmit what we can,
1059 * otherwise force out a byte.
1060 */
1061 if (so->so_snd.sb_cc && TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
1062 TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
1063 tp->t_rxtshift = 0;
1064 tcp_setpersist(tp);
1065 }
1066
1067 /*
1068 * No reason to send a segment, just return.
1069 */
1070 just_return:
1071 TCP_REASS_UNLOCK(tp);
1072 return 0;
1073
1074 send:
1075 /*
1076 * Before ESTABLISHED, force sending of initial options unless TCP set
1077 * not to do any options.
1078 *
1079 * Note: we assume that the IP/TCP header plus TCP options always fit
1080 * in a single mbuf, leaving room for a maximum link header, i.e.:
1081 * max_linkhdr + IP_header + TCP_header + optlen <= MCLBYTES
1082 */
1083 optlen = 0;
1084 optp = opt;
1085 switch (af) {
1086 case AF_INET:
1087 iphdrlen = sizeof(struct ip) + sizeof(struct tcphdr);
1088 break;
1089 #ifdef INET6
1090 case AF_INET6:
1091 iphdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1092 break;
1093 #endif
1094 default: /*pacify gcc*/
1095 iphdrlen = 0;
1096 break;
1097 }
1098 hdrlen = iphdrlen;
1099 if (flags & TH_SYN) {
1100 struct rtentry *synrt;
1101
1102 synrt = NULL;
1103 if (tp->t_inpcb)
1104 synrt = in_pcbrtentry(tp->t_inpcb);
1105 #ifdef INET6
1106 if (tp->t_in6pcb)
1107 synrt = in6_pcbrtentry(tp->t_in6pcb);
1108 #endif
1109
1110 tp->snd_nxt = tp->iss;
1111 tp->t_ourmss = tcp_mss_to_advertise(synrt != NULL ?
1112 synrt->rt_ifp : NULL, af);
1113 if (tp->t_inpcb)
1114 in_pcbrtentry_unref(synrt, tp->t_inpcb);
1115 #ifdef INET6
1116 if (tp->t_in6pcb)
1117 in6_pcbrtentry_unref(synrt, tp->t_in6pcb);
1118 #endif
1119 if ((tp->t_flags & TF_NOOPT) == 0 && OPT_FITS(TCPOLEN_MAXSEG)) {
1120 *optp++ = TCPOPT_MAXSEG;
1121 *optp++ = TCPOLEN_MAXSEG;
1122 *optp++ = (tp->t_ourmss >> 8) & 0xff;
1123 *optp++ = tp->t_ourmss & 0xff;
1124 optlen += TCPOLEN_MAXSEG;
1125
1126 if ((tp->t_flags & TF_REQ_SCALE) &&
1127 ((flags & TH_ACK) == 0 ||
1128 (tp->t_flags & TF_RCVD_SCALE)) &&
1129 OPT_FITS(TCPOLEN_WINDOW + TCPOLEN_NOP)) {
1130 *((uint32_t *)optp) = htonl(
1131 TCPOPT_NOP << 24 |
1132 TCPOPT_WINDOW << 16 |
1133 TCPOLEN_WINDOW << 8 |
1134 tp->request_r_scale);
1135 optp += TCPOLEN_WINDOW + TCPOLEN_NOP;
1136 optlen += TCPOLEN_WINDOW + TCPOLEN_NOP;
1137 }
1138 if (tcp_do_sack && OPT_FITS(TCPOLEN_SACK_PERMITTED)) {
1139 *optp++ = TCPOPT_SACK_PERMITTED;
1140 *optp++ = TCPOLEN_SACK_PERMITTED;
1141 optlen += TCPOLEN_SACK_PERMITTED;
1142 }
1143 }
1144 }
1145
1146 /*
1147 * Send a timestamp and echo-reply if this is a SYN and our side
1148 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
1149 * and our peer have sent timestamps in our SYN's.
1150 */
1151 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
1152 (flags & TH_RST) == 0 &&
1153 ((flags & (TH_SYN|TH_ACK)) == TH_SYN ||
1154 (tp->t_flags & TF_RCVD_TSTMP))) {
1155 int alen = 0;
1156 while (optlen % 4 != 2) {
1157 optlen += TCPOLEN_NOP;
1158 *optp++ = TCPOPT_NOP;
1159 alen++;
1160 }
1161 if (OPT_FITS(TCPOLEN_TIMESTAMP)) {
1162 *optp++ = TCPOPT_TIMESTAMP;
1163 *optp++ = TCPOLEN_TIMESTAMP;
1164 uint32_t *lp = (uint32_t *)optp;
1165 /* Form timestamp option (appendix A of RFC 1323) */
1166 *lp++ = htonl(TCP_TIMESTAMP(tp));
1167 *lp = htonl(tp->ts_recent);
1168 optp += TCPOLEN_TIMESTAMP - 2;
1169 optlen += TCPOLEN_TIMESTAMP;
1170
1171 /* Set receive buffer autosizing timestamp. */
1172 if (tp->rfbuf_ts == 0 &&
1173 (so->so_rcv.sb_flags & SB_AUTOSIZE))
1174 tp->rfbuf_ts = TCP_TIMESTAMP(tp);
1175 } else {
1176 optp -= alen;
1177 optlen -= alen;
1178 }
1179 }
1180
1181 #ifdef TCP_SIGNATURE
1182 if (tp->t_flags & TF_SIGNATURE) {
1183 /*
1184 * Initialize TCP-MD5 option (RFC2385)
1185 */
1186 if (!OPT_FITS(TCPOLEN_SIGNATURE))
1187 goto reset;
1188
1189 *optp++ = TCPOPT_SIGNATURE;
1190 *optp++ = TCPOLEN_SIGNATURE;
1191 sigoff = optlen + 2;
1192 memset(optp, 0, TCP_SIGLEN);
1193 optlen += TCPOLEN_SIGNATURE;
1194 optp += TCP_SIGLEN;
1195 }
1196 #endif
1197
1198 /*
1199 * Tack on the SACK block if it is necessary.
1200 */
1201 if (sack_numblks) {
1202 int alen = 0;
1203 int sack_len = sack_numblks * 8;
1204 while (optlen % 4 != 2) {
1205 optlen += TCPOLEN_NOP;
1206 *optp++ = TCPOPT_NOP;
1207 alen++;
1208 }
1209 if (OPT_FITS(sack_len + 2)) {
1210 struct ipqent *tiqe;
1211 *optp++ = TCPOPT_SACK;
1212 *optp++ = sack_len + 2;
1213 uint32_t *lp = (uint32_t *)optp;
1214 if ((tp->rcv_sack_flags & TCPSACK_HAVED) != 0) {
1215 sack_numblks--;
1216 *lp++ = htonl(tp->rcv_dsack_block.left);
1217 *lp++ = htonl(tp->rcv_dsack_block.right);
1218 tp->rcv_sack_flags &= ~TCPSACK_HAVED;
1219 }
1220 for (tiqe = TAILQ_FIRST(&tp->timeq);
1221 sack_numblks > 0;
1222 tiqe = TAILQ_NEXT(tiqe, ipqe_timeq)) {
1223 KASSERT(tiqe != NULL);
1224 sack_numblks--;
1225 *lp++ = htonl(tiqe->ipqe_seq);
1226 *lp++ = htonl(tiqe->ipqe_seq + tiqe->ipqe_len +
1227 ((tiqe->ipqe_flags & TH_FIN) != 0 ? 1 : 0));
1228 }
1229 optlen += sack_len + 2;
1230 optp += sack_len;
1231 } else {
1232 optp -= alen;
1233 optlen -= alen;
1234 }
1235 }
1236
1237 /* Terminate and pad TCP options to a 4 byte boundary. */
1238 if (optlen % 4) {
1239 if (!OPT_FITS(TCPOLEN_EOL)) {
1240 reset: TCP_REASS_UNLOCK(tp);
1241 error = ECONNABORTED;
1242 goto out;
1243 }
1244 optlen += TCPOLEN_EOL;
1245 *optp++ = TCPOPT_EOL;
1246 }
1247 /*
1248 * According to RFC 793 (STD0007):
1249 * "The content of the header beyond the End-of-Option option
1250 * must be header padding (i.e., zero)."
1251 * and later: "The padding is composed of zeros."
1252 */
1253 while (optlen % 4) {
1254 if (!OPT_FITS(TCPOLEN_PAD))
1255 goto reset;
1256 optlen += TCPOLEN_PAD;
1257 *optp++ = TCPOPT_PAD;
1258 }
1259
1260 TCP_REASS_UNLOCK(tp);
1261
1262 hdrlen += optlen;
1263
1264 #ifdef DIAGNOSTIC
1265 if (!use_tso && len > txsegsize)
1266 panic("tcp data to be sent is larger than segment");
1267 else if (use_tso && len > IP_MAXPACKET)
1268 panic("tcp data to be sent is larger than max TSO size");
1269 if (max_linkhdr + hdrlen > MCLBYTES)
1270 panic("tcphdr too big");
1271 #endif
1272
1273 /*
1274 * Grab a header mbuf, attaching a copy of data to
1275 * be transmitted, and initialize the header from
1276 * the template for sends on this connection.
1277 */
1278 if (len) {
1279 error = tcp_build_datapkt(tp, so, off, len, hdrlen, &m);
1280 if (error)
1281 goto out;
1282 /*
1283 * If we're sending everything we've got, set PUSH.
1284 * (This will keep happy those implementations which only
1285 * give data to the user when a buffer fills or
1286 * a PUSH comes in.)
1287 */
1288 if (off + len == so->so_snd.sb_cc)
1289 flags |= TH_PUSH;
1290 } else {
1291 tcps = TCP_STAT_GETREF();
1292 if (tp->t_flags & TF_ACKNOW)
1293 tcps[TCP_STAT_SNDACKS]++;
1294 else if (flags & (TH_SYN|TH_FIN|TH_RST))
1295 tcps[TCP_STAT_SNDCTRL]++;
1296 else if (SEQ_GT(tp->snd_up, tp->snd_una))
1297 tcps[TCP_STAT_SNDURG]++;
1298 else
1299 tcps[TCP_STAT_SNDWINUP]++;
1300 TCP_STAT_PUTREF();
1301
1302 MGETHDR(m, M_DONTWAIT, MT_HEADER);
1303 if (m != NULL && max_linkhdr + hdrlen > MHLEN) {
1304 MCLGET(m, M_DONTWAIT);
1305 if ((m->m_flags & M_EXT) == 0) {
1306 m_freem(m);
1307 m = NULL;
1308 }
1309 }
1310 if (m == NULL) {
1311 error = ENOBUFS;
1312 goto out;
1313 }
1314 MCLAIM(m, &tcp_tx_mowner);
1315 m->m_data += max_linkhdr;
1316 m->m_len = hdrlen;
1317 }
1318 m_reset_rcvif(m);
1319 switch (af) {
1320 case AF_INET:
1321 ip = mtod(m, struct ip *);
1322 #ifdef INET6
1323 ip6 = NULL;
1324 #endif
1325 th = (struct tcphdr *)(ip + 1);
1326 break;
1327 #ifdef INET6
1328 case AF_INET6:
1329 ip = NULL;
1330 ip6 = mtod(m, struct ip6_hdr *);
1331 th = (struct tcphdr *)(ip6 + 1);
1332 break;
1333 #endif
1334 default: /*pacify gcc*/
1335 ip = NULL;
1336 #ifdef INET6
1337 ip6 = NULL;
1338 #endif
1339 th = NULL;
1340 break;
1341 }
1342 if (tp->t_template == NULL)
1343 panic("%s: no template", __func__);
1344 if (tp->t_template->m_len < iphdrlen)
1345 panic("%s: %d < %d", __func__, tp->t_template->m_len, iphdrlen);
1346 bcopy(mtod(tp->t_template, void *), mtod(m, void *), iphdrlen);
1347
1348 /*
1349 * If we are starting a connection, send ECN setup
1350 * SYN packet. If we are on a retransmit, we may
1351 * resend those bits a number of times as per
1352 * RFC 3168.
1353 */
1354 if (tp->t_state == TCPS_SYN_SENT && tcp_do_ecn) {
1355 if (tp->t_flags & TF_SYN_REXMT) {
1356 if (tp->t_ecn_retries--)
1357 flags |= TH_ECE|TH_CWR;
1358 } else {
1359 flags |= TH_ECE|TH_CWR;
1360 tp->t_ecn_retries = tcp_ecn_maxretries;
1361 }
1362 }
1363
1364 if (TCP_ECN_ALLOWED(tp)) {
1365 /*
1366 * If the peer has ECN, mark data packets
1367 * ECN capable. Ignore pure ack packets, retransmissions
1368 * and window probes.
1369 */
1370 if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
1371 !(tp->t_force && len == 1)) {
1372 ecn_tos = IPTOS_ECN_ECT0;
1373 TCP_STATINC(TCP_STAT_ECN_ECT);
1374 }
1375
1376 /*
1377 * Reply with proper ECN notifications.
1378 */
1379 if (tp->t_flags & TF_ECN_SND_CWR) {
1380 flags |= TH_CWR;
1381 tp->t_flags &= ~TF_ECN_SND_CWR;
1382 }
1383 if (tp->t_flags & TF_ECN_SND_ECE) {
1384 flags |= TH_ECE;
1385 }
1386 }
1387
1388 /*
1389 * If we are doing retransmissions, then snd_nxt will
1390 * not reflect the first unsent octet. For ACK only
1391 * packets, we do not want the sequence number of the
1392 * retransmitted packet, we want the sequence number
1393 * of the next unsent octet. So, if there is no data
1394 * (and no SYN or FIN), use snd_max instead of snd_nxt
1395 * when filling in ti_seq. But if we are in persist
1396 * state, snd_max might reflect one byte beyond the
1397 * right edge of the window, so use snd_nxt in that
1398 * case, since we know we aren't doing a retransmission.
1399 * (retransmit and persist are mutually exclusive...)
1400 */
1401 if (TCP_SACK_ENABLED(tp) && sack_rxmit) {
1402 th->th_seq = htonl(p->rxmit);
1403 p->rxmit += len;
1404 } else {
1405 if (len || (flags & (TH_SYN|TH_FIN)) ||
1406 TCP_TIMER_ISARMED(tp, TCPT_PERSIST))
1407 th->th_seq = htonl(tp->snd_nxt);
1408 else
1409 th->th_seq = htonl(tp->snd_max);
1410 }
1411 th->th_ack = htonl(tp->rcv_nxt);
1412 if (optlen) {
1413 memcpy(th + 1, opt, optlen);
1414 th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
1415 }
1416 th->th_flags = flags;
1417 /*
1418 * Calculate receive window. Don't shrink window,
1419 * but avoid silly window syndrome.
1420 */
1421 if (win < (long)(so->so_rcv.sb_hiwat / 4) && win < (long)rxsegsize)
1422 win = 0;
1423 if (win > (long)TCP_MAXWIN << tp->rcv_scale)
1424 win = (long)TCP_MAXWIN << tp->rcv_scale;
1425 if (win < (long)(int32_t)(tp->rcv_adv - tp->rcv_nxt))
1426 win = (long)(int32_t)(tp->rcv_adv - tp->rcv_nxt);
1427 th->th_win = htons((u_int16_t) (win>>tp->rcv_scale));
1428 if (th->th_win == 0) {
1429 tp->t_sndzerowin++;
1430 }
1431 if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
1432 u_int32_t urp = tp->snd_up - tp->snd_nxt;
1433 if (urp > IP_MAXPACKET)
1434 urp = IP_MAXPACKET;
1435 th->th_urp = htons((u_int16_t)urp);
1436 th->th_flags |= TH_URG;
1437 } else
1438 /*
1439 * If no urgent pointer to send, then we pull
1440 * the urgent pointer to the left edge of the send window
1441 * so that it doesn't drift into the send window on sequence
1442 * number wraparound.
1443 */
1444 tp->snd_up = tp->snd_una; /* drag it along */
1445
1446 #ifdef TCP_SIGNATURE
1447 if (sigoff && (tp->t_flags & TF_SIGNATURE)) {
1448 struct secasvar *sav;
1449 u_int8_t *sigp;
1450
1451 sav = tcp_signature_getsav(m);
1452 if (sav == NULL) {
1453 if (m)
1454 m_freem(m);
1455 return EPERM;
1456 }
1457
1458 m->m_pkthdr.len = hdrlen + len;
1459 sigp = (char *)th + sizeof(*th) + sigoff;
1460 tcp_signature(m, th, (char *)th - mtod(m, char *), sav, sigp);
1461
1462 key_sa_recordxfer(sav, m);
1463 KEY_SA_UNREF(&sav);
1464 }
1465 #endif
1466
1467 /*
1468 * Set ourselves up to be checksummed just before the packet
1469 * hits the wire.
1470 */
1471 switch (af) {
1472 case AF_INET:
1473 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1474 if (use_tso) {
1475 m->m_pkthdr.segsz = txsegsize;
1476 m->m_pkthdr.csum_flags = M_CSUM_TSOv4;
1477 } else {
1478 m->m_pkthdr.csum_flags = M_CSUM_TCPv4;
1479 if (len + optlen) {
1480 /* Fixup the pseudo-header checksum. */
1481 /* XXXJRT Not IP Jumbogram safe. */
1482 th->th_sum = in_cksum_addword(th->th_sum,
1483 htons((u_int16_t) (len + optlen)));
1484 }
1485 }
1486 break;
1487 #ifdef INET6
1488 case AF_INET6:
1489 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1490 if (use_tso) {
1491 m->m_pkthdr.segsz = txsegsize;
1492 m->m_pkthdr.csum_flags = M_CSUM_TSOv6;
1493 } else {
1494 m->m_pkthdr.csum_flags = M_CSUM_TCPv6;
1495 if (len + optlen) {
1496 /* Fixup the pseudo-header checksum. */
1497 /* XXXJRT: Not IPv6 Jumbogram safe. */
1498 th->th_sum = in_cksum_addword(th->th_sum,
1499 htons((u_int16_t) (len + optlen)));
1500 }
1501 }
1502 break;
1503 #endif
1504 }
1505
1506 /*
1507 * In transmit state, time the transmission and arrange for
1508 * the retransmit. In persist state, just set snd_max.
1509 */
1510 if (tp->t_force == 0 || TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
1511 tcp_seq startseq = tp->snd_nxt;
1512
1513 /*
1514 * Advance snd_nxt over sequence space of this segment.
1515 * There are no states in which we send both a SYN and a FIN,
1516 * so we collapse the tests for these flags.
1517 */
1518 if (flags & (TH_SYN|TH_FIN))
1519 tp->snd_nxt++;
1520 if (sack_rxmit)
1521 goto timer;
1522 tp->snd_nxt += len;
1523 if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
1524 tp->snd_max = tp->snd_nxt;
1525 /*
1526 * Time this transmission if not a retransmission and
1527 * not currently timing anything.
1528 */
1529 if (tp->t_rtttime == 0) {
1530 tp->t_rtttime = tcp_now;
1531 tp->t_rtseq = startseq;
1532 TCP_STATINC(TCP_STAT_SEGSTIMED);
1533 }
1534 }
1535
1536 /*
1537 * Set retransmit timer if not currently set,
1538 * and not doing an ack or a keep-alive probe.
1539 * Initial value for retransmit timer is smoothed
1540 * round-trip time + 2 * round-trip time variance.
1541 * Initialize shift counter which is used for backoff
1542 * of retransmit time.
1543 */
1544 timer:
1545 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0) {
1546 if ((sack_rxmit && tp->snd_nxt != tp->snd_max)
1547 || tp->snd_nxt != tp->snd_una) {
1548 if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST)) {
1549 TCP_TIMER_DISARM(tp, TCPT_PERSIST);
1550 tp->t_rxtshift = 0;
1551 }
1552 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
1553 } else if (len == 0 && so->so_snd.sb_cc > 0
1554 && TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
1555 /*
1556 * If we are sending a window probe and there's
1557 * unacked data in the socket, make sure at
1558 * least the persist timer is running.
1559 */
1560 tp->t_rxtshift = 0;
1561 tcp_setpersist(tp);
1562 }
1563 }
1564 } else
1565 if (SEQ_GT(tp->snd_nxt + len, tp->snd_max))
1566 tp->snd_max = tp->snd_nxt + len;
1567
1568 #ifdef TCP_DEBUG
1569 /*
1570 * Trace.
1571 */
1572 if (so->so_options & SO_DEBUG)
1573 tcp_trace(TA_OUTPUT, tp->t_state, tp, m, 0);
1574 #endif
1575
1576 /*
1577 * Fill in IP length and desired time to live and
1578 * send to IP level. There should be a better way
1579 * to handle ttl and tos; we could keep them in
1580 * the template, but need a way to checksum without them.
1581 */
1582 m->m_pkthdr.len = hdrlen + len;
1583
1584 switch (af) {
1585 case AF_INET:
1586 ip->ip_len = htons(m->m_pkthdr.len);
1587 packetlen = m->m_pkthdr.len;
1588 if (tp->t_inpcb) {
1589 ip->ip_ttl = tp->t_inpcb->inp_ip.ip_ttl;
1590 ip->ip_tos = tp->t_inpcb->inp_ip.ip_tos | ecn_tos;
1591 }
1592 #ifdef INET6
1593 else if (tp->t_in6pcb) {
1594 ip->ip_ttl = in6_selecthlim(tp->t_in6pcb, NULL); /*XXX*/
1595 ip->ip_tos = ecn_tos; /*XXX*/
1596 }
1597 #endif
1598 break;
1599 #ifdef INET6
1600 case AF_INET6:
1601 packetlen = m->m_pkthdr.len;
1602 ip6->ip6_nxt = IPPROTO_TCP;
1603 if (tp->t_in6pcb) {
1604 /*
1605 * we separately set hoplimit for every segment, since
1606 * the user might want to change the value via
1607 * setsockopt. Also, desired default hop limit might
1608 * be changed via Neighbor Discovery.
1609 */
1610 ip6->ip6_hlim = in6_selecthlim_rt(tp->t_in6pcb);
1611 }
1612 ip6->ip6_flow |= htonl(ecn_tos << 20);
1613 /* ip6->ip6_flow = ??? (from template) */
1614 /* ip6_plen will be filled in ip6_output(). */
1615 break;
1616 #endif
1617 default: /*pacify gcc*/
1618 packetlen = 0;
1619 break;
1620 }
1621
1622 switch (af) {
1623 case AF_INET:
1624 {
1625 struct mbuf *opts;
1626
1627 if (tp->t_inpcb)
1628 opts = tp->t_inpcb->inp_options;
1629 else
1630 opts = NULL;
1631 error = ip_output(m, opts, ro,
1632 (tp->t_mtudisc ? IP_MTUDISC : 0) |
1633 (so->so_options & SO_DONTROUTE), NULL, tp->t_inpcb);
1634 break;
1635 }
1636 #ifdef INET6
1637 case AF_INET6:
1638 {
1639 struct ip6_pktopts *opts;
1640
1641 if (tp->t_in6pcb)
1642 opts = tp->t_in6pcb->in6p_outputopts;
1643 else
1644 opts = NULL;
1645 error = ip6_output(m, opts, ro, so->so_options & SO_DONTROUTE,
1646 NULL, tp->t_in6pcb, NULL);
1647 break;
1648 }
1649 #endif
1650 default:
1651 error = EAFNOSUPPORT;
1652 break;
1653 }
1654 if (error) {
1655 out:
1656 if (error == ENOBUFS) {
1657 TCP_STATINC(TCP_STAT_SELFQUENCH);
1658 if (tp->t_inpcb)
1659 tcp_quench(tp->t_inpcb);
1660 #ifdef INET6
1661 if (tp->t_in6pcb)
1662 tcp6_quench(tp->t_in6pcb);
1663 #endif
1664 error = 0;
1665 } else if ((error == EHOSTUNREACH || error == ENETDOWN) &&
1666 TCPS_HAVERCVDSYN(tp->t_state)) {
1667 tp->t_softerror = error;
1668 error = 0;
1669 }
1670
1671 /* Back out the sequence number advance. */
1672 if (sack_rxmit)
1673 p->rxmit -= len;
1674
1675 /* Restart the delayed ACK timer, if necessary. */
1676 if (tp->t_flags & TF_DELACK)
1677 TCP_RESTART_DELACK(tp);
1678
1679 return error;
1680 }
1681
1682 if (packetlen > tp->t_pmtud_mtu_sent)
1683 tp->t_pmtud_mtu_sent = packetlen;
1684
1685 tcps = TCP_STAT_GETREF();
1686 tcps[TCP_STAT_SNDTOTAL]++;
1687 if (tp->t_flags & TF_DELACK)
1688 tcps[TCP_STAT_DELACK]++;
1689 TCP_STAT_PUTREF();
1690
1691 /*
1692 * Data sent (as far as we can tell).
1693 * If this advertises a larger window than any other segment,
1694 * then remember the size of the advertised window.
1695 * Any pending ACK has now been sent.
1696 */
1697 if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
1698 tp->rcv_adv = tp->rcv_nxt + win;
1699 tp->last_ack_sent = tp->rcv_nxt;
1700 tp->t_flags &= ~TF_ACKNOW;
1701 TCP_CLEAR_DELACK(tp);
1702 #ifdef DIAGNOSTIC
1703 if (maxburst < 0)
1704 printf("tcp_output: maxburst exceeded by %d\n", -maxburst);
1705 #endif
1706 if (sendalot && (tp->t_congctl == &tcp_reno_ctl || --maxburst))
1707 goto again;
1708 return 0;
1709 }
1710
1711 void
1712 tcp_setpersist(struct tcpcb *tp)
1713 {
1714 int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2);
1715 int nticks;
1716
1717 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT))
1718 panic("tcp_output REXMT");
1719 /*
1720 * Start/restart persistance timer.
1721 */
1722 if (t < tp->t_rttmin)
1723 t = tp->t_rttmin;
1724 TCPT_RANGESET(nticks, t * tcp_backoff[tp->t_rxtshift],
1725 TCPTV_PERSMIN, TCPTV_PERSMAX);
1726 TCP_TIMER_ARM(tp, TCPT_PERSIST, nticks);
1727 if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
1728 tp->t_rxtshift++;
1729 }
1730