1 /*
2 * Copyright (c) 2000-2021 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
30 * The Regents of the University of California. All rights reserved.
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. All advertising materials mentioning features or use of this software
41 * must display the following acknowledgement:
42 * This product includes software developed by the University of
43 * California, Berkeley and its contributors.
44 * 4. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 *
60 * @(#)tcp_output.c 8.4 (Berkeley) 5/24/95
61 * $FreeBSD: src/sys/netinet/tcp_output.c,v 1.39.2.10 2001/07/07 04:30:38 silby Exp $
62 */
63 /*
64 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
65 * support for mandatory and extensible security protections. This notice
66 * is included in support of clause 2.2 (b) of the Apple Public License,
67 * Version 2.0.
68 */
69
70 #define _IP_VHL
71
72
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/mbuf.h>
78 #include <sys/domain.h>
79 #include <sys/protosw.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82
83 #include <net/route.h>
84 #include <net/ntstat.h>
85 #include <net/if_var.h>
86 #include <net/if.h>
87 #include <net/if_types.h>
88 #include <net/dlil.h>
89
90 #include <netinet/in.h>
91 #include <netinet/in_systm.h>
92 #include <netinet/in_var.h>
93 #include <netinet/in_tclass.h>
94 #include <netinet/ip.h>
95 #include <netinet/in_pcb.h>
96 #include <netinet/ip_var.h>
97 #include <mach/sdt.h>
98 #include <netinet6/in6_pcb.h>
99 #include <netinet/ip6.h>
100 #include <netinet6/ip6_var.h>
101 #include <netinet/tcp.h>
102 #define TCPOUTFLAGS
103 #include <netinet/tcp_cache.h>
104 #include <netinet/tcp_fsm.h>
105 #include <netinet/tcp_seq.h>
106 #include <netinet/tcp_timer.h>
107 #include <netinet/tcp_var.h>
108 #include <netinet/tcpip.h>
109 #include <netinet/tcp_cc.h>
110 #if TCPDEBUG
111 #include <netinet/tcp_debug.h>
112 #endif
113 #include <netinet/tcp_log.h>
114 #include <sys/kdebug.h>
115 #include <mach/sdt.h>
116
117 #if IPSEC
118 #include <netinet6/ipsec.h>
119 #endif /*IPSEC*/
120
121 #if MPTCP
122 #include <netinet/mptcp_var.h>
123 #include <netinet/mptcp.h>
124 #include <netinet/mptcp_opt.h>
125 #include <netinet/mptcp_seq.h>
126 #endif
127
128 #include <corecrypto/ccaes.h>
129
130 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 1)
131 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 3)
132 #define DBG_FNC_TCP_OUTPUT NETDBG_CODE(DBG_NETTCP, (4 << 8) | 1)
133
134 SYSCTL_SKMEM_TCP_INT(OID_AUTO, path_mtu_discovery,
135 CTLFLAG_RW | CTLFLAG_LOCKED, int, path_mtu_discovery, 1,
136 "Enable Path MTU Discovery");
137
138 SYSCTL_SKMEM_TCP_INT(OID_AUTO, local_slowstart_flightsize,
139 CTLFLAG_RW | CTLFLAG_LOCKED, int, ss_fltsz_local, 8,
140 "Slow start flight size for local networks");
141
142 int tcp_do_tso = 1;
143 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tso, CTLFLAG_RW | CTLFLAG_LOCKED,
144 &tcp_do_tso, 0, "Enable TCP Segmentation Offload");
145
146 SYSCTL_SKMEM_TCP_INT(OID_AUTO, ecn_setup_percentage,
147 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_ecn_setup_percentage, 100,
148 "Max ECN setup percentage");
149
150 SYSCTL_SKMEM_TCP_INT(OID_AUTO, do_ack_compression,
151 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_do_ack_compression, 1,
152 "Enable TCP ACK compression (on (cell only): 1, off: 0, on (all interfaces): 2)");
153
154 SYSCTL_SKMEM_TCP_INT(OID_AUTO, ack_compression_rate,
155 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_ack_compression_rate, TCP_COMP_CHANGE_RATE,
156 "Rate at which we force sending new ACKs (in ms)");
157
158 SYSCTL_SKMEM_TCP_INT(OID_AUTO, randomize_timestamps,
159 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_randomize_timestamps, 1,
160 "Randomize TCP timestamps to prevent tracking (on: 1, off: 0)");
161
162 static int
163 sysctl_change_ecn_setting SYSCTL_HANDLER_ARGS
164 {
165 #pragma unused(oidp, arg1, arg2)
166 int i, err = 0, changed = 0;
167 struct ifnet *ifp;
168
169 err = sysctl_io_number(req, tcp_ecn_outbound, sizeof(int32_t),
170 &i, &changed);
171 if (err != 0 || req->newptr == USER_ADDR_NULL) {
172 return err;
173 }
174
175 if (changed) {
176 if ((tcp_ecn_outbound == 0 || tcp_ecn_outbound == 1) &&
177 (i == 0 || i == 1)) {
178 tcp_ecn_outbound = i;
179 SYSCTL_SKMEM_UPDATE_FIELD(tcp.ecn_initiate_out, tcp_ecn_outbound);
180 return err;
181 }
182 if (tcp_ecn_outbound == 2 && (i == 0 || i == 1)) {
183 /*
184 * Reset ECN enable flags on non-cellular
185 * interfaces so that the system default will take
186 * over
187 */
188 ifnet_head_lock_shared();
189 TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
190 if (!IFNET_IS_CELLULAR(ifp)) {
191 if_clear_eflags(ifp,
192 IFEF_ECN_ENABLE |
193 IFEF_ECN_DISABLE);
194 }
195 }
196 ifnet_head_done();
197 } else {
198 /*
199 * Set ECN enable flags on non-cellular
200 * interfaces
201 */
202 ifnet_head_lock_shared();
203 TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
204 if (!IFNET_IS_CELLULAR(ifp)) {
205 if_set_eflags(ifp, IFEF_ECN_ENABLE);
206 if_clear_eflags(ifp, IFEF_ECN_DISABLE);
207 }
208 }
209 ifnet_head_done();
210 }
211 tcp_ecn_outbound = i;
212 SYSCTL_SKMEM_UPDATE_FIELD(tcp.ecn_initiate_out, tcp_ecn_outbound);
213 }
214 /* Change the other one too as the work is done */
215 if (i == 2 || tcp_ecn_inbound == 2) {
216 tcp_ecn_inbound = i;
217 SYSCTL_SKMEM_UPDATE_FIELD(tcp.ecn_negotiate_in, tcp_ecn_inbound);
218 }
219 return err;
220 }
221
222 int tcp_ecn_outbound = 2;
223 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, ecn_initiate_out,
224 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_ecn_outbound, 0,
225 sysctl_change_ecn_setting, "IU",
226 "Initiate ECN for outbound connections");
227
228 int tcp_ecn_inbound = 2;
229 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, ecn_negotiate_in,
230 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_ecn_inbound, 0,
231 sysctl_change_ecn_setting, "IU",
232 "Initiate ECN for inbound connections");
233
234 SYSCTL_SKMEM_TCP_INT(OID_AUTO, packetchain,
235 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_packet_chaining, 50,
236 "Enable TCP output packet chaining");
237
238 SYSCTL_SKMEM_TCP_INT(OID_AUTO, socket_unlocked_on_output,
239 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_output_unlocked, 1,
240 "Unlock TCP when sending packets down to IP");
241
242 SYSCTL_SKMEM_TCP_INT(OID_AUTO, min_iaj_win,
243 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_min_iaj_win, MIN_IAJ_WIN,
244 "Minimum recv win based on inter-packet arrival jitter");
245
246 SYSCTL_SKMEM_TCP_INT(OID_AUTO, acc_iaj_react_limit,
247 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_acc_iaj_react_limit,
248 ACC_IAJ_REACT_LIMIT, "Accumulated IAJ when receiver starts to react");
249
250 SYSCTL_SKMEM_TCP_INT(OID_AUTO, autosndbufinc,
251 CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_autosndbuf_inc,
252 8 * 1024, "Increment in send socket bufffer size");
253
254 SYSCTL_SKMEM_TCP_INT(OID_AUTO, autosndbufmax,
255 CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_autosndbuf_max, 2 * 1024 * 1024,
256 "Maximum send socket buffer size");
257
258 SYSCTL_SKMEM_TCP_INT(OID_AUTO, rtt_recvbg,
259 CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_use_rtt_recvbg, 1,
260 "Use RTT for bg recv algorithm");
261
262 SYSCTL_SKMEM_TCP_INT(OID_AUTO, recv_throttle_minwin,
263 CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_recv_throttle_minwin, 16 * 1024,
264 "Minimum recv win for throttling");
265
266 SYSCTL_SKMEM_TCP_INT(OID_AUTO, enable_tlp,
267 CTLFLAG_RW | CTLFLAG_LOCKED,
268 int32_t, tcp_enable_tlp, 1, "Enable Tail loss probe");
269
270 static int32_t packchain_newlist = 0;
271 static int32_t packchain_looped = 0;
272 static int32_t packchain_sent = 0;
273
274 /* temporary: for testing */
275 #if IPSEC
276 extern int ipsec_bypass;
277 #endif
278
279 extern int slowlink_wsize; /* window correction for slow links */
280
281 extern u_int32_t kipf_count;
282
283 static int tcp_ip_output(struct socket *, struct tcpcb *, struct mbuf *,
284 int, struct mbuf *, int, int, boolean_t);
285 static int tcp_recv_throttle(struct tcpcb *tp);
286
287 __attribute__((noinline))
288 static int32_t
tcp_tfo_check(struct tcpcb * tp,int32_t len)289 tcp_tfo_check(struct tcpcb *tp, int32_t len)
290 {
291 struct socket *so = tp->t_inpcb->inp_socket;
292 unsigned int optlen = 0;
293 unsigned int cookie_len;
294
295 if (tp->t_flags & TF_NOOPT) {
296 goto fallback;
297 }
298
299 if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
300 !tcp_heuristic_do_tfo(tp)) {
301 tp->t_tfo_stats |= TFO_S_HEURISTICS_DISABLE;
302 tcpstat.tcps_tfo_heuristics_disable++;
303 goto fallback;
304 }
305
306 if (so->so_flags1 & SOF1_DATA_AUTHENTICATED) {
307 return len;
308 }
309
310 optlen += TCPOLEN_MAXSEG;
311
312 if (tp->t_flags & TF_REQ_SCALE) {
313 optlen += 4;
314 }
315
316 #if MPTCP
317 if ((so->so_flags & SOF_MP_SUBFLOW) && mptcp_enable &&
318 (tp->t_rxtshift <= mptcp_mpcap_retries ||
319 (tptomptp(tp)->mpt_mpte->mpte_flags & MPTE_FORCE_ENABLE))) {
320 optlen += sizeof(struct mptcp_mpcapable_opt_common) + sizeof(mptcp_key_t);
321 }
322 #endif /* MPTCP */
323
324 if (tp->t_flags & TF_REQ_TSTMP) {
325 optlen += TCPOLEN_TSTAMP_APPA;
326 }
327
328 if (SACK_ENABLED(tp)) {
329 optlen += TCPOLEN_SACK_PERMITTED;
330 }
331
332 /* Now, decide whether to use TFO or not */
333
334 /* Don't even bother trying if there is no space at all... */
335 if (MAX_TCPOPTLEN - optlen < TCPOLEN_FASTOPEN_REQ) {
336 goto fallback;
337 }
338
339 cookie_len = tcp_cache_get_cookie_len(tp);
340 if (cookie_len == 0) {
341 /* No cookie, so we request one */
342 return 0;
343 }
344
345 /* There is not enough space for the cookie, so we cannot do TFO */
346 if (MAX_TCPOPTLEN - optlen < cookie_len) {
347 goto fallback;
348 }
349
350 /* Do not send SYN+data if there is more in the queue than MSS */
351 if (so->so_snd.sb_cc > (tp->t_maxopd - MAX_TCPOPTLEN)) {
352 goto fallback;
353 }
354
355 /* Ok, everything looks good. We can go on and do TFO */
356 return len;
357
358 fallback:
359 tcp_disable_tfo(tp);
360 return 0;
361 }
362
363 /* Returns the number of bytes written to the TCP option-space */
364 __attribute__((noinline))
365 static unsigned int
tcp_tfo_write_cookie_rep(struct tcpcb * tp,unsigned int optlen,u_char * opt)366 tcp_tfo_write_cookie_rep(struct tcpcb *tp, unsigned int optlen, u_char *opt)
367 {
368 u_char out[CCAES_BLOCK_SIZE];
369 unsigned ret = 0;
370 u_char *bp;
371
372 if ((MAX_TCPOPTLEN - optlen) <
373 (TCPOLEN_FASTOPEN_REQ + TFO_COOKIE_LEN_DEFAULT)) {
374 return ret;
375 }
376
377 tcp_tfo_gen_cookie(tp->t_inpcb, out, sizeof(out));
378
379 bp = opt + optlen;
380
381 *bp++ = TCPOPT_FASTOPEN;
382 *bp++ = 2 + TFO_COOKIE_LEN_DEFAULT;
383 memcpy(bp, out, TFO_COOKIE_LEN_DEFAULT);
384 ret += 2 + TFO_COOKIE_LEN_DEFAULT;
385
386 tp->t_tfo_stats |= TFO_S_COOKIE_SENT;
387 tcpstat.tcps_tfo_cookie_sent++;
388
389 return ret;
390 }
391
392 __attribute__((noinline))
393 static unsigned int
tcp_tfo_write_cookie(struct tcpcb * tp,unsigned int optlen,int32_t len,u_char * opt)394 tcp_tfo_write_cookie(struct tcpcb *tp, unsigned int optlen, int32_t len,
395 u_char *opt)
396 {
397 uint8_t tfo_len;
398 struct socket *so = tp->t_inpcb->inp_socket;
399 unsigned ret = 0;
400 int res;
401 u_char *bp;
402
403 if (TCPOLEN_FASTOPEN_REQ > MAX_TCPOPTLEN - optlen) {
404 return 0;
405 }
406 tfo_len = (uint8_t)(MAX_TCPOPTLEN - optlen - TCPOLEN_FASTOPEN_REQ);
407
408 if (so->so_flags1 & SOF1_DATA_AUTHENTICATED) {
409 /* If there is some data, let's track it */
410 if (len > 0) {
411 tp->t_tfo_stats |= TFO_S_SYN_DATA_SENT;
412 tcpstat.tcps_tfo_syn_data_sent++;
413 }
414
415 return 0;
416 }
417
418 bp = opt + optlen;
419
420 /*
421 * The cookie will be copied in the appropriate place within the
422 * TCP-option space. That way we avoid the need for an intermediate
423 * variable.
424 */
425 res = tcp_cache_get_cookie(tp, bp + TCPOLEN_FASTOPEN_REQ, &tfo_len);
426 if (res == 0) {
427 *bp++ = TCPOPT_FASTOPEN;
428 *bp++ = TCPOLEN_FASTOPEN_REQ;
429 ret += TCPOLEN_FASTOPEN_REQ;
430
431 tp->t_tfo_flags |= TFO_F_COOKIE_REQ;
432
433 tp->t_tfo_stats |= TFO_S_COOKIE_REQ;
434 tcpstat.tcps_tfo_cookie_req++;
435 } else {
436 *bp++ = TCPOPT_FASTOPEN;
437 *bp++ = TCPOLEN_FASTOPEN_REQ + tfo_len;
438
439 ret += TCPOLEN_FASTOPEN_REQ + tfo_len;
440
441 tp->t_tfo_flags |= TFO_F_COOKIE_SENT;
442
443 /* If there is some data, let's track it */
444 if (len > 0) {
445 tp->t_tfo_stats |= TFO_S_SYN_DATA_SENT;
446 tcpstat.tcps_tfo_syn_data_sent++;
447 }
448 }
449
450 return ret;
451 }
452
453 static inline bool
tcp_send_ecn_flags_on_syn(struct tcpcb * tp)454 tcp_send_ecn_flags_on_syn(struct tcpcb *tp)
455 {
456 return !(tp->ecn_flags & TE_SETUPSENT);
457 }
458
459 void
tcp_set_ecn(struct tcpcb * tp,struct ifnet * ifp)460 tcp_set_ecn(struct tcpcb *tp, struct ifnet *ifp)
461 {
462 boolean_t inbound;
463
464 /*
465 * Socket option has precedence
466 */
467 if (tp->ecn_flags & TE_ECN_MODE_ENABLE) {
468 tp->ecn_flags |= TE_ENABLE_ECN;
469 goto check_heuristic;
470 }
471
472 if (tp->ecn_flags & TE_ECN_MODE_DISABLE) {
473 tp->ecn_flags &= ~TE_ENABLE_ECN;
474 return;
475 }
476 /*
477 * Per interface setting comes next
478 */
479 if (ifp != NULL) {
480 if (ifp->if_eflags & IFEF_ECN_ENABLE) {
481 tp->ecn_flags |= TE_ENABLE_ECN;
482 goto check_heuristic;
483 }
484
485 if (ifp->if_eflags & IFEF_ECN_DISABLE) {
486 tp->ecn_flags &= ~TE_ENABLE_ECN;
487 return;
488 }
489 }
490 /*
491 * System wide settings come last
492 */
493 inbound = (tp->t_inpcb->inp_socket->so_head != NULL);
494 if ((inbound && tcp_ecn_inbound == 1) ||
495 (!inbound && tcp_ecn_outbound == 1)) {
496 tp->ecn_flags |= TE_ENABLE_ECN;
497 goto check_heuristic;
498 } else {
499 tp->ecn_flags &= ~TE_ENABLE_ECN;
500 }
501
502 return;
503
504 check_heuristic:
505 if (!tcp_heuristic_do_ecn(tp)) {
506 tp->ecn_flags &= ~TE_ENABLE_ECN;
507 }
508
509 /*
510 * If the interface setting, system-level setting and heuristics
511 * allow to enable ECN, randomly select 5% of connections to
512 * enable it
513 */
514 if ((tp->ecn_flags & (TE_ECN_MODE_ENABLE | TE_ECN_MODE_DISABLE
515 | TE_ENABLE_ECN)) == TE_ENABLE_ECN) {
516 /*
517 * Use the random value in iss for randomizing
518 * this selection
519 */
520 if ((tp->iss % 100) >= tcp_ecn_setup_percentage) {
521 tp->ecn_flags &= ~TE_ENABLE_ECN;
522 }
523 }
524 }
525
526 int
tcp_flight_size(struct tcpcb * tp)527 tcp_flight_size(struct tcpcb *tp)
528 {
529 int ret;
530
531 VERIFY(tp->sackhint.sack_bytes_acked >= 0);
532 VERIFY(tp->sackhint.sack_bytes_rexmit >= 0);
533
534 /*
535 * RFC6675, SetPipe (), SACK'd bytes are discounted. All the rest is still in-flight.
536 */
537 ret = tp->snd_nxt - tp->snd_una - tp->sackhint.sack_bytes_acked;
538
539 if (ret < 0) {
540 /*
541 * This happens when the RTO-timer fires because snd_nxt gets artificially
542 * decreased. If we then receive some SACK-blogs, sack_bytes_acked is
543 * going to be high.
544 */
545 ret = 0;
546 }
547
548 return ret;
549 }
550
551 /*
552 * Tcp output routine: figure out what should be sent and send it.
553 *
554 * Returns: 0 Success
555 * EADDRNOTAVAIL
556 * ENOBUFS
557 * EMSGSIZE
558 * EHOSTUNREACH
559 * ENETDOWN
560 * ip_output_list:ENOMEM
561 * ip_output_list:EADDRNOTAVAIL
562 * ip_output_list:ENETUNREACH
563 * ip_output_list:EHOSTUNREACH
564 * ip_output_list:EACCES
565 * ip_output_list:EMSGSIZE
566 * ip_output_list:ENOBUFS
567 * ip_output_list:??? [ignorable: mostly IPSEC/firewall/DLIL]
568 * ip6_output_list:EINVAL
569 * ip6_output_list:EOPNOTSUPP
570 * ip6_output_list:EHOSTUNREACH
571 * ip6_output_list:EADDRNOTAVAIL
572 * ip6_output_list:ENETUNREACH
573 * ip6_output_list:EMSGSIZE
574 * ip6_output_list:ENOBUFS
575 * ip6_output_list:??? [ignorable: mostly IPSEC/firewall/DLIL]
576 */
577 int
tcp_output(struct tcpcb * tp)578 tcp_output(struct tcpcb *tp)
579 {
580 struct inpcb *inp = tp->t_inpcb;
581 struct socket *so = inp->inp_socket;
582 int32_t len, recwin, sendwin, off;
583 uint8_t flags;
584 int error;
585 struct mbuf *m;
586 struct ip *ip = NULL;
587 struct ip6_hdr *ip6 = NULL;
588 struct tcphdr *th;
589 u_char opt[TCP_MAXOLEN];
590 unsigned int ipoptlen, optlen, hdrlen;
591 int idle, sendalot, lost = 0;
592 int i, sack_rxmit;
593 int tso = 0;
594 int sack_bytes_rxmt;
595 tcp_seq old_snd_nxt = 0;
596 struct sackhole *p;
597 #if IPSEC
598 unsigned int ipsec_optlen = 0;
599 #endif /* IPSEC */
600 int idle_time = 0;
601 struct mbuf *packetlist = NULL;
602 struct mbuf *tp_inp_options = inp->inp_depend4.inp4_options;
603 int isipv6 = inp->inp_vflag & INP_IPV6;
604 int packchain_listadd = 0;
605 int so_options = so->so_options;
606 struct rtentry *rt;
607 u_int32_t svc_flags = 0, allocated_len;
608 unsigned int sackoptlen = 0;
609 #if MPTCP
610 boolean_t mptcp_acknow;
611 #endif /* MPTCP */
612 boolean_t cell = FALSE;
613 boolean_t wifi = FALSE;
614 boolean_t wired = FALSE;
615 boolean_t sack_rescue_rxt = FALSE;
616 int sotc = so->so_traffic_class;
617 boolean_t do_not_compress = FALSE;
618 boolean_t sack_rxmted = FALSE;
619
620 /*
621 * Determine length of data that should be transmitted,
622 * and flags that will be used.
623 * If there is some data or critical controls (SYN, RST)
624 * to send, then transmit; otherwise, investigate further.
625 */
626 idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
627
628 /* Since idle_time is signed integer, the following integer subtraction
629 * will take care of wrap around of tcp_now
630 */
631 idle_time = tcp_now - tp->t_rcvtime;
632 if (idle && idle_time >= TCP_IDLETIMEOUT(tp)) {
633 if (CC_ALGO(tp)->after_idle != NULL &&
634 (tp->tcp_cc_index != TCP_CC_ALGO_CUBIC_INDEX ||
635 idle_time >= TCP_CC_CWND_NONVALIDATED_PERIOD)) {
636 CC_ALGO(tp)->after_idle(tp);
637 tcp_ccdbg_trace(tp, NULL, TCP_CC_IDLE_TIMEOUT);
638 }
639
640 /*
641 * Do some other tasks that need to be done after
642 * idle time
643 */
644 if (!SLIST_EMPTY(&tp->t_rxt_segments)) {
645 tcp_rxtseg_clean(tp);
646 }
647
648 /* If stretch ack was auto-disabled, re-evaluate it */
649 tcp_cc_after_idle_stretchack(tp);
650 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
651 }
652 tp->t_flags &= ~TF_LASTIDLE;
653 if (idle) {
654 if (tp->t_flags & TF_MORETOCOME) {
655 tp->t_flags |= TF_LASTIDLE;
656 idle = 0;
657 }
658 }
659 #if MPTCP
660 if (tp->t_mpflags & TMPF_RESET) {
661 tcp_check_timer_state(tp);
662 /*
663 * Once a RST has been sent for an MPTCP subflow,
664 * the subflow socket stays around until deleted.
665 * No packets such as FINs must be sent after RST.
666 */
667 return 0;
668 }
669 #endif /* MPTCP */
670
671 again:
672 #if MPTCP
673 mptcp_acknow = FALSE;
674 #endif
675 do_not_compress = FALSE;
676
677 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_START, 0, 0, 0, 0, 0);
678
679 if (isipv6) {
680 KERNEL_DEBUG(DBG_LAYER_BEG,
681 ((inp->inp_fport << 16) | inp->inp_lport),
682 (((inp->in6p_laddr.s6_addr16[0] & 0xffff) << 16) |
683 (inp->in6p_faddr.s6_addr16[0] & 0xffff)),
684 sendalot, 0, 0);
685 } else {
686 KERNEL_DEBUG(DBG_LAYER_BEG,
687 ((inp->inp_fport << 16) | inp->inp_lport),
688 (((inp->inp_laddr.s_addr & 0xffff) << 16) |
689 (inp->inp_faddr.s_addr & 0xffff)),
690 sendalot, 0, 0);
691 }
692 /*
693 * If the route generation id changed, we need to check that our
694 * local (source) IP address is still valid. If it isn't either
695 * return error or silently do nothing (assuming the address will
696 * come back before the TCP connection times out).
697 */
698 rt = inp->inp_route.ro_rt;
699 if (rt != NULL && ROUTE_UNUSABLE(&tp->t_inpcb->inp_route)) {
700 struct ifnet *ifp;
701 struct in_ifaddr *ia = NULL;
702 struct in6_ifaddr *ia6 = NULL;
703 int found_srcaddr = 0;
704
705 /* disable multipages at the socket */
706 somultipages(so, FALSE);
707
708 /* Disable TSO for the socket until we know more */
709 tp->t_flags &= ~TF_TSO;
710
711 soif2kcl(so, FALSE);
712
713 if (isipv6) {
714 ia6 = ifa_foraddr6(&inp->in6p_laddr);
715 if (ia6 != NULL) {
716 found_srcaddr = 1;
717 }
718 } else {
719 ia = ifa_foraddr(inp->inp_laddr.s_addr);
720 if (ia != NULL) {
721 found_srcaddr = 1;
722 }
723 }
724
725 /* check that the source address is still valid */
726 if (found_srcaddr == 0) {
727 soevent(so,
728 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_NOSRCADDR));
729
730 if (tp->t_state >= TCPS_CLOSE_WAIT) {
731 tcp_drop(tp, EADDRNOTAVAIL);
732 return EADDRNOTAVAIL;
733 }
734
735 /*
736 * Set retransmit timer if it wasn't set,
737 * reset Persist timer and shift register as the
738 * advertised peer window may not be valid anymore
739 */
740 if (tp->t_timer[TCPT_REXMT] == 0) {
741 tp->t_timer[TCPT_REXMT] =
742 OFFSET_FROM_START(tp, tp->t_rxtcur);
743 if (tp->t_timer[TCPT_PERSIST] != 0) {
744 tp->t_timer[TCPT_PERSIST] = 0;
745 tp->t_persist_stop = 0;
746 TCP_RESET_REXMT_STATE(tp);
747 }
748 }
749
750 if (tp->t_pktlist_head != NULL) {
751 m_freem_list(tp->t_pktlist_head);
752 }
753 TCP_PKTLIST_CLEAR(tp);
754
755 /* drop connection if source address isn't available */
756 if (so->so_flags & SOF_NOADDRAVAIL) {
757 tcp_drop(tp, EADDRNOTAVAIL);
758 return EADDRNOTAVAIL;
759 } else {
760 tcp_check_timer_state(tp);
761 return 0; /* silently ignore, keep data in socket: address may be back */
762 }
763 }
764 if (ia != NULL) {
765 IFA_REMREF(&ia->ia_ifa);
766 }
767
768 if (ia6 != NULL) {
769 IFA_REMREF(&ia6->ia_ifa);
770 }
771
772 /*
773 * Address is still valid; check for multipages capability
774 * again in case the outgoing interface has changed.
775 */
776 RT_LOCK(rt);
777 if ((ifp = rt->rt_ifp) != NULL) {
778 somultipages(so, (ifp->if_hwassist & IFNET_MULTIPAGES));
779 tcp_set_tso(tp, ifp);
780 soif2kcl(so, (ifp->if_eflags & IFEF_2KCL));
781 tcp_set_ecn(tp, ifp);
782 }
783 if (rt->rt_flags & RTF_UP) {
784 RT_GENID_SYNC(rt);
785 }
786 /*
787 * See if we should do MTU discovery. Don't do it if:
788 * 1) it is disabled via the sysctl
789 * 2) the route isn't up
790 * 3) the MTU is locked (if it is, then discovery
791 * has been disabled)
792 */
793
794 if (!path_mtu_discovery || ((rt != NULL) &&
795 (!(rt->rt_flags & RTF_UP) ||
796 (rt->rt_rmx.rmx_locks & RTV_MTU)))) {
797 tp->t_flags &= ~TF_PMTUD;
798 } else {
799 tp->t_flags |= TF_PMTUD;
800 }
801
802 RT_UNLOCK(rt);
803 }
804
805 if (rt != NULL) {
806 cell = IFNET_IS_CELLULAR(rt->rt_ifp);
807 wifi = (!cell && IFNET_IS_WIFI(rt->rt_ifp));
808 wired = (!wifi && IFNET_IS_WIRED(rt->rt_ifp));
809 }
810
811 /*
812 * If we've recently taken a timeout, snd_max will be greater than
813 * snd_nxt. There may be SACK information that allows us to avoid
814 * resending already delivered data. Adjust snd_nxt accordingly.
815 */
816 if (SACK_ENABLED(tp) && SEQ_LT(tp->snd_nxt, tp->snd_max)) {
817 tcp_sack_adjust(tp);
818 }
819 sendalot = 0;
820 off = tp->snd_nxt - tp->snd_una;
821 sendwin = min(tp->snd_wnd, tp->snd_cwnd);
822
823 if (tp->t_flags & TF_SLOWLINK && slowlink_wsize > 0) {
824 sendwin = min(sendwin, slowlink_wsize);
825 }
826
827 flags = tcp_outflags[tp->t_state];
828 /*
829 * Send any SACK-generated retransmissions. If we're explicitly
830 * trying to send out new data (when sendalot is 1), bypass this
831 * function. If we retransmit in fast recovery mode, decrement
832 * snd_cwnd, since we're replacing a (future) new transmission
833 * with a retransmission now, and we previously incremented
834 * snd_cwnd in tcp_input().
835 */
836 /*
837 * Still in sack recovery , reset rxmit flag to zero.
838 */
839 sack_rxmit = 0;
840 sack_bytes_rxmt = 0;
841 len = 0;
842 p = NULL;
843 if (SACK_ENABLED(tp) && IN_FASTRECOVERY(tp) &&
844 (p = tcp_sack_output(tp, &sack_bytes_rxmt))) {
845 int32_t cwin;
846
847 if (tcp_do_better_lr) {
848 cwin = min(tp->snd_wnd, tp->snd_cwnd) - tcp_flight_size(tp);
849 if (cwin <= 0 && sack_rxmted == FALSE) {
850 /* Allow to clock out at least on per period */
851 cwin = tp->t_maxseg;
852 }
853
854 sack_rxmted = TRUE;
855 } else {
856 cwin = min(tp->snd_wnd, tp->snd_cwnd) - sack_bytes_rxmt;
857 }
858 if (cwin < 0) {
859 cwin = 0;
860 }
861 /* Do not retransmit SACK segments beyond snd_recover */
862 if (SEQ_GT(p->end, tp->snd_recover)) {
863 /*
864 * (At least) part of sack hole extends beyond
865 * snd_recover. Check to see if we can rexmit data
866 * for this hole.
867 */
868 if (SEQ_GEQ(p->rxmit, tp->snd_recover)) {
869 /*
870 * Can't rexmit any more data for this hole.
871 * That data will be rexmitted in the next
872 * sack recovery episode, when snd_recover
873 * moves past p->rxmit.
874 */
875 p = NULL;
876 goto after_sack_rexmit;
877 } else {
878 /* Can rexmit part of the current hole */
879 len = ((int32_t)min(cwin,
880 tp->snd_recover - p->rxmit));
881 }
882 } else {
883 len = ((int32_t)min(cwin, p->end - p->rxmit));
884 }
885 if (len > 0) {
886 off = p->rxmit - tp->snd_una;
887 sack_rxmit = 1;
888 sendalot = 1;
889 /* Everything sent after snd_nxt will allow us to account for fast-retransmit of the retransmitted segment */
890 tp->send_highest_sack = tp->snd_nxt;
891 tp->t_new_dupacks = 0;
892 tcpstat.tcps_sack_rexmits++;
893 tcpstat.tcps_sack_rexmit_bytes +=
894 min(len, tp->t_maxseg);
895 } else {
896 len = 0;
897 }
898 }
899 after_sack_rexmit:
900 /*
901 * Get standard flags, and add SYN or FIN if requested by 'hidden'
902 * state flags.
903 */
904 if (tp->t_flags & TF_NEEDFIN) {
905 flags |= TH_FIN;
906 }
907
908 /*
909 * If in persist timeout with window of 0, send 1 byte.
910 * Otherwise, if window is small but nonzero
911 * and timer expired, we will send what we can
912 * and go to transmit state.
913 */
914 if (tp->t_flagsext & TF_FORCE) {
915 if (sendwin == 0) {
916 /*
917 * If we still have some data to send, then
918 * clear the FIN bit. Usually this would
919 * happen below when it realizes that we
920 * aren't sending all the data. However,
921 * if we have exactly 1 byte of unsent data,
922 * then it won't clear the FIN bit below,
923 * and if we are in persist state, we wind
924 * up sending the packet without recording
925 * that we sent the FIN bit.
926 *
927 * We can't just blindly clear the FIN bit,
928 * because if we don't have any more data
929 * to send then the probe will be the FIN
930 * itself.
931 */
932 if (off < so->so_snd.sb_cc) {
933 flags &= ~TH_FIN;
934 }
935 sendwin = 1;
936 } else {
937 tp->t_timer[TCPT_PERSIST] = 0;
938 tp->t_persist_stop = 0;
939 TCP_RESET_REXMT_STATE(tp);
940 }
941 }
942
943 /*
944 * If snd_nxt == snd_max and we have transmitted a FIN, the
945 * offset will be > 0 even if so_snd.sb_cc is 0, resulting in
946 * a negative length. This can also occur when TCP opens up
947 * its congestion window while receiving additional duplicate
948 * acks after fast-retransmit because TCP will reset snd_nxt
949 * to snd_max after the fast-retransmit.
950 *
951 * In the normal retransmit-FIN-only case, however, snd_nxt will
952 * be set to snd_una, the offset will be 0, and the length may
953 * wind up 0.
954 *
955 * If sack_rxmit is true we are retransmitting from the scoreboard
956 * in which case len is already set.
957 */
958 if (sack_rxmit == 0) {
959 if (sack_bytes_rxmt == 0) {
960 len = min(so->so_snd.sb_cc, sendwin) - off;
961 } else {
962 int32_t cwin;
963
964 if (tcp_do_better_lr) {
965 cwin = tp->snd_cwnd - tcp_flight_size(tp);
966 } else {
967 cwin = tp->snd_cwnd -
968 (tp->snd_nxt - tp->sack_newdata) -
969 sack_bytes_rxmt;
970 }
971 if (cwin < 0) {
972 cwin = 0;
973 }
974 /*
975 * We are inside of a SACK recovery episode and are
976 * sending new data, having retransmitted all the
977 * data possible in the scoreboard.
978 */
979 len = min(so->so_snd.sb_cc, tp->snd_wnd) - off;
980 /*
981 * Don't remove this (len > 0) check !
982 * We explicitly check for len > 0 here (although it
983 * isn't really necessary), to work around a gcc
984 * optimization issue - to force gcc to compute
985 * len above. Without this check, the computation
986 * of len is bungled by the optimizer.
987 */
988 if (len > 0) {
989 len = imin(len, cwin);
990 } else {
991 len = 0;
992 }
993 /*
994 * At this point SACK recovery can not send any
995 * data from scoreboard or any new data. Check
996 * if we can do a rescue retransmit towards the
997 * tail end of recovery window.
998 */
999 if (len == 0 && cwin > 0 &&
1000 SEQ_LT(tp->snd_fack, tp->snd_recover) &&
1001 !(tp->t_flagsext & TF_RESCUE_RXT)) {
1002 len = min((tp->snd_recover - tp->snd_fack),
1003 tp->t_maxseg);
1004 len = imin(len, cwin);
1005 old_snd_nxt = tp->snd_nxt;
1006 sack_rescue_rxt = TRUE;
1007 tp->snd_nxt = tp->snd_recover - len;
1008 /*
1009 * If FIN has been sent, snd_max
1010 * must have been advanced to cover it.
1011 */
1012 if ((tp->t_flags & TF_SENTFIN) &&
1013 tp->snd_max == tp->snd_recover) {
1014 tp->snd_nxt--;
1015 }
1016
1017 off = tp->snd_nxt - tp->snd_una;
1018 sendalot = 0;
1019 tp->t_flagsext |= TF_RESCUE_RXT;
1020 }
1021 }
1022 }
1023
1024 /*
1025 * Lop off SYN bit if it has already been sent. However, if this
1026 * is SYN-SENT state and if segment contains data and if we don't
1027 * know that foreign host supports TAO, suppress sending segment.
1028 */
1029 if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
1030 if (tp->t_state == TCPS_SYN_RECEIVED && tfo_enabled(tp) && tp->snd_nxt == tp->snd_una + 1) {
1031 /* We are sending the SYN again! */
1032 off--;
1033 len++;
1034 } else {
1035 if (tp->t_state != TCPS_SYN_RECEIVED || tfo_enabled(tp)) {
1036 flags &= ~TH_SYN;
1037 }
1038
1039 off--;
1040 len++;
1041 if (len > 0 && tp->t_state == TCPS_SYN_SENT) {
1042 while (inp->inp_sndinprog_cnt == 0 &&
1043 tp->t_pktlist_head != NULL) {
1044 packetlist = tp->t_pktlist_head;
1045 packchain_listadd = tp->t_lastchain;
1046 packchain_sent++;
1047 TCP_PKTLIST_CLEAR(tp);
1048
1049 error = tcp_ip_output(so, tp, packetlist,
1050 packchain_listadd, tp_inp_options,
1051 (so_options & SO_DONTROUTE),
1052 (sack_rxmit || (sack_bytes_rxmt != 0)),
1053 isipv6);
1054 }
1055
1056 /*
1057 * tcp was closed while we were in ip,
1058 * resume close
1059 */
1060 if (inp->inp_sndinprog_cnt == 0 &&
1061 (tp->t_flags & TF_CLOSING)) {
1062 tp->t_flags &= ~TF_CLOSING;
1063 (void) tcp_close(tp);
1064 } else {
1065 tcp_check_timer_state(tp);
1066 }
1067 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END,
1068 0, 0, 0, 0, 0);
1069 return 0;
1070 }
1071 }
1072 }
1073
1074 /*
1075 * Be careful not to send data and/or FIN on SYN segments.
1076 * This measure is needed to prevent interoperability problems
1077 * with not fully conformant TCP implementations.
1078 *
1079 * In case of TFO, we handle the setting of the len in
1080 * tcp_tfo_check. In case TFO is not enabled, never ever send
1081 * SYN+data.
1082 */
1083 if ((flags & TH_SYN) && !tfo_enabled(tp)) {
1084 len = 0;
1085 flags &= ~TH_FIN;
1086 }
1087
1088 /*
1089 * Don't send a RST with data.
1090 */
1091 if (flags & TH_RST) {
1092 len = 0;
1093 }
1094
1095 if ((flags & TH_SYN) && tp->t_state <= TCPS_SYN_SENT && tfo_enabled(tp)) {
1096 len = tcp_tfo_check(tp, len);
1097 }
1098
1099 /*
1100 * The check here used to be (len < 0). Some times len is zero
1101 * when the congestion window is closed and we need to check
1102 * if persist timer has to be set in that case. But don't set
1103 * persist until connection is established.
1104 */
1105 if (len <= 0 && !(flags & TH_SYN)) {
1106 /*
1107 * If FIN has been sent but not acked,
1108 * but we haven't been called to retransmit,
1109 * len will be < 0. Otherwise, window shrank
1110 * after we sent into it. If window shrank to 0,
1111 * cancel pending retransmit, pull snd_nxt back
1112 * to (closed) window, and set the persist timer
1113 * if it isn't already going. If the window didn't
1114 * close completely, just wait for an ACK.
1115 */
1116 len = 0;
1117 if (sendwin == 0) {
1118 tp->t_timer[TCPT_REXMT] = 0;
1119 tp->t_timer[TCPT_PTO] = 0;
1120 TCP_RESET_REXMT_STATE(tp);
1121 tp->snd_nxt = tp->snd_una;
1122 off = 0;
1123 if (tp->t_timer[TCPT_PERSIST] == 0) {
1124 tcp_setpersist(tp);
1125 }
1126 }
1127 }
1128
1129 /*
1130 * Automatic sizing of send socket buffer. Increase the send
1131 * socket buffer size if all of the following criteria are met
1132 * 1. the receiver has enough buffer space for this data
1133 * 2. send buffer is filled to 7/8th with data (so we actually
1134 * have data to make use of it);
1135 * 3. our send window (slow start and congestion controlled) is
1136 * larger than sent but unacknowledged data in send buffer.
1137 */
1138 if (!INP_WAIT_FOR_IF_FEEDBACK(inp) && !IN_FASTRECOVERY(tp) &&
1139 (so->so_snd.sb_flags & (SB_AUTOSIZE | SB_TRIM)) == SB_AUTOSIZE &&
1140 tcp_cansbgrow(&so->so_snd)) {
1141 if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat &&
1142 so->so_snd.sb_cc >= (so->so_snd.sb_hiwat / 8 * 7) &&
1143 sendwin >= (so->so_snd.sb_cc - (tp->snd_nxt - tp->snd_una))) {
1144 if (sbreserve(&so->so_snd,
1145 min(so->so_snd.sb_hiwat + tcp_autosndbuf_inc,
1146 tcp_autosndbuf_max)) == 1) {
1147 so->so_snd.sb_idealsize = so->so_snd.sb_hiwat;
1148 }
1149 }
1150 }
1151
1152 /*
1153 * Truncate to the maximum segment length or enable TCP Segmentation
1154 * Offloading (if supported by hardware) and ensure that FIN is removed
1155 * if the length no longer contains the last data byte.
1156 *
1157 * TSO may only be used if we are in a pure bulk sending state.
1158 * The presence of TCP-MD5, SACK retransmits, SACK advertizements,
1159 * filters and IP options, as well as disabling hardware checksum
1160 * offload prevent using TSO. With TSO the TCP header is the same
1161 * (except for the sequence number) for all generated packets. This
1162 * makes it impossible to transmit any options which vary per generated
1163 * segment or packet.
1164 *
1165 * The length of TSO bursts is limited to TCP_MAXWIN. That limit and
1166 * removal of FIN (if not already catched here) are handled later after
1167 * the exact length of the TCP options are known.
1168 */
1169 #if IPSEC
1170 /*
1171 * Pre-calculate here as we save another lookup into the darknesses
1172 * of IPsec that way and can actually decide if TSO is ok.
1173 */
1174 if (ipsec_bypass == 0) {
1175 ipsec_optlen = (unsigned int)ipsec_hdrsiz_tcp(tp);
1176 }
1177 #endif
1178 if (len > tp->t_maxseg) {
1179 if ((tp->t_flags & TF_TSO) && tcp_do_tso && hwcksum_tx &&
1180 kipf_count == 0 &&
1181 tp->rcv_numsacks == 0 && sack_rxmit == 0 &&
1182 sack_bytes_rxmt == 0 &&
1183 inp->inp_options == NULL &&
1184 inp->in6p_options == NULL
1185 #if IPSEC
1186 && ipsec_optlen == 0
1187 #endif
1188 ) {
1189 tso = 1;
1190 sendalot = 0;
1191 } else {
1192 len = tp->t_maxseg;
1193 sendalot = 1;
1194 tso = 0;
1195 }
1196 } else {
1197 tso = 0;
1198 }
1199
1200 /* Send one segment or less as a tail loss probe */
1201 if (tp->t_flagsext & TF_SENT_TLPROBE) {
1202 len = min(len, tp->t_maxseg);
1203 sendalot = 0;
1204 tso = 0;
1205 }
1206
1207 #if MPTCP
1208 if (so->so_flags & SOF_MP_SUBFLOW && off < 0) {
1209 os_log_error(mptcp_log_handle, "%s - %lx: offset is negative! len %d off %d\n",
1210 __func__, (unsigned long)VM_KERNEL_ADDRPERM(tp->t_mpsub->mpts_mpte),
1211 len, off);
1212 }
1213
1214 if ((so->so_flags & SOF_MP_SUBFLOW) &&
1215 !(tp->t_mpflags & TMPF_TCP_FALLBACK)) {
1216 int newlen = len;
1217 struct mptcb *mp_tp = tptomptp(tp);
1218 if (tp->t_state >= TCPS_ESTABLISHED &&
1219 (tp->t_mpflags & TMPF_SND_MPPRIO ||
1220 tp->t_mpflags & TMPF_SND_REM_ADDR ||
1221 tp->t_mpflags & TMPF_SND_MPFAIL ||
1222 (tp->t_mpflags & TMPF_SND_KEYS &&
1223 mp_tp->mpt_version == MPTCP_VERSION_0) ||
1224 tp->t_mpflags & TMPF_SND_JACK ||
1225 tp->t_mpflags & TMPF_MPTCP_ECHO_ADDR)) {
1226 if (len > 0) {
1227 len = 0;
1228 tso = 0;
1229 }
1230 /*
1231 * On a new subflow, don't try to send again, because
1232 * we are still waiting for the fourth ack.
1233 */
1234 if (!(tp->t_mpflags & TMPF_PREESTABLISHED)) {
1235 sendalot = 1;
1236 }
1237 mptcp_acknow = TRUE;
1238 } else {
1239 mptcp_acknow = FALSE;
1240 }
1241 /*
1242 * The contiguous bytes in the subflow socket buffer can be
1243 * discontiguous at the MPTCP level. Since only one DSS
1244 * option can be sent in one packet, reduce length to match
1245 * the contiguous MPTCP level. Set sendalot to send remainder.
1246 */
1247 if (len > 0 && off >= 0) {
1248 newlen = mptcp_adj_sendlen(so, off);
1249 }
1250
1251 if (newlen < len) {
1252 len = newlen;
1253 if (len <= tp->t_maxseg) {
1254 tso = 0;
1255 }
1256 }
1257 }
1258 #endif /* MPTCP */
1259
1260 if (sack_rxmit) {
1261 if (SEQ_LT(p->rxmit + len, tp->snd_una + so->so_snd.sb_cc)) {
1262 flags &= ~TH_FIN;
1263 }
1264 } else {
1265 if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc)) {
1266 flags &= ~TH_FIN;
1267 }
1268 }
1269 /*
1270 * Compare available window to amount of window
1271 * known to peer (as advertised window less
1272 * next expected input). If the difference is at least two
1273 * max size segments, or at least 25% of the maximum possible
1274 * window, then want to send a window update to peer.
1275 */
1276 recwin = tcp_sbspace(tp);
1277
1278 if (!(so->so_flags & SOF_MP_SUBFLOW)) {
1279 if (recwin < (int32_t)(so->so_rcv.sb_hiwat / 4) &&
1280 recwin < (int)tp->t_maxseg) {
1281 recwin = 0;
1282 }
1283 } else {
1284 struct mptcb *mp_tp = tptomptp(tp);
1285 struct socket *mp_so = mptetoso(mp_tp->mpt_mpte);
1286
1287 if (recwin < (int32_t)(mp_so->so_rcv.sb_hiwat / 4) &&
1288 recwin < (int)tp->t_maxseg) {
1289 recwin = 0;
1290 }
1291 }
1292
1293 #if TRAFFIC_MGT
1294 if (tcp_recv_bg == 1 || IS_TCP_RECV_BG(so)) {
1295 /*
1296 * Timestamp MUST be supported to use rledbat unless we haven't
1297 * yet negotiated it.
1298 */
1299 if (TCP_RLEDBAT_ENABLED(tp) || (tcp_rledbat && tp->t_state <
1300 TCPS_ESTABLISHED)) {
1301 if (recwin > 0 && tcp_cc_rledbat.get_rlwin != NULL) {
1302 /* Min of flow control window and rledbat window */
1303 recwin = imin(recwin, tcp_cc_rledbat.get_rlwin(tp));
1304 }
1305 } else if (recwin > 0 && tcp_recv_throttle(tp)) {
1306 uint32_t min_iaj_win = tcp_min_iaj_win * tp->t_maxseg;
1307 uint32_t bg_rwintop = tp->rcv_adv;
1308 if (SEQ_LT(bg_rwintop, tp->rcv_nxt + min_iaj_win)) {
1309 bg_rwintop = tp->rcv_nxt + min_iaj_win;
1310 }
1311 recwin = imin((int32_t)(bg_rwintop - tp->rcv_nxt),
1312 recwin);
1313 if (recwin < 0) {
1314 recwin = 0;
1315 }
1316 }
1317 }
1318 #endif /* TRAFFIC_MGT */
1319
1320 if (recwin > (int32_t)(TCP_MAXWIN << tp->rcv_scale)) {
1321 recwin = (int32_t)(TCP_MAXWIN << tp->rcv_scale);
1322 }
1323
1324 if (!(so->so_flags & SOF_MP_SUBFLOW)) {
1325 if (recwin < (int32_t)(tp->rcv_adv - tp->rcv_nxt)) {
1326 recwin = (int32_t)(tp->rcv_adv - tp->rcv_nxt);
1327 }
1328 } else {
1329 struct mptcb *mp_tp = tptomptp(tp);
1330 int64_t recwin_announced = (int64_t)(mp_tp->mpt_rcvadv - mp_tp->mpt_rcvnxt);
1331
1332 /* Don't remove what we announced at the MPTCP-layer */
1333 VERIFY(recwin_announced < INT32_MAX && recwin_announced > INT32_MIN);
1334 if (recwin < (int32_t)recwin_announced) {
1335 recwin = (int32_t)recwin_announced;
1336 }
1337 }
1338
1339 /*
1340 * Sender silly window avoidance. We transmit under the following
1341 * conditions when len is non-zero:
1342 *
1343 * - we've timed out (e.g. persist timer)
1344 * - we need to retransmit
1345 * - We have a full segment (or more with TSO)
1346 * - This is the last buffer in a write()/send() and we are
1347 * either idle or running NODELAY
1348 * - we have more then 1/2 the maximum send window's worth of
1349 * data (receiver may be limited the window size)
1350 */
1351 if (len) {
1352 if (tp->t_flagsext & TF_FORCE) {
1353 goto send;
1354 }
1355 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
1356 goto send;
1357 }
1358 if (sack_rxmit) {
1359 goto send;
1360 }
1361
1362 /*
1363 * If this here is the first segment after SYN/ACK and TFO
1364 * is being used, then we always send it, regardless of Nagle,...
1365 */
1366 if (tp->t_state == TCPS_SYN_RECEIVED &&
1367 tfo_enabled(tp) &&
1368 (tp->t_tfo_flags & TFO_F_COOKIE_VALID) &&
1369 tp->snd_nxt == tp->iss + 1) {
1370 goto send;
1371 }
1372
1373 /*
1374 * Send new data on the connection only if it is
1375 * not flow controlled
1376 */
1377 if (!INP_WAIT_FOR_IF_FEEDBACK(inp) ||
1378 tp->t_state != TCPS_ESTABLISHED) {
1379 if (len >= tp->t_maxseg) {
1380 goto send;
1381 }
1382
1383 if (!(tp->t_flags & TF_MORETOCOME) &&
1384 (idle || tp->t_flags & TF_NODELAY ||
1385 (tp->t_flags & TF_MAXSEGSNT) ||
1386 ALLOW_LIMITED_TRANSMIT(tp)) &&
1387 (tp->t_flags & TF_NOPUSH) == 0 &&
1388 (len + off >= so->so_snd.sb_cc ||
1389 /*
1390 * MPTCP needs to respect the DSS-mappings. So, it
1391 * may be sending data that *could* have been
1392 * coalesced, but cannot because of
1393 * mptcp_adj_sendlen().
1394 */
1395 so->so_flags & SOF_MP_SUBFLOW)) {
1396 goto send;
1397 }
1398 if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
1399 goto send;
1400 }
1401 } else {
1402 tcpstat.tcps_fcholdpacket++;
1403 }
1404 }
1405
1406 if (recwin > 0) {
1407 /*
1408 * "adv" is the amount we can increase the window,
1409 * taking into account that we are limited by
1410 * TCP_MAXWIN << tp->rcv_scale.
1411 */
1412 int32_t adv, oldwin = 0;
1413 adv = imin(recwin, (int)TCP_MAXWIN << tp->rcv_scale) -
1414 (tp->rcv_adv - tp->rcv_nxt);
1415
1416 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
1417 oldwin = tp->rcv_adv - tp->rcv_nxt;
1418 }
1419
1420 if (tcp_ack_strategy == TCP_ACK_STRATEGY_LEGACY) {
1421 if (adv >= (int32_t) (2 * tp->t_maxseg)) {
1422 /*
1423 * Update only if the resulting scaled value of
1424 * the window changed, or if there is a change in
1425 * the sequence since the last ack. This avoids
1426 * what appears as dupe ACKS (see rdar://5640997)
1427 *
1428 * If streaming is detected avoid sending too many
1429 * window updates. We will depend on the delack
1430 * timer to send a window update when needed.
1431 *
1432 * If there is more data to read, don't send an ACK.
1433 * Otherwise we will end up sending many ACKs if the
1434 * application is doing micro-reads.
1435 */
1436 if (!(tp->t_flags & TF_STRETCHACK) &&
1437 (tp->last_ack_sent != tp->rcv_nxt ||
1438 ((oldwin + adv) >> tp->rcv_scale) >
1439 (oldwin >> tp->rcv_scale))) {
1440 goto send;
1441 }
1442 }
1443 } else {
1444 if (adv >= (int32_t) (2 * tp->t_maxseg)) {
1445 /*
1446 * ACK every second full-sized segment, if the
1447 * ACK is advancing or the window becomes bigger
1448 */
1449 if (so->so_rcv.sb_cc < so->so_rcv.sb_lowat &&
1450 (tp->last_ack_sent != tp->rcv_nxt ||
1451 ((oldwin + adv) >> tp->rcv_scale) >
1452 (oldwin >> tp->rcv_scale))) {
1453 goto send;
1454 }
1455 } else if (tp->t_flags & TF_DELACK) {
1456 /*
1457 * If we delayed the ACK and the window
1458 * is not advancing by a lot (< 2MSS), ACK
1459 * immediately if the last incoming packet had
1460 * the push flag set and we emptied the buffer.
1461 *
1462 * This takes care of a sender doing small
1463 * repeated writes with Nagle enabled.
1464 */
1465 if (so->so_rcv.sb_cc == 0 &&
1466 tp->last_ack_sent != tp->rcv_nxt &&
1467 (tp->t_flagsext & TF_LAST_IS_PSH)) {
1468 goto send;
1469 }
1470 }
1471 }
1472 if (4 * adv >= (int32_t) so->so_rcv.sb_hiwat) {
1473 goto send;
1474 }
1475
1476 /*
1477 * Make sure that the delayed ack timer is set if
1478 * we delayed sending a window update because of
1479 * streaming detection.
1480 */
1481 if (tcp_ack_strategy == TCP_ACK_STRATEGY_LEGACY &&
1482 (tp->t_flags & TF_STRETCHACK) &&
1483 !(tp->t_flags & TF_DELACK)) {
1484 tp->t_flags |= TF_DELACK;
1485 tp->t_timer[TCPT_DELACK] =
1486 OFFSET_FROM_START(tp, tcp_delack);
1487 }
1488 }
1489
1490 /*
1491 * Send if we owe the peer an ACK, RST, SYN, or urgent data. ACKNOW
1492 * is also a catch-all for the retransmit timer timeout case.
1493 */
1494 if (tp->t_flags & TF_ACKNOW) {
1495 if (tp->t_forced_acks > 0) {
1496 tp->t_forced_acks--;
1497 }
1498 goto send;
1499 }
1500 if ((flags & TH_RST) || (flags & TH_SYN)) {
1501 goto send;
1502 }
1503 if (SEQ_GT(tp->snd_up, tp->snd_una)) {
1504 goto send;
1505 }
1506 #if MPTCP
1507 if (mptcp_acknow) {
1508 goto send;
1509 }
1510 #endif /* MPTCP */
1511 /*
1512 * If our state indicates that FIN should be sent
1513 * and we have not yet done so, then we need to send.
1514 */
1515 if ((flags & TH_FIN) &&
1516 (!(tp->t_flags & TF_SENTFIN) || tp->snd_nxt == tp->snd_una)) {
1517 goto send;
1518 }
1519 /*
1520 * In SACK, it is possible for tcp_output to fail to send a segment
1521 * after the retransmission timer has been turned off. Make sure
1522 * that the retransmission timer is set.
1523 */
1524 if (SACK_ENABLED(tp) && (tp->t_state >= TCPS_ESTABLISHED) &&
1525 SEQ_GT(tp->snd_max, tp->snd_una) &&
1526 tp->t_timer[TCPT_REXMT] == 0 &&
1527 tp->t_timer[TCPT_PERSIST] == 0) {
1528 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp,
1529 tp->t_rxtcur);
1530 goto just_return;
1531 }
1532 /*
1533 * TCP window updates are not reliable, rather a polling protocol
1534 * using ``persist'' packets is used to insure receipt of window
1535 * updates. The three ``states'' for the output side are:
1536 * idle not doing retransmits or persists
1537 * persisting to move a small or zero window
1538 * (re)transmitting and thereby not persisting
1539 *
1540 * tp->t_timer[TCPT_PERSIST]
1541 * is set when we are in persist state.
1542 * tp->t_force
1543 * is set when we are called to send a persist packet.
1544 * tp->t_timer[TCPT_REXMT]
1545 * is set when we are retransmitting
1546 * The output side is idle when both timers are zero.
1547 *
1548 * If send window is too small, there is data to transmit, and no
1549 * retransmit or persist is pending, then go to persist state.
1550 * If nothing happens soon, send when timer expires:
1551 * if window is nonzero, transmit what we can,
1552 * otherwise force out a byte.
1553 */
1554 if (so->so_snd.sb_cc && tp->t_timer[TCPT_REXMT] == 0 &&
1555 tp->t_timer[TCPT_PERSIST] == 0) {
1556 TCP_RESET_REXMT_STATE(tp);
1557 tcp_setpersist(tp);
1558 }
1559 just_return:
1560 /*
1561 * If there is no reason to send a segment, just return.
1562 * but if there is some packets left in the packet list, send them now.
1563 */
1564 while (inp->inp_sndinprog_cnt == 0 &&
1565 tp->t_pktlist_head != NULL) {
1566 packetlist = tp->t_pktlist_head;
1567 packchain_listadd = tp->t_lastchain;
1568 packchain_sent++;
1569 TCP_PKTLIST_CLEAR(tp);
1570
1571 error = tcp_ip_output(so, tp, packetlist,
1572 packchain_listadd,
1573 tp_inp_options, (so_options & SO_DONTROUTE),
1574 (sack_rxmit || (sack_bytes_rxmt != 0)), isipv6);
1575 }
1576 /* tcp was closed while we were in ip; resume close */
1577 if (inp->inp_sndinprog_cnt == 0 &&
1578 (tp->t_flags & TF_CLOSING)) {
1579 tp->t_flags &= ~TF_CLOSING;
1580 (void) tcp_close(tp);
1581 } else {
1582 tcp_check_timer_state(tp);
1583 }
1584 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
1585 return 0;
1586
1587 send:
1588 /*
1589 * Set TF_MAXSEGSNT flag if the segment size is greater than
1590 * the max segment size.
1591 */
1592 if (len > 0) {
1593 do_not_compress = TRUE;
1594
1595 if (len >= tp->t_maxseg) {
1596 tp->t_flags |= TF_MAXSEGSNT;
1597 } else {
1598 tp->t_flags &= ~TF_MAXSEGSNT;
1599 }
1600 }
1601 /*
1602 * Before ESTABLISHED, force sending of initial options
1603 * unless TCP set not to do any options.
1604 * NOTE: we assume that the IP/TCP header plus TCP options
1605 * always fit in a single mbuf, leaving room for a maximum
1606 * link header, i.e.
1607 * max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
1608 */
1609 optlen = 0;
1610 if (isipv6) {
1611 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1612 } else {
1613 hdrlen = sizeof(struct tcpiphdr);
1614 }
1615 if (flags & TH_SYN) {
1616 tp->snd_nxt = tp->iss;
1617 if ((tp->t_flags & TF_NOOPT) == 0) {
1618 u_short mss;
1619
1620 opt[0] = TCPOPT_MAXSEG;
1621 opt[1] = TCPOLEN_MAXSEG;
1622 mss = htons((u_short) tcp_mssopt(tp));
1623 (void)memcpy(opt + 2, &mss, sizeof(mss));
1624 optlen = TCPOLEN_MAXSEG;
1625
1626 if ((tp->t_flags & TF_REQ_SCALE) &&
1627 ((flags & TH_ACK) == 0 ||
1628 (tp->t_flags & TF_RCVD_SCALE))) {
1629 *((u_int32_t *)(void *)(opt + optlen)) = htonl(
1630 TCPOPT_NOP << 24 |
1631 TCPOPT_WINDOW << 16 |
1632 TCPOLEN_WINDOW << 8 |
1633 tp->request_r_scale);
1634 optlen += 4;
1635 }
1636 #if MPTCP
1637 if (mptcp_enable && (so->so_flags & SOF_MP_SUBFLOW)) {
1638 optlen = mptcp_setup_syn_opts(so, opt, optlen);
1639 }
1640 #endif /* MPTCP */
1641 }
1642 }
1643
1644 /*
1645 * Send a timestamp and echo-reply if this is a SYN and our side
1646 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
1647 * and our peer have sent timestamps in our SYN's.
1648 */
1649 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
1650 (flags & TH_RST) == 0 &&
1651 ((flags & TH_ACK) == 0 ||
1652 (tp->t_flags & TF_RCVD_TSTMP))) {
1653 u_int32_t *lp = (u_int32_t *)(void *)(opt + optlen);
1654
1655 /* Form timestamp option as shown in appendix A of RFC 1323. */
1656 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
1657 *lp++ = htonl(tcp_now + tp->t_ts_offset);
1658 *lp = htonl(tp->ts_recent);
1659 optlen += TCPOLEN_TSTAMP_APPA;
1660 }
1661
1662 if (SACK_ENABLED(tp) && ((tp->t_flags & TF_NOOPT) == 0)) {
1663 /*
1664 * Tack on the SACK permitted option *last*.
1665 * And do padding of options after tacking this on.
1666 * This is because of MSS, TS, WinScale and Signatures are
1667 * all present, we have just 2 bytes left for the SACK
1668 * permitted option, which is just enough.
1669 */
1670 /*
1671 * If this is the first SYN of connection (not a SYN
1672 * ACK), include SACK permitted option. If this is a
1673 * SYN ACK, include SACK permitted option if peer has
1674 * already done so. This is only for active connect,
1675 * since the syncache takes care of the passive connect.
1676 */
1677 if ((flags & TH_SYN) &&
1678 (!(flags & TH_ACK) || (tp->t_flags & TF_SACK_PERMIT))) {
1679 u_char *bp;
1680 bp = (u_char *)opt + optlen;
1681
1682 *bp++ = TCPOPT_SACK_PERMITTED;
1683 *bp++ = TCPOLEN_SACK_PERMITTED;
1684 optlen += TCPOLEN_SACK_PERMITTED;
1685 }
1686 }
1687 #if MPTCP
1688 if (so->so_flags & SOF_MP_SUBFLOW) {
1689 /*
1690 * Its important to piggyback acks with data as ack only packets
1691 * may get lost and data packets that don't send Data ACKs
1692 * still advance the subflow level ACK and therefore make it
1693 * hard for the remote end to recover in low cwnd situations.
1694 */
1695 if (len != 0) {
1696 tp->t_mpflags |= (TMPF_SEND_DSN |
1697 TMPF_MPTCP_ACKNOW);
1698 } else {
1699 tp->t_mpflags |= TMPF_MPTCP_ACKNOW;
1700 }
1701 optlen = mptcp_setup_opts(tp, off, &opt[0], optlen, flags,
1702 len, &mptcp_acknow, &do_not_compress);
1703 tp->t_mpflags &= ~TMPF_SEND_DSN;
1704 }
1705 #endif /* MPTCP */
1706
1707 if (tfo_enabled(tp) && !(tp->t_flags & TF_NOOPT) &&
1708 (flags & (TH_SYN | TH_ACK)) == TH_SYN) {
1709 optlen += tcp_tfo_write_cookie(tp, optlen, len, opt);
1710 }
1711
1712 if (tfo_enabled(tp) &&
1713 (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK) &&
1714 (tp->t_tfo_flags & TFO_F_OFFER_COOKIE)) {
1715 optlen += tcp_tfo_write_cookie_rep(tp, optlen, opt);
1716 }
1717
1718 if (SACK_ENABLED(tp) && ((tp->t_flags & TF_NOOPT) == 0)) {
1719 /*
1720 * Send SACKs if necessary. This should be the last
1721 * option processed. Only as many SACKs are sent as
1722 * are permitted by the maximum options size.
1723 *
1724 * In general, SACK blocks consume 8*n+2 bytes.
1725 * So a full size SACK blocks option is 34 bytes
1726 * (to generate 4 SACK blocks). At a minimum,
1727 * we need 10 bytes (to generate 1 SACK block).
1728 * If TCP Timestamps (12 bytes) and TCP Signatures
1729 * (18 bytes) are both present, we'll just have
1730 * 10 bytes for SACK options 40 - (12 + 18).
1731 */
1732 if (TCPS_HAVEESTABLISHED(tp->t_state) &&
1733 (tp->t_flags & TF_SACK_PERMIT) &&
1734 (tp->rcv_numsacks > 0 || TCP_SEND_DSACK_OPT(tp)) &&
1735 MAX_TCPOPTLEN - optlen - 2 >= TCPOLEN_SACK) {
1736 int nsack, padlen;
1737 u_char *bp = (u_char *)opt + optlen;
1738 u_int32_t *lp;
1739
1740 nsack = (MAX_TCPOPTLEN - optlen - 2) / TCPOLEN_SACK;
1741 nsack = min(nsack, (tp->rcv_numsacks +
1742 (TCP_SEND_DSACK_OPT(tp) ? 1 : 0)));
1743 sackoptlen = (2 + nsack * TCPOLEN_SACK);
1744 VERIFY(sackoptlen < UINT8_MAX);
1745
1746 /*
1747 * First we need to pad options so that the
1748 * SACK blocks can start at a 4-byte boundary
1749 * (sack option and length are at a 2 byte offset).
1750 */
1751 padlen = (MAX_TCPOPTLEN - optlen - sackoptlen) % 4;
1752 optlen += padlen;
1753 while (padlen-- > 0) {
1754 *bp++ = TCPOPT_NOP;
1755 }
1756
1757 tcpstat.tcps_sack_send_blocks++;
1758 *bp++ = TCPOPT_SACK;
1759 *bp++ = (uint8_t)sackoptlen;
1760 lp = (u_int32_t *)(void *)bp;
1761
1762 /*
1763 * First block of SACK option should represent
1764 * DSACK. Prefer to send SACK information if there
1765 * is space for only one SACK block. This will
1766 * allow for faster recovery.
1767 */
1768 if (TCP_SEND_DSACK_OPT(tp) && nsack > 0 &&
1769 (tp->rcv_numsacks == 0 || nsack > 1)) {
1770 *lp++ = htonl(tp->t_dsack_lseq);
1771 *lp++ = htonl(tp->t_dsack_rseq);
1772 tcpstat.tcps_dsack_sent++;
1773 tp->t_dsack_sent++;
1774 nsack--;
1775 }
1776 VERIFY(nsack == 0 || tp->rcv_numsacks >= nsack);
1777 for (i = 0; i < nsack; i++) {
1778 struct sackblk sack = tp->sackblks[i];
1779 *lp++ = htonl(sack.start);
1780 *lp++ = htonl(sack.end);
1781 }
1782 optlen += sackoptlen;
1783 }
1784 }
1785
1786 /* Pad TCP options to a 4 byte boundary */
1787 if (optlen < MAX_TCPOPTLEN && (optlen % sizeof(u_int32_t))) {
1788 int pad = sizeof(u_int32_t) - (optlen % sizeof(u_int32_t));
1789 u_char *bp = (u_char *)opt + optlen;
1790
1791 optlen += pad;
1792 while (pad) {
1793 *bp++ = TCPOPT_EOL;
1794 pad--;
1795 }
1796 }
1797
1798 /*
1799 * RFC 3168 states that:
1800 * - If you ever sent an ECN-setup SYN/SYN-ACK you must be prepared
1801 * to handle the TCP ECE flag, even if you also later send a
1802 * non-ECN-setup SYN/SYN-ACK.
1803 * - If you ever send a non-ECN-setup SYN/SYN-ACK, you must not set
1804 * the ip ECT flag.
1805 *
1806 * It is not clear how the ECE flag would ever be set if you never
1807 * set the IP ECT flag on outbound packets. All the same, we use
1808 * the TE_SETUPSENT to indicate that we have committed to handling
1809 * the TCP ECE flag correctly. We use the TE_SENDIPECT to indicate
1810 * whether or not we should set the IP ECT flag on outbound packet
1811 *
1812 * For a SYN-ACK, send an ECN setup SYN-ACK
1813 */
1814 if ((flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK) &&
1815 (tp->ecn_flags & TE_ENABLE_ECN)) {
1816 if (tp->ecn_flags & TE_SETUPRECEIVED) {
1817 if (tcp_send_ecn_flags_on_syn(tp)) {
1818 /*
1819 * Setting TH_ECE makes this an ECN-setup
1820 * SYN-ACK
1821 */
1822 flags |= TH_ECE;
1823
1824 /*
1825 * Record that we sent the ECN-setup and
1826 * default to setting IP ECT.
1827 */
1828 tp->ecn_flags |= (TE_SETUPSENT | TE_SENDIPECT);
1829 tcpstat.tcps_ecn_server_setup++;
1830 tcpstat.tcps_ecn_server_success++;
1831 } else {
1832 /*
1833 * We sent an ECN-setup SYN-ACK but it was
1834 * dropped. Fallback to non-ECN-setup
1835 * SYN-ACK and clear flag to indicate that
1836 * we should not send data with IP ECT set
1837 *
1838 * Pretend we didn't receive an
1839 * ECN-setup SYN.
1840 *
1841 * We already incremented the counter
1842 * assuming that the ECN setup will
1843 * succeed. Decrementing here
1844 * tcps_ecn_server_success to correct it.
1845 */
1846 if (tp->ecn_flags & TE_SETUPSENT) {
1847 tcpstat.tcps_ecn_lost_synack++;
1848 tcpstat.tcps_ecn_server_success--;
1849 tp->ecn_flags |= TE_LOST_SYNACK;
1850 }
1851
1852 tp->ecn_flags &=
1853 ~(TE_SETUPRECEIVED | TE_SENDIPECT |
1854 TE_SENDCWR);
1855 }
1856 }
1857 } else if ((flags & (TH_SYN | TH_ACK)) == TH_SYN &&
1858 (tp->ecn_flags & TE_ENABLE_ECN)) {
1859 if (tcp_send_ecn_flags_on_syn(tp)) {
1860 /*
1861 * Setting TH_ECE and TH_CWR makes this an
1862 * ECN-setup SYN
1863 */
1864 flags |= (TH_ECE | TH_CWR);
1865 tcpstat.tcps_ecn_client_setup++;
1866 tp->ecn_flags |= TE_CLIENT_SETUP;
1867
1868 /*
1869 * Record that we sent the ECN-setup and default to
1870 * setting IP ECT.
1871 */
1872 tp->ecn_flags |= (TE_SETUPSENT | TE_SENDIPECT);
1873 } else {
1874 /*
1875 * We sent an ECN-setup SYN but it was dropped.
1876 * Fall back to non-ECN and clear flag indicating
1877 * we should send data with IP ECT set.
1878 */
1879 if (tp->ecn_flags & TE_SETUPSENT) {
1880 tcpstat.tcps_ecn_lost_syn++;
1881 tp->ecn_flags |= TE_LOST_SYN;
1882 }
1883 tp->ecn_flags &= ~TE_SENDIPECT;
1884 }
1885 }
1886
1887 /*
1888 * Check if we should set the TCP CWR flag.
1889 * CWR flag is sent when we reduced the congestion window because
1890 * we received a TCP ECE or we performed a fast retransmit. We
1891 * never set the CWR flag on retransmitted packets. We only set
1892 * the CWR flag on data packets. Pure acks don't have this set.
1893 */
1894 if ((tp->ecn_flags & TE_SENDCWR) != 0 && len != 0 &&
1895 !SEQ_LT(tp->snd_nxt, tp->snd_max) && !sack_rxmit) {
1896 flags |= TH_CWR;
1897 tp->ecn_flags &= ~TE_SENDCWR;
1898 }
1899
1900 /*
1901 * Check if we should set the TCP ECE flag.
1902 */
1903 if ((tp->ecn_flags & TE_SENDECE) != 0 && len == 0) {
1904 flags |= TH_ECE;
1905 tcpstat.tcps_ecn_sent_ece++;
1906 }
1907
1908
1909 hdrlen += optlen;
1910
1911 /* Reset DSACK sequence numbers */
1912 tp->t_dsack_lseq = 0;
1913 tp->t_dsack_rseq = 0;
1914
1915 if (isipv6) {
1916 ipoptlen = ip6_optlen(inp);
1917 } else {
1918 if (tp_inp_options) {
1919 ipoptlen = tp_inp_options->m_len -
1920 offsetof(struct ipoption, ipopt_list);
1921 } else {
1922 ipoptlen = 0;
1923 }
1924 }
1925 #if IPSEC
1926 ipoptlen += ipsec_optlen;
1927 #endif
1928
1929 /*
1930 * Adjust data length if insertion of options will
1931 * bump the packet length beyond the t_maxopd length.
1932 * Clear the FIN bit because we cut off the tail of
1933 * the segment.
1934 *
1935 * When doing TSO limit a burst to TCP_MAXWIN minus the
1936 * IP, TCP and Options length to keep ip->ip_len from
1937 * overflowing. Prevent the last segment from being
1938 * fractional thus making them all equal sized and set
1939 * the flag to continue sending. TSO is disabled when
1940 * IP options or IPSEC are present.
1941 */
1942 if (len + optlen + ipoptlen > tp->t_maxopd) {
1943 /*
1944 * If there is still more to send,
1945 * don't close the connection.
1946 */
1947 flags &= ~TH_FIN;
1948 if (tso) {
1949 int32_t tso_maxlen;
1950
1951 tso_maxlen = tp->tso_max_segment_size ?
1952 tp->tso_max_segment_size : TCP_MAXWIN;
1953
1954 /* hdrlen includes optlen */
1955 if (len > tso_maxlen - hdrlen) {
1956 len = tso_maxlen - hdrlen;
1957 sendalot = 1;
1958 } else if (tp->t_flags & TF_NEEDFIN) {
1959 sendalot = 1;
1960 }
1961
1962 if (len % (tp->t_maxopd - optlen) != 0) {
1963 len = len - (len % (tp->t_maxopd - optlen));
1964 sendalot = 1;
1965 }
1966 } else {
1967 len = tp->t_maxopd - optlen - ipoptlen;
1968 sendalot = 1;
1969 }
1970 }
1971
1972 if (max_linkhdr + hdrlen > MCLBYTES) {
1973 panic("tcphdr too big");
1974 }
1975
1976 /* Check if there is enough data in the send socket
1977 * buffer to start measuring bandwidth
1978 */
1979 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
1980 (tp->t_bwmeas != NULL) &&
1981 (tp->t_flagsext & TF_BWMEAS_INPROGRESS) == 0) {
1982 tp->t_bwmeas->bw_size = min(min(
1983 (so->so_snd.sb_cc - (tp->snd_max - tp->snd_una)),
1984 tp->snd_cwnd), tp->snd_wnd);
1985 if (tp->t_bwmeas->bw_minsize > 0 &&
1986 tp->t_bwmeas->bw_size < tp->t_bwmeas->bw_minsize) {
1987 tp->t_bwmeas->bw_size = 0;
1988 }
1989 if (tp->t_bwmeas->bw_maxsize > 0) {
1990 tp->t_bwmeas->bw_size = min(tp->t_bwmeas->bw_size,
1991 tp->t_bwmeas->bw_maxsize);
1992 }
1993 if (tp->t_bwmeas->bw_size > 0) {
1994 tp->t_flagsext |= TF_BWMEAS_INPROGRESS;
1995 tp->t_bwmeas->bw_start = tp->snd_max;
1996 tp->t_bwmeas->bw_ts = tcp_now;
1997 }
1998 }
1999
2000 VERIFY(inp->inp_flowhash != 0);
2001 /*
2002 * Grab a header mbuf, attaching a copy of data to
2003 * be transmitted, and initialize the header from
2004 * the template for sends on this connection.
2005 */
2006 if (len) {
2007 /* Remember what the last head-of-line packet-size was */
2008 if (tp->t_pmtud_lastseg_size == 0 && tp->snd_nxt == tp->snd_una) {
2009 ASSERT(len + optlen + ipoptlen <= IP_MAXPACKET);
2010 tp->t_pmtud_lastseg_size = (uint16_t)(len + optlen + ipoptlen);
2011 }
2012 if ((tp->t_flagsext & TF_FORCE) && len == 1) {
2013 tcpstat.tcps_sndprobe++;
2014 } else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
2015 tcpstat.tcps_sndrexmitpack++;
2016 tcpstat.tcps_sndrexmitbyte += len;
2017 if (nstat_collect) {
2018 nstat_route_tx(inp->inp_route.ro_rt, 1,
2019 len, NSTAT_TX_FLAG_RETRANSMIT);
2020 INP_ADD_STAT(inp, cell, wifi, wired,
2021 txpackets, 1);
2022 INP_ADD_STAT(inp, cell, wifi, wired,
2023 txbytes, len);
2024 tp->t_stat.txretransmitbytes += len;
2025 tp->t_stat.rxmitpkts++;
2026 }
2027 } else {
2028 tcpstat.tcps_sndpack++;
2029 tcpstat.tcps_sndbyte += len;
2030
2031 if (nstat_collect) {
2032 INP_ADD_STAT(inp, cell, wifi, wired,
2033 txpackets, 1);
2034 INP_ADD_STAT(inp, cell, wifi, wired,
2035 txbytes, len);
2036 }
2037 inp_decr_sndbytes_unsent(so, len);
2038 }
2039 inp_set_activity_bitmap(inp);
2040 #if MPTCP
2041 if (tp->t_mpflags & TMPF_MPTCP_TRUE) {
2042 tcpstat.tcps_mp_sndpacks++;
2043 tcpstat.tcps_mp_sndbytes += len;
2044 }
2045 #endif /* MPTCP */
2046 /*
2047 * try to use the new interface that allocates all
2048 * the necessary mbuf hdrs under 1 mbuf lock and
2049 * avoids rescanning the socket mbuf list if
2050 * certain conditions are met. This routine can't
2051 * be used in the following cases...
2052 * 1) the protocol headers exceed the capacity of
2053 * of a single mbuf header's data area (no cluster attached)
2054 * 2) the length of the data being transmitted plus
2055 * the protocol headers fits into a single mbuf header's
2056 * data area (no cluster attached)
2057 */
2058 m = NULL;
2059
2060 /* minimum length we are going to allocate */
2061 allocated_len = MHLEN;
2062 if (MHLEN < hdrlen + max_linkhdr) {
2063 MGETHDR(m, M_DONTWAIT, MT_HEADER);
2064 if (m == NULL) {
2065 error = ENOBUFS;
2066 goto out;
2067 }
2068 MCLGET(m, M_DONTWAIT);
2069 if ((m->m_flags & M_EXT) == 0) {
2070 m_freem(m);
2071 error = ENOBUFS;
2072 goto out;
2073 }
2074 m->m_data += max_linkhdr;
2075 m->m_len = hdrlen;
2076 allocated_len = MCLBYTES;
2077 }
2078 if (len <= allocated_len - hdrlen - max_linkhdr) {
2079 if (m == NULL) {
2080 VERIFY(allocated_len <= MHLEN);
2081 MGETHDR(m, M_DONTWAIT, MT_HEADER);
2082 if (m == NULL) {
2083 error = ENOBUFS;
2084 goto out;
2085 }
2086 m->m_data += max_linkhdr;
2087 m->m_len = hdrlen;
2088 }
2089 /* makes sure we still have data left to be sent at this point */
2090 if (so->so_snd.sb_mb == NULL || off < 0) {
2091 if (m != NULL) {
2092 m_freem(m);
2093 }
2094 error = 0; /* should we return an error? */
2095 goto out;
2096 }
2097 m_copydata(so->so_snd.sb_mb, off, (int) len,
2098 mtod(m, caddr_t) + hdrlen);
2099 m->m_len += len;
2100 } else {
2101 uint32_t copymode;
2102 /*
2103 * Retain packet header metadata at the socket
2104 * buffer if this is is an MPTCP subflow,
2105 * otherwise move it.
2106 */
2107 copymode = M_COPYM_MOVE_HDR;
2108 #if MPTCP
2109 if (so->so_flags & SOF_MP_SUBFLOW) {
2110 copymode = M_COPYM_NOOP_HDR;
2111 }
2112 #endif /* MPTCP */
2113 if (m != NULL) {
2114 m->m_next = m_copym_mode(so->so_snd.sb_mb,
2115 off, (int)len, M_DONTWAIT, copymode);
2116 if (m->m_next == NULL) {
2117 (void) m_free(m);
2118 error = ENOBUFS;
2119 goto out;
2120 }
2121 } else {
2122 /*
2123 * make sure we still have data left
2124 * to be sent at this point
2125 */
2126 if (so->so_snd.sb_mb == NULL) {
2127 error = 0; /* should we return an error? */
2128 goto out;
2129 }
2130
2131 /*
2132 * m_copym_with_hdrs will always return the
2133 * last mbuf pointer and the offset into it that
2134 * it acted on to fullfill the current request,
2135 * whether a valid 'hint' was passed in or not.
2136 */
2137 if ((m = m_copym_with_hdrs(so->so_snd.sb_mb,
2138 off, len, M_DONTWAIT, NULL, NULL,
2139 copymode)) == NULL) {
2140 error = ENOBUFS;
2141 goto out;
2142 }
2143 m->m_data += max_linkhdr;
2144 m->m_len = hdrlen;
2145 }
2146 }
2147 /*
2148 * If we're sending everything we've got, set PUSH.
2149 * (This will keep happy those implementations which only
2150 * give data to the user when a buffer fills or
2151 * a PUSH comes in.)
2152 *
2153 * On SYN-segments we should not add the PUSH-flag.
2154 */
2155 if (off + len == so->so_snd.sb_cc && !(flags & TH_SYN)) {
2156 flags |= TH_PUSH;
2157 }
2158 } else {
2159 if (tp->t_flags & TF_ACKNOW) {
2160 tcpstat.tcps_sndacks++;
2161 } else if (flags & (TH_SYN | TH_FIN | TH_RST)) {
2162 tcpstat.tcps_sndctrl++;
2163 } else if (SEQ_GT(tp->snd_up, tp->snd_una)) {
2164 tcpstat.tcps_sndurg++;
2165 } else {
2166 tcpstat.tcps_sndwinup++;
2167 }
2168
2169 MGETHDR(m, M_DONTWAIT, MT_HEADER); /* MAC-OK */
2170 if (m == NULL) {
2171 error = ENOBUFS;
2172 goto out;
2173 }
2174 if (MHLEN < (hdrlen + max_linkhdr)) {
2175 MCLGET(m, M_DONTWAIT);
2176 if ((m->m_flags & M_EXT) == 0) {
2177 m_freem(m);
2178 error = ENOBUFS;
2179 goto out;
2180 }
2181 }
2182 m->m_data += max_linkhdr;
2183 m->m_len = hdrlen;
2184 }
2185 m->m_pkthdr.rcvif = 0;
2186 m_add_crumb(m, PKT_CRUMB_TCP_OUTPUT);
2187
2188 /* Any flag other than pure-ACK: Do not compress! */
2189 if (flags & ~(TH_ACK)) {
2190 do_not_compress = TRUE;
2191 }
2192
2193 if (tp->rcv_scale == 0) {
2194 do_not_compress = TRUE;
2195 }
2196
2197 if (do_not_compress || (tcp_do_ack_compression == 1 && !cell) || __improbable(!tcp_do_ack_compression)) {
2198 m->m_pkthdr.comp_gencnt = 0;
2199 } else {
2200 if (TSTMP_LT(tp->t_comp_lastinc + tcp_ack_compression_rate, tcp_now)) {
2201 tp->t_comp_gencnt++;
2202 /* 0 means no compression, thus jump this */
2203 if (tp->t_comp_gencnt <= TCP_ACK_COMPRESSION_DUMMY) {
2204 tp->t_comp_gencnt = TCP_ACK_COMPRESSION_DUMMY + 1;
2205 }
2206 tp->t_comp_lastinc = tcp_now;
2207 }
2208 m->m_pkthdr.comp_gencnt = tp->t_comp_gencnt;
2209 }
2210
2211 if (isipv6) {
2212 ip6 = mtod(m, struct ip6_hdr *);
2213 th = (struct tcphdr *)(void *)(ip6 + 1);
2214 tcp_fillheaders(m, tp, ip6, th);
2215 if ((tp->ecn_flags & TE_SENDIPECT) != 0 && len &&
2216 !SEQ_LT(tp->snd_nxt, tp->snd_max) && !sack_rxmit) {
2217 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
2218 }
2219 svc_flags |= PKT_SCF_IPV6;
2220 #if PF_ECN
2221 m_pftag(m)->pftag_hdr = (void *)ip6;
2222 m_pftag(m)->pftag_flags |= PF_TAG_HDR_INET6;
2223 #endif /* PF_ECN */
2224 } else {
2225 ip = mtod(m, struct ip *);
2226 th = (struct tcphdr *)(void *)(ip + 1);
2227 /* this picks up the pseudo header (w/o the length) */
2228 tcp_fillheaders(m, tp, ip, th);
2229 if ((tp->ecn_flags & TE_SENDIPECT) != 0 && len &&
2230 !SEQ_LT(tp->snd_nxt, tp->snd_max) &&
2231 !sack_rxmit && !(flags & TH_SYN)) {
2232 ip->ip_tos |= IPTOS_ECN_ECT0;
2233 }
2234 #if PF_ECN
2235 m_pftag(m)->pftag_hdr = (void *)ip;
2236 m_pftag(m)->pftag_flags |= PF_TAG_HDR_INET;
2237 #endif /* PF_ECN */
2238 }
2239
2240 /*
2241 * Fill in fields, remembering maximum advertised
2242 * window for use in delaying messages about window sizes.
2243 * If resending a FIN, be sure not to use a new sequence number.
2244 */
2245 if ((flags & TH_FIN) && (tp->t_flags & TF_SENTFIN) &&
2246 tp->snd_nxt == tp->snd_max) {
2247 tp->snd_nxt--;
2248 }
2249 /*
2250 * If we are doing retransmissions, then snd_nxt will
2251 * not reflect the first unsent octet. For ACK only
2252 * packets, we do not want the sequence number of the
2253 * retransmitted packet, we want the sequence number
2254 * of the next unsent octet. So, if there is no data
2255 * (and no SYN or FIN), use snd_max instead of snd_nxt
2256 * when filling in ti_seq. But if we are in persist
2257 * state, snd_max might reflect one byte beyond the
2258 * right edge of the window, so use snd_nxt in that
2259 * case, since we know we aren't doing a retransmission.
2260 * (retransmit and persist are mutually exclusive...)
2261 *
2262 * Note the state of this retransmit segment to detect spurious
2263 * retransmissions.
2264 */
2265 if (sack_rxmit == 0) {
2266 if (len || (flags & (TH_SYN | TH_FIN)) ||
2267 tp->t_timer[TCPT_PERSIST]) {
2268 th->th_seq = htonl(tp->snd_nxt);
2269 if (len > 0) {
2270 m->m_pkthdr.tx_start_seq = tp->snd_nxt;
2271 m->m_pkthdr.pkt_flags |= PKTF_START_SEQ;
2272 }
2273 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
2274 if (SACK_ENABLED(tp) && len > 1) {
2275 tcp_rxtseg_insert(tp, tp->snd_nxt,
2276 (tp->snd_nxt + len - 1));
2277 }
2278 if (len > 0) {
2279 m->m_pkthdr.pkt_flags |=
2280 PKTF_TCP_REXMT;
2281 }
2282 }
2283 } else {
2284 th->th_seq = htonl(tp->snd_max);
2285 }
2286 } else {
2287 th->th_seq = htonl(p->rxmit);
2288 if (len > 0) {
2289 m->m_pkthdr.pkt_flags |=
2290 (PKTF_TCP_REXMT | PKTF_START_SEQ);
2291 m->m_pkthdr.tx_start_seq = p->rxmit;
2292 }
2293 tcp_rxtseg_insert(tp, p->rxmit, (p->rxmit + len - 1));
2294 p->rxmit += len;
2295 tp->sackhint.sack_bytes_rexmit += len;
2296 }
2297 th->th_ack = htonl(tp->rcv_nxt);
2298 tp->last_ack_sent = tp->rcv_nxt;
2299 if (optlen) {
2300 bcopy(opt, th + 1, optlen);
2301 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
2302 }
2303 th->th_flags = flags;
2304 th->th_win = htons((u_short) (recwin >> tp->rcv_scale));
2305 tp->t_last_recwin = recwin;
2306 if (!(so->so_flags & SOF_MP_SUBFLOW)) {
2307 if (recwin > 0 && SEQ_LT(tp->rcv_adv, tp->rcv_nxt + recwin)) {
2308 tp->rcv_adv = tp->rcv_nxt + recwin;
2309 }
2310 } else {
2311 struct mptcb *mp_tp = tptomptp(tp);
2312 if (recwin > 0) {
2313 tp->rcv_adv = tp->rcv_nxt + recwin;
2314 }
2315
2316 if (recwin > 0 && MPTCP_SEQ_LT(mp_tp->mpt_rcvadv, mp_tp->mpt_rcvnxt + recwin)) {
2317 mp_tp->mpt_rcvadv = mp_tp->mpt_rcvnxt + recwin;
2318 }
2319 }
2320
2321 /*
2322 * Adjust the RXWIN0SENT flag - indicate that we have advertised
2323 * a 0 window. This may cause the remote transmitter to stall. This
2324 * flag tells soreceive() to disable delayed acknowledgements when
2325 * draining the buffer. This can occur if the receiver is attempting
2326 * to read more data then can be buffered prior to transmitting on
2327 * the connection.
2328 */
2329 if (th->th_win == 0) {
2330 tp->t_flags |= TF_RXWIN0SENT;
2331 } else {
2332 tp->t_flags &= ~TF_RXWIN0SENT;
2333 }
2334
2335 if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
2336 th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
2337 th->th_flags |= TH_URG;
2338 } else {
2339 /*
2340 * If no urgent pointer to send, then we pull
2341 * the urgent pointer to the left edge of the send window
2342 * so that it doesn't drift into the send window on sequence
2343 * number wraparound.
2344 */
2345 tp->snd_up = tp->snd_una; /* drag it along */
2346 }
2347
2348 /*
2349 * Put TCP length in extended header, and then
2350 * checksum extended header and data.
2351 */
2352 m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
2353
2354 /*
2355 * If this is potentially the last packet on the stream, then mark
2356 * it in order to enable some optimizations in the underlying
2357 * layers
2358 */
2359 if (tp->t_state != TCPS_ESTABLISHED &&
2360 (tp->t_state == TCPS_CLOSING || tp->t_state == TCPS_TIME_WAIT
2361 || tp->t_state == TCPS_LAST_ACK || (th->th_flags & TH_RST))) {
2362 m->m_pkthdr.pkt_flags |= PKTF_LAST_PKT;
2363 }
2364
2365 if (isipv6) {
2366 /*
2367 * ip6_plen is not need to be filled now, and will be filled
2368 * in ip6_output.
2369 */
2370 m->m_pkthdr.csum_flags = CSUM_TCPIPV6;
2371 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2372 if (len + optlen) {
2373 th->th_sum = in_addword(th->th_sum,
2374 htons((u_short)(optlen + len)));
2375 }
2376 } else {
2377 m->m_pkthdr.csum_flags = CSUM_TCP;
2378 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2379 if (len + optlen) {
2380 th->th_sum = in_addword(th->th_sum,
2381 htons((u_short)(optlen + len)));
2382 }
2383 }
2384
2385 /*
2386 * Enable TSO and specify the size of the segments.
2387 * The TCP pseudo header checksum is always provided.
2388 */
2389 if (tso) {
2390 if (isipv6) {
2391 m->m_pkthdr.csum_flags |= CSUM_TSO_IPV6;
2392 } else {
2393 m->m_pkthdr.csum_flags |= CSUM_TSO_IPV4;
2394 }
2395
2396 m->m_pkthdr.tso_segsz = tp->t_maxopd - optlen;
2397 } else {
2398 m->m_pkthdr.tso_segsz = 0;
2399 }
2400
2401 /*
2402 * In transmit state, time the transmission and arrange for
2403 * the retransmit. In persist state, just set snd_max.
2404 */
2405 if (!(tp->t_flagsext & TF_FORCE)
2406 || tp->t_timer[TCPT_PERSIST] == 0) {
2407 tcp_seq startseq = tp->snd_nxt;
2408
2409 /*
2410 * Advance snd_nxt over sequence space of this segment.
2411 */
2412 if (flags & (TH_SYN | TH_FIN)) {
2413 if (flags & TH_SYN) {
2414 tp->snd_nxt++;
2415 }
2416 if ((flags & TH_FIN) &&
2417 !(tp->t_flags & TF_SENTFIN)) {
2418 tp->snd_nxt++;
2419 tp->t_flags |= TF_SENTFIN;
2420 }
2421 }
2422 if (sack_rxmit) {
2423 goto timer;
2424 }
2425 if (sack_rescue_rxt == TRUE) {
2426 tp->snd_nxt = old_snd_nxt;
2427 sack_rescue_rxt = FALSE;
2428 tcpstat.tcps_pto_in_recovery++;
2429 } else {
2430 tp->snd_nxt += len;
2431 }
2432 if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
2433 tp->snd_max = tp->snd_nxt;
2434 tp->t_sndtime = tcp_now;
2435 /*
2436 * Time this transmission if not a retransmission and
2437 * not currently timing anything.
2438 */
2439 if (tp->t_rtttime == 0) {
2440 tp->t_rtttime = tcp_now;
2441 tp->t_rtseq = startseq;
2442 tcpstat.tcps_segstimed++;
2443
2444 /* update variables related to pipe ack */
2445 tp->t_pipeack_lastuna = tp->snd_una;
2446 }
2447 }
2448
2449 /*
2450 * Set retransmit timer if not currently set,
2451 * and not doing an ack or a keep-alive probe.
2452 */
2453 timer:
2454 if (tp->t_timer[TCPT_REXMT] == 0 &&
2455 ((sack_rxmit && tp->snd_nxt != tp->snd_max) ||
2456 tp->snd_nxt != tp->snd_una || (flags & TH_FIN))) {
2457 if (tp->t_timer[TCPT_PERSIST]) {
2458 tp->t_timer[TCPT_PERSIST] = 0;
2459 tp->t_persist_stop = 0;
2460 TCP_RESET_REXMT_STATE(tp);
2461 }
2462 tp->t_timer[TCPT_REXMT] =
2463 OFFSET_FROM_START(tp, tp->t_rxtcur);
2464 }
2465
2466 /*
2467 * Set tail loss probe timeout if new data is being
2468 * transmitted. This will be supported only when
2469 * SACK option is enabled on a connection.
2470 *
2471 * Every time new data is sent PTO will get reset.
2472 */
2473 if (tcp_enable_tlp && len != 0 && tp->t_state == TCPS_ESTABLISHED &&
2474 SACK_ENABLED(tp) && !IN_FASTRECOVERY(tp) &&
2475 tp->snd_nxt == tp->snd_max &&
2476 SEQ_GT(tp->snd_nxt, tp->snd_una) &&
2477 tp->t_rxtshift == 0 &&
2478 (tp->t_flagsext & (TF_SENT_TLPROBE | TF_PKTS_REORDERED)) == 0) {
2479 uint32_t pto, srtt;
2480
2481 if (tcp_do_better_lr) {
2482 srtt = tp->t_srtt >> TCP_RTT_SHIFT;
2483 pto = 2 * srtt;
2484 if ((tp->snd_max - tp->snd_una) <= tp->t_maxseg) {
2485 pto += tcp_delack;
2486 } else {
2487 pto += 2;
2488 }
2489 } else {
2490 /*
2491 * Using SRTT alone to set PTO can cause spurious
2492 * retransmissions on wireless networks where there
2493 * is a lot of variance in RTT. Taking variance
2494 * into account will avoid this.
2495 */
2496 srtt = tp->t_srtt >> TCP_RTT_SHIFT;
2497 pto = ((TCP_REXMTVAL(tp)) * 3) >> 1;
2498 pto = max(2 * srtt, pto);
2499 if ((tp->snd_max - tp->snd_una) == tp->t_maxseg) {
2500 pto = max(pto,
2501 (((3 * pto) >> 2) + tcp_delack * 2));
2502 } else {
2503 pto = max(10, pto);
2504 }
2505 }
2506
2507 /* if RTO is less than PTO, choose RTO instead */
2508 if (tp->t_rxtcur < pto) {
2509 pto = tp->t_rxtcur;
2510 }
2511
2512 tp->t_timer[TCPT_PTO] = OFFSET_FROM_START(tp, pto);
2513 }
2514 } else {
2515 /*
2516 * Persist case, update snd_max but since we are in
2517 * persist mode (no window) we do not update snd_nxt.
2518 */
2519 int xlen = len;
2520 if (flags & TH_SYN) {
2521 ++xlen;
2522 }
2523 if ((flags & TH_FIN) &&
2524 !(tp->t_flags & TF_SENTFIN)) {
2525 ++xlen;
2526 tp->t_flags |= TF_SENTFIN;
2527 }
2528 if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max)) {
2529 tp->snd_max = tp->snd_nxt + len;
2530 tp->t_sndtime = tcp_now;
2531 }
2532 }
2533
2534 #if TCPDEBUG
2535 /*
2536 * Trace.
2537 */
2538 if (so_options & SO_DEBUG) {
2539 tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
2540 }
2541 #endif
2542
2543 /*
2544 * Fill in IP length and desired time to live and
2545 * send to IP level. There should be a better way
2546 * to handle ttl and tos; we could keep them in
2547 * the template, but need a way to checksum without them.
2548 */
2549 /*
2550 * m->m_pkthdr.len should have been set before cksum calcuration,
2551 * because in6_cksum() need it.
2552 */
2553 if (isipv6) {
2554 /*
2555 * we separately set hoplimit for every segment, since the
2556 * user might want to change the value via setsockopt.
2557 * Also, desired default hop limit might be changed via
2558 * Neighbor Discovery.
2559 */
2560 ip6->ip6_hlim = in6_selecthlim(inp, inp->in6p_route.ro_rt ?
2561 inp->in6p_route.ro_rt->rt_ifp : NULL);
2562
2563 /* TODO: IPv6 IP6TOS_ECT bit on */
2564 KERNEL_DEBUG(DBG_LAYER_BEG,
2565 ((inp->inp_fport << 16) | inp->inp_lport),
2566 (((inp->in6p_laddr.s6_addr16[0] & 0xffff) << 16) |
2567 (inp->in6p_faddr.s6_addr16[0] & 0xffff)),
2568 sendalot, 0, 0);
2569 } else {
2570 ASSERT(m->m_pkthdr.len <= IP_MAXPACKET);
2571 ip->ip_len = (u_short)m->m_pkthdr.len;
2572 ip->ip_ttl = inp->inp_ip_ttl; /* XXX */
2573 ip->ip_tos |= (inp->inp_ip_tos & ~IPTOS_ECN_MASK);/* XXX */
2574 KERNEL_DEBUG(DBG_LAYER_BEG,
2575 ((inp->inp_fport << 16) | inp->inp_lport),
2576 (((inp->inp_laddr.s_addr & 0xffff) << 16) |
2577 (inp->inp_faddr.s_addr & 0xffff)), 0, 0, 0);
2578 }
2579
2580 /*
2581 * See if we should do MTU discovery.
2582 * Look at the flag updated on the following criterias:
2583 * 1) Path MTU discovery is authorized by the sysctl
2584 * 2) The route isn't set yet (unlikely but could happen)
2585 * 3) The route is up
2586 * 4) the MTU is not locked (if it is, then discovery has been
2587 * disabled for that route)
2588 */
2589 if (!isipv6) {
2590 if (path_mtu_discovery && (tp->t_flags & TF_PMTUD)) {
2591 ip->ip_off |= IP_DF;
2592 }
2593 }
2594
2595 #if NECP
2596 {
2597 necp_kernel_policy_id policy_id;
2598 necp_kernel_policy_id skip_policy_id;
2599 u_int32_t route_rule_id;
2600 u_int32_t pass_flags;
2601 if (!necp_socket_is_allowed_to_send_recv(inp, NULL, 0, &policy_id, &route_rule_id, &skip_policy_id, &pass_flags)) {
2602 TCP_LOG_DROP_NECP(isipv6 ? (void *)ip6 : (void *)ip, th, tp, true);
2603 m_freem(m);
2604 error = EHOSTUNREACH;
2605 goto out;
2606 }
2607 necp_mark_packet_from_socket(m, inp, policy_id, route_rule_id, skip_policy_id, pass_flags);
2608
2609 if (net_qos_policy_restricted != 0) {
2610 necp_socket_update_qos_marking(inp, inp->inp_route.ro_rt, route_rule_id);
2611 }
2612 }
2613 #endif /* NECP */
2614
2615 #if IPSEC
2616 if (inp->inp_sp != NULL) {
2617 ipsec_setsocket(m, so);
2618 }
2619 #endif /*IPSEC*/
2620
2621 /*
2622 * The socket is kept locked while sending out packets in ip_output, even if packet chaining is not active.
2623 */
2624 lost = 0;
2625
2626 /*
2627 * Embed the flow hash in pkt hdr and mark the packet as
2628 * capable of flow controlling
2629 */
2630 m->m_pkthdr.pkt_flowsrc = FLOWSRC_INPCB;
2631 m->m_pkthdr.pkt_flowid = inp->inp_flowhash;
2632 m->m_pkthdr.pkt_flags |= (PKTF_FLOW_ID | PKTF_FLOW_LOCALSRC | PKTF_FLOW_ADV);
2633 m->m_pkthdr.pkt_proto = IPPROTO_TCP;
2634 m->m_pkthdr.tx_tcp_pid = so->last_pid;
2635 if (so->so_flags & SOF_DELEGATED) {
2636 m->m_pkthdr.tx_tcp_e_pid = so->e_pid;
2637 } else {
2638 m->m_pkthdr.tx_tcp_e_pid = 0;
2639 }
2640
2641 m->m_nextpkt = NULL;
2642
2643 if (inp->inp_last_outifp != NULL &&
2644 !(inp->inp_last_outifp->if_flags & IFF_LOOPBACK)) {
2645 /* Hint to prioritize this packet if
2646 * 1. if the packet has no data
2647 * 2. the interface supports transmit-start model and did
2648 * not disable ACK prioritization.
2649 * 3. Only ACK flag is set.
2650 * 4. there is no outstanding data on this connection.
2651 */
2652 if (len == 0 && (inp->inp_last_outifp->if_eflags & (IFEF_TXSTART | IFEF_NOACKPRI)) == IFEF_TXSTART) {
2653 if (th->th_flags == TH_ACK &&
2654 tp->snd_una == tp->snd_max &&
2655 tp->t_timer[TCPT_REXMT] == 0) {
2656 svc_flags |= PKT_SCF_TCP_ACK;
2657 }
2658 if (th->th_flags & TH_SYN) {
2659 svc_flags |= PKT_SCF_TCP_SYN;
2660 }
2661 }
2662 set_packet_service_class(m, so, sotc, svc_flags);
2663 } else {
2664 /*
2665 * Optimization for loopback just set the mbuf
2666 * service class
2667 */
2668 (void) m_set_service_class(m, so_tc2msc(sotc));
2669 }
2670
2671 TCP_LOG_TH_FLAGS(isipv6 ? (void *)ip6 : (void *)ip, th, tp, true,
2672 inp->inp_last_outifp != NULL ? inp->inp_last_outifp :
2673 inp->inp_boundifp);
2674
2675 tp->t_pktlist_sentlen += len;
2676 tp->t_lastchain++;
2677
2678 if (isipv6) {
2679 DTRACE_TCP5(send, struct mbuf *, m, struct inpcb *, inp,
2680 struct ip6 *, ip6, struct tcpcb *, tp, struct tcphdr *,
2681 th);
2682 } else {
2683 DTRACE_TCP5(send, struct mbuf *, m, struct inpcb *, inp,
2684 struct ip *, ip, struct tcpcb *, tp, struct tcphdr *, th);
2685 }
2686
2687 if (tp->t_pktlist_head != NULL) {
2688 tp->t_pktlist_tail->m_nextpkt = m;
2689 tp->t_pktlist_tail = m;
2690 } else {
2691 packchain_newlist++;
2692 tp->t_pktlist_head = tp->t_pktlist_tail = m;
2693 }
2694
2695 if (sendalot == 0 || (tp->t_state != TCPS_ESTABLISHED) ||
2696 (tp->snd_cwnd <= (tp->snd_wnd / 8)) ||
2697 (tp->t_flags & TF_ACKNOW) ||
2698 (tp->t_flagsext & TF_FORCE) ||
2699 tp->t_lastchain >= tcp_packet_chaining) {
2700 error = 0;
2701 while (inp->inp_sndinprog_cnt == 0 &&
2702 tp->t_pktlist_head != NULL) {
2703 packetlist = tp->t_pktlist_head;
2704 packchain_listadd = tp->t_lastchain;
2705 packchain_sent++;
2706 lost = tp->t_pktlist_sentlen;
2707 TCP_PKTLIST_CLEAR(tp);
2708
2709 error = tcp_ip_output(so, tp, packetlist,
2710 packchain_listadd, tp_inp_options,
2711 (so_options & SO_DONTROUTE),
2712 (sack_rxmit || (sack_bytes_rxmt != 0)), isipv6);
2713 if (error) {
2714 /*
2715 * Take into account the rest of unsent
2716 * packets in the packet list for this tcp
2717 * into "lost", since we're about to free
2718 * the whole list below.
2719 */
2720 lost += tp->t_pktlist_sentlen;
2721 break;
2722 } else {
2723 lost = 0;
2724 }
2725 }
2726 /* tcp was closed while we were in ip; resume close */
2727 if (inp->inp_sndinprog_cnt == 0 &&
2728 (tp->t_flags & TF_CLOSING)) {
2729 tp->t_flags &= ~TF_CLOSING;
2730 (void) tcp_close(tp);
2731 return 0;
2732 }
2733 } else {
2734 error = 0;
2735 packchain_looped++;
2736 tcpstat.tcps_sndtotal++;
2737
2738 goto again;
2739 }
2740 if (error) {
2741 /*
2742 * Assume that the packets were lost, so back out the
2743 * sequence number advance, if any. Note that the "lost"
2744 * variable represents the amount of user data sent during
2745 * the recent call to ip_output_list() plus the amount of
2746 * user data in the packet list for this tcp at the moment.
2747 */
2748 if (!(tp->t_flagsext & TF_FORCE)
2749 || tp->t_timer[TCPT_PERSIST] == 0) {
2750 /*
2751 * No need to check for TH_FIN here because
2752 * the TF_SENTFIN flag handles that case.
2753 */
2754 if ((flags & TH_SYN) == 0) {
2755 if (sack_rxmit) {
2756 if (SEQ_GT((p->rxmit - lost),
2757 tp->snd_una)) {
2758 p->rxmit -= lost;
2759
2760 if (SEQ_LT(p->rxmit, p->start)) {
2761 p->rxmit = p->start;
2762 }
2763 } else {
2764 lost = p->rxmit - tp->snd_una;
2765 p->rxmit = tp->snd_una;
2766
2767 if (SEQ_LT(p->rxmit, p->start)) {
2768 p->rxmit = p->start;
2769 }
2770 }
2771 tp->sackhint.sack_bytes_rexmit -= lost;
2772 if (tp->sackhint.sack_bytes_rexmit < 0) {
2773 tp->sackhint.sack_bytes_rexmit = 0;
2774 }
2775 } else {
2776 if (SEQ_GT((tp->snd_nxt - lost),
2777 tp->snd_una)) {
2778 tp->snd_nxt -= lost;
2779 } else {
2780 tp->snd_nxt = tp->snd_una;
2781 }
2782 }
2783 }
2784 }
2785 out:
2786 if (tp->t_pktlist_head != NULL) {
2787 m_freem_list(tp->t_pktlist_head);
2788 }
2789 TCP_PKTLIST_CLEAR(tp);
2790
2791 if (error == ENOBUFS) {
2792 /*
2793 * Set retransmit timer if not currently set
2794 * when we failed to send a segment that can be
2795 * retransmitted (i.e. not pure ack or rst)
2796 */
2797 if (tp->t_timer[TCPT_REXMT] == 0 &&
2798 tp->t_timer[TCPT_PERSIST] == 0 &&
2799 (len != 0 || (flags & (TH_SYN | TH_FIN)) != 0 ||
2800 so->so_snd.sb_cc > 0)) {
2801 tp->t_timer[TCPT_REXMT] =
2802 OFFSET_FROM_START(tp, tp->t_rxtcur);
2803 }
2804 tp->snd_cwnd = tp->t_maxseg;
2805 tp->t_bytes_acked = 0;
2806 tcp_check_timer_state(tp);
2807 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
2808
2809 tcp_ccdbg_trace(tp, NULL, TCP_CC_OUTPUT_ERROR);
2810 return 0;
2811 }
2812 if (error == EMSGSIZE) {
2813 /*
2814 * ip_output() will have already fixed the route
2815 * for us. tcp_mtudisc() will, as its last action,
2816 * initiate retransmission, so it is important to
2817 * not do so here.
2818 *
2819 * If TSO was active we either got an interface
2820 * without TSO capabilits or TSO was turned off.
2821 * Disable it for this connection as too and
2822 * immediatly retry with MSS sized segments generated
2823 * by this function.
2824 */
2825 if (tso) {
2826 tp->t_flags &= ~TF_TSO;
2827 }
2828
2829 tcp_mtudisc(inp, 0);
2830 tcp_check_timer_state(tp);
2831
2832 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
2833 return 0;
2834 }
2835 /*
2836 * Unless this is due to interface restriction policy,
2837 * treat EHOSTUNREACH/ENETDOWN/EADDRNOTAVAIL as a soft error.
2838 */
2839 if ((error == EHOSTUNREACH || error == ENETDOWN || error == EADDRNOTAVAIL) &&
2840 TCPS_HAVERCVDSYN(tp->t_state) &&
2841 !inp_restricted_send(inp, inp->inp_last_outifp)) {
2842 tp->t_softerror = error;
2843 error = 0;
2844 }
2845 tcp_check_timer_state(tp);
2846 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
2847 return error;
2848 }
2849
2850 tcpstat.tcps_sndtotal++;
2851
2852 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
2853 if (sendalot) {
2854 goto again;
2855 }
2856
2857 tcp_check_timer_state(tp);
2858
2859 return 0;
2860 }
2861
2862 static int
tcp_ip_output(struct socket * so,struct tcpcb * tp,struct mbuf * pkt,int cnt,struct mbuf * opt,int flags,int sack_in_progress,boolean_t isipv6)2863 tcp_ip_output(struct socket *so, struct tcpcb *tp, struct mbuf *pkt,
2864 int cnt, struct mbuf *opt, int flags, int sack_in_progress, boolean_t isipv6)
2865 {
2866 int error = 0;
2867 boolean_t chain;
2868 boolean_t unlocked = FALSE;
2869 boolean_t ifdenied = FALSE;
2870 struct inpcb *inp = tp->t_inpcb;
2871 struct ifnet *outif = NULL;
2872 bool check_qos_marking_again = (so->so_flags1 & SOF1_QOSMARKING_POLICY_OVERRIDE) ? FALSE : TRUE;
2873
2874 union {
2875 struct route _ro;
2876 struct route_in6 _ro6;
2877 } route_u_ = {};
2878 #define ro route_u_._ro
2879 #define ro6 route_u_._ro6
2880
2881 union {
2882 struct ip_out_args _ipoa;
2883 struct ip6_out_args _ip6oa;
2884 } out_args_u_ = {};
2885 #define ipoa out_args_u_._ipoa
2886 #define ip6oa out_args_u_._ip6oa
2887
2888 if (isipv6) {
2889 ip6oa.ip6oa_boundif = IFSCOPE_NONE;
2890 ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR;
2891 ip6oa.ip6oa_sotc = SO_TC_UNSPEC;
2892 ip6oa.ip6oa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
2893 } else {
2894 ipoa.ipoa_boundif = IFSCOPE_NONE;
2895 ipoa.ipoa_flags = IPOAF_SELECT_SRCIF | IPOAF_BOUND_SRCADDR;
2896 ipoa.ipoa_sotc = SO_TC_UNSPEC;
2897 ipoa.ipoa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
2898 }
2899
2900 struct flowadv *adv =
2901 (isipv6 ? &ip6oa.ip6oa_flowadv : &ipoa.ipoa_flowadv);
2902
2903 /* If socket was bound to an ifindex, tell ip_output about it */
2904 if (inp->inp_flags & INP_BOUND_IF) {
2905 if (isipv6) {
2906 ip6oa.ip6oa_boundif = inp->inp_boundifp->if_index;
2907 ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
2908 } else {
2909 ipoa.ipoa_boundif = inp->inp_boundifp->if_index;
2910 ipoa.ipoa_flags |= IPOAF_BOUND_IF;
2911 }
2912 } else if (!in6_embedded_scope && isipv6 && (IN6_IS_SCOPE_EMBED(&inp->in6p_faddr))) {
2913 ip6oa.ip6oa_boundif = inp->inp_fifscope;
2914 ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
2915 }
2916
2917 if (INP_NO_CELLULAR(inp)) {
2918 if (isipv6) {
2919 ip6oa.ip6oa_flags |= IP6OAF_NO_CELLULAR;
2920 } else {
2921 ipoa.ipoa_flags |= IPOAF_NO_CELLULAR;
2922 }
2923 }
2924 if (INP_NO_EXPENSIVE(inp)) {
2925 if (isipv6) {
2926 ip6oa.ip6oa_flags |= IP6OAF_NO_EXPENSIVE;
2927 } else {
2928 ipoa.ipoa_flags |= IPOAF_NO_EXPENSIVE;
2929 }
2930 }
2931 if (INP_NO_CONSTRAINED(inp)) {
2932 if (isipv6) {
2933 ip6oa.ip6oa_flags |= IP6OAF_NO_CONSTRAINED;
2934 } else {
2935 ipoa.ipoa_flags |= IPOAF_NO_CONSTRAINED;
2936 }
2937 }
2938 if (INP_AWDL_UNRESTRICTED(inp)) {
2939 if (isipv6) {
2940 ip6oa.ip6oa_flags |= IP6OAF_AWDL_UNRESTRICTED;
2941 } else {
2942 ipoa.ipoa_flags |= IPOAF_AWDL_UNRESTRICTED;
2943 }
2944 }
2945 if (INP_INTCOPROC_ALLOWED(inp) && isipv6) {
2946 ip6oa.ip6oa_flags |= IP6OAF_INTCOPROC_ALLOWED;
2947 }
2948 if (isipv6) {
2949 ip6oa.ip6oa_sotc = so->so_traffic_class;
2950 ip6oa.ip6oa_netsvctype = so->so_netsvctype;
2951 ip6oa.qos_marking_gencount = inp->inp_policyresult.results.qos_marking_gencount;
2952 } else {
2953 ipoa.ipoa_sotc = so->so_traffic_class;
2954 ipoa.ipoa_netsvctype = so->so_netsvctype;
2955 ipoa.qos_marking_gencount = inp->inp_policyresult.results.qos_marking_gencount;
2956 }
2957 if ((so->so_flags1 & SOF1_QOSMARKING_ALLOWED)) {
2958 if (isipv6) {
2959 ip6oa.ip6oa_flags |= IP6OAF_QOSMARKING_ALLOWED;
2960 } else {
2961 ipoa.ipoa_flags |= IPOAF_QOSMARKING_ALLOWED;
2962 }
2963 }
2964 if (check_qos_marking_again) {
2965 if (isipv6) {
2966 ip6oa.ip6oa_flags |= IP6OAF_REDO_QOSMARKING_POLICY;
2967 } else {
2968 ipoa.ipoa_flags |= IPOAF_REDO_QOSMARKING_POLICY;
2969 }
2970 }
2971 if (isipv6) {
2972 flags |= IPV6_OUTARGS;
2973 } else {
2974 flags |= IP_OUTARGS;
2975 }
2976
2977 /* Copy the cached route and take an extra reference */
2978 if (isipv6) {
2979 in6p_route_copyout(inp, &ro6);
2980 } else {
2981 inp_route_copyout(inp, &ro);
2982 }
2983 #if (DEBUG || DEVELOPMENT)
2984 if ((so->so_flags & SOF_MARK_WAKE_PKT) && pkt != NULL) {
2985 so->so_flags &= ~SOF_MARK_WAKE_PKT;
2986 pkt->m_pkthdr.pkt_flags |= PKTF_WAKE_PKT;
2987 }
2988 #endif /* (DEBUG || DEVELOPMENT) */
2989
2990 /*
2991 * Make sure ACK/DELACK conditions are cleared before
2992 * we unlock the socket.
2993 */
2994 tp->last_ack_sent = tp->rcv_nxt;
2995 tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
2996 tp->t_timer[TCPT_DELACK] = 0;
2997 tp->t_unacksegs = 0;
2998
2999 /* Increment the count of outstanding send operations */
3000 inp->inp_sndinprog_cnt++;
3001
3002 /*
3003 * If allowed, unlock TCP socket while in IP
3004 * but only if the connection is established and
3005 * in a normal mode where reentrancy on the tcpcb won't be
3006 * an issue:
3007 * - there is no SACK episode
3008 * - we're not in Fast Recovery mode
3009 * - if we're not sending from an upcall.
3010 */
3011 if (tcp_output_unlocked && !so->so_upcallusecount &&
3012 (tp->t_state == TCPS_ESTABLISHED) && (sack_in_progress == 0) &&
3013 !IN_FASTRECOVERY(tp) && !(so->so_flags & SOF_MP_SUBFLOW)) {
3014 unlocked = TRUE;
3015 socket_unlock(so, 0);
3016 }
3017
3018 /*
3019 * Don't send down a chain of packets when:
3020 * - TCP chaining is disabled
3021 * - there is an IPsec rule set
3022 * - there is a non default rule set for the firewall
3023 */
3024
3025 chain = tcp_packet_chaining > 1
3026 #if IPSEC
3027 && ipsec_bypass
3028 #endif
3029 ; // I'm important, not extraneous
3030
3031 while (pkt != NULL) {
3032 struct mbuf *npkt = pkt->m_nextpkt;
3033
3034 if (!chain) {
3035 pkt->m_nextpkt = NULL;
3036 /*
3037 * If we are not chaining, make sure to set the packet
3038 * list count to 0 so that IP takes the right path;
3039 * this is important for cases such as IPsec where a
3040 * single mbuf might result in multiple mbufs as part
3041 * of the encapsulation. If a non-zero count is passed
3042 * down to IP, the head of the chain might change and
3043 * we could end up skipping it (thus generating bogus
3044 * packets). Fixing it in IP would be desirable, but
3045 * for now this would do it.
3046 */
3047 cnt = 0;
3048 }
3049 if (isipv6) {
3050 error = ip6_output_list(pkt, cnt,
3051 inp->in6p_outputopts, &ro6, flags, NULL, NULL,
3052 &ip6oa);
3053 ifdenied = (ip6oa.ip6oa_flags & IP6OAF_R_IFDENIED);
3054 } else {
3055 error = ip_output_list(pkt, cnt, opt, &ro, flags, NULL,
3056 &ipoa);
3057 ifdenied = (ipoa.ipoa_flags & IPOAF_R_IFDENIED);
3058 }
3059
3060 if (chain || error) {
3061 /*
3062 * If we sent down a chain then we are done since
3063 * the callee had taken care of everything; else
3064 * we need to free the rest of the chain ourselves.
3065 */
3066 if (!chain) {
3067 m_freem_list(npkt);
3068 }
3069 break;
3070 }
3071 pkt = npkt;
3072 }
3073
3074 if (unlocked) {
3075 socket_lock(so, 0);
3076 }
3077
3078 /*
3079 * Enter flow controlled state if the connection is established
3080 * and is not in recovery. Flow control is allowed only if there
3081 * is outstanding data.
3082 *
3083 * A connection will enter suspended state even if it is in
3084 * recovery.
3085 */
3086 if (((adv->code == FADV_FLOW_CONTROLLED && !IN_FASTRECOVERY(tp)) ||
3087 adv->code == FADV_SUSPENDED) &&
3088 !(tp->t_flags & TF_CLOSING) &&
3089 tp->t_state == TCPS_ESTABLISHED &&
3090 SEQ_GT(tp->snd_max, tp->snd_una)) {
3091 int rc;
3092 rc = inp_set_fc_state(inp, adv->code);
3093
3094 if (rc == 1) {
3095 tcp_ccdbg_trace(tp, NULL,
3096 ((adv->code == FADV_FLOW_CONTROLLED) ?
3097 TCP_CC_FLOW_CONTROL : TCP_CC_SUSPEND));
3098 }
3099 }
3100
3101 /*
3102 * When an interface queue gets suspended, some of the
3103 * packets are dropped. Return ENOBUFS, to update the
3104 * pcb state.
3105 */
3106 if (adv->code == FADV_SUSPENDED) {
3107 error = ENOBUFS;
3108 }
3109
3110 VERIFY(inp->inp_sndinprog_cnt > 0);
3111 if (--inp->inp_sndinprog_cnt == 0) {
3112 inp->inp_flags &= ~(INP_FC_FEEDBACK);
3113 if (inp->inp_sndingprog_waiters > 0) {
3114 wakeup(&inp->inp_sndinprog_cnt);
3115 }
3116 }
3117
3118 if (isipv6) {
3119 /*
3120 * When an NECP IP tunnel policy forces the outbound interface,
3121 * ip6_output_list() informs the transport layer what is the actual
3122 * outgoing interface
3123 */
3124 if (ip6oa.ip6oa_flags & IP6OAF_BOUND_IF) {
3125 outif = ifindex2ifnet[ip6oa.ip6oa_boundif];
3126 } else if (ro6.ro_rt != NULL) {
3127 outif = ro6.ro_rt->rt_ifp;
3128 }
3129 } else {
3130 if (ro.ro_rt != NULL) {
3131 outif = ro.ro_rt->rt_ifp;
3132 }
3133 }
3134 if (check_qos_marking_again) {
3135 uint32_t qos_marking_gencount;
3136 bool allow_qos_marking;
3137 if (isipv6) {
3138 qos_marking_gencount = ip6oa.qos_marking_gencount;
3139 allow_qos_marking = ip6oa.ip6oa_flags & IP6OAF_QOSMARKING_ALLOWED ? TRUE : FALSE;
3140 } else {
3141 qos_marking_gencount = ipoa.qos_marking_gencount;
3142 allow_qos_marking = ipoa.ipoa_flags & IPOAF_QOSMARKING_ALLOWED ? TRUE : FALSE;
3143 }
3144 inp->inp_policyresult.results.qos_marking_gencount = qos_marking_gencount;
3145 if (allow_qos_marking == TRUE) {
3146 inp->inp_socket->so_flags1 |= SOF1_QOSMARKING_ALLOWED;
3147 } else {
3148 inp->inp_socket->so_flags1 &= ~SOF1_QOSMARKING_ALLOWED;
3149 }
3150 }
3151
3152 if (outif != NULL && outif != inp->inp_last_outifp) {
3153 /* Update the send byte count */
3154 if (so->so_snd.sb_cc > 0 && so->so_snd.sb_flags & SB_SNDBYTE_CNT) {
3155 inp_decr_sndbytes_total(so, so->so_snd.sb_cc);
3156 inp_decr_sndbytes_allunsent(so, tp->snd_una);
3157 so->so_snd.sb_flags &= ~SB_SNDBYTE_CNT;
3158 }
3159 inp->inp_last_outifp = outif;
3160 #if SKYWALK
3161 if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
3162 netns_set_ifnet(&inp->inp_netns_token, inp->inp_last_outifp);
3163 }
3164 #endif /* SKYWALK */
3165 }
3166
3167 if (error != 0 && ifdenied &&
3168 (INP_NO_CELLULAR(inp) || INP_NO_EXPENSIVE(inp) || INP_NO_CONSTRAINED(inp))) {
3169 soevent(so,
3170 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_IFDENIED));
3171 }
3172
3173 /* Synchronize cached PCB route & options */
3174 if (isipv6) {
3175 in6p_route_copyin(inp, &ro6);
3176 } else {
3177 inp_route_copyin(inp, &ro);
3178 }
3179
3180 if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift == 0 &&
3181 tp->t_inpcb->inp_route.ro_rt != NULL) {
3182 /* If we found the route and there is an rtt on it
3183 * reset the retransmit timer
3184 */
3185 tcp_getrt_rtt(tp, tp->t_inpcb->in6p_route.ro_rt);
3186 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp, tp->t_rxtcur);
3187 }
3188 return error;
3189 #undef ro
3190 #undef ro6
3191 #undef ipoa
3192 #undef ip6oa
3193 }
3194
3195 int tcptv_persmin_val = TCPTV_PERSMIN;
3196
3197 void
tcp_setpersist(struct tcpcb * tp)3198 tcp_setpersist(struct tcpcb *tp)
3199 {
3200 int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
3201
3202 /* If a PERSIST_TIMER option was set we will limit the
3203 * time the persist timer will be active for that connection
3204 * in order to avoid DOS by using zero window probes.
3205 * see rdar://5805356
3206 */
3207
3208 if (tp->t_persist_timeout != 0 &&
3209 tp->t_timer[TCPT_PERSIST] == 0 &&
3210 tp->t_persist_stop == 0) {
3211 tp->t_persist_stop = tcp_now + tp->t_persist_timeout;
3212 }
3213
3214 /*
3215 * Start/restart persistance timer.
3216 */
3217 TCPT_RANGESET(tp->t_timer[TCPT_PERSIST],
3218 t * tcp_backoff[tp->t_rxtshift],
3219 tcptv_persmin_val, TCPTV_PERSMAX, 0);
3220 tp->t_timer[TCPT_PERSIST] = OFFSET_FROM_START(tp, tp->t_timer[TCPT_PERSIST]);
3221
3222 if (tp->t_rxtshift < TCP_MAXRXTSHIFT) {
3223 tp->t_rxtshift++;
3224 }
3225 }
3226
3227 static int
tcp_recv_throttle(struct tcpcb * tp)3228 tcp_recv_throttle(struct tcpcb *tp)
3229 {
3230 uint32_t base_rtt, newsize;
3231 struct sockbuf *sbrcv = &tp->t_inpcb->inp_socket->so_rcv;
3232
3233 if (tcp_use_rtt_recvbg == 1 &&
3234 TSTMP_SUPPORTED(tp)) {
3235 /*
3236 * Timestamps are supported on this connection. Use
3237 * RTT to look for an increase in latency.
3238 */
3239
3240 /*
3241 * If the connection is already being throttled, leave it
3242 * in that state until rtt comes closer to base rtt
3243 */
3244 if (tp->t_flagsext & TF_RECV_THROTTLE) {
3245 return 1;
3246 }
3247
3248 base_rtt = get_base_rtt(tp);
3249
3250 if (base_rtt != 0 && tp->t_rttcur != 0) {
3251 /*
3252 * if latency increased on a background flow,
3253 * return 1 to start throttling.
3254 */
3255 if (tp->t_rttcur > (base_rtt + target_qdelay)) {
3256 tp->t_flagsext |= TF_RECV_THROTTLE;
3257 if (tp->t_recv_throttle_ts == 0) {
3258 tp->t_recv_throttle_ts = tcp_now;
3259 }
3260 /*
3261 * Reduce the recv socket buffer size to
3262 * minimize latecy.
3263 */
3264 if (sbrcv->sb_idealsize >
3265 tcp_recv_throttle_minwin) {
3266 newsize = sbrcv->sb_idealsize >> 1;
3267 /* Set a minimum of 16 K */
3268 newsize =
3269 max(newsize,
3270 tcp_recv_throttle_minwin);
3271 sbrcv->sb_idealsize = newsize;
3272 }
3273 return 1;
3274 } else {
3275 return 0;
3276 }
3277 }
3278 }
3279
3280 /*
3281 * Timestamps are not supported or there is no good RTT
3282 * measurement. Use IPDV in this case.
3283 */
3284 if (tp->acc_iaj > tcp_acc_iaj_react_limit) {
3285 return 1;
3286 }
3287
3288 return 0;
3289 }
3290