1 /*
2 * Copyright (c) 2000-2024 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 #include <stdint.h>
71 #define _IP_VHL
72
73 #include "tcp_includes.h"
74
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/kernel.h>
78 #include <sys/sysctl.h>
79 #include <sys/mbuf.h>
80 #include <sys/domain.h>
81 #include <sys/protosw.h>
82 #include <sys/socket.h>
83 #include <sys/socketvar.h>
84 #include <os/ptrtools.h>
85 #include <kern/clock.h>
86
87 #include <net/route.h>
88 #include <net/ntstat.h>
89 #include <net/if_var.h>
90 #include <net/if.h>
91 #include <net/if_types.h>
92 #include <net/dlil.h>
93 #include <net/droptap.h>
94
95 #include <netinet/in.h>
96 #include <netinet/in_systm.h>
97 #include <netinet/in_var.h>
98 #include <netinet/in_tclass.h>
99 #include <netinet/ip.h>
100 #include <netinet/in_pcb.h>
101 #include <netinet/ip_var.h>
102 #include <mach/sdt.h>
103 #include <netinet6/in6_pcb.h>
104 #include <netinet/ip6.h>
105 #include <netinet6/ip6_var.h>
106 #include <netinet/tcp.h>
107 #include <netinet/tcp_cache.h>
108 #include <netinet/tcp_fsm.h>
109 #include <netinet/tcp_seq.h>
110 #include <netinet/tcp_timer.h>
111 #include <netinet/tcp_var.h>
112 #include <netinet/tcpip.h>
113 #include <netinet/tcp_cc.h>
114 #include <netinet/tcp_log.h>
115 #include <sys/kdebug.h>
116 #include <mach/sdt.h>
117
118 #if IPSEC
119 #include <netinet6/ipsec.h>
120 #endif /*IPSEC*/
121
122 #if MPTCP
123 #include <netinet/mptcp_var.h>
124 #include <netinet/mptcp.h>
125 #include <netinet/mptcp_opt.h>
126 #include <netinet/mptcp_seq.h>
127 #endif
128
129 #include <corecrypto/ccaes.h>
130
131 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 1)
132 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 3)
133 #define DBG_FNC_TCP_OUTPUT NETDBG_CODE(DBG_NETTCP, (4 << 8) | 1)
134
135 SYSCTL_SKMEM_TCP_INT(OID_AUTO, path_mtu_discovery,
136 CTLFLAG_RW | CTLFLAG_LOCKED, int, path_mtu_discovery, 1,
137 "Enable Path MTU Discovery");
138
139 SYSCTL_SKMEM_TCP_INT(OID_AUTO, local_slowstart_flightsize,
140 CTLFLAG_RW | CTLFLAG_LOCKED, int, ss_fltsz_local, 8,
141 "Slow start flight size for local networks");
142
143 SYSCTL_SKMEM_TCP_INT(OID_AUTO, tso, CTLFLAG_RW | CTLFLAG_LOCKED,
144 int, tcp_do_tso, 1, "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, accurate_ecn,
151 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_acc_ecn, 0,
152 "Accurate ECN mode (0: disable, 1: enable Accurate ECN feedback");
153
154 int tcp_l4s_developer = 0;
155 SYSCTL_INT(_net_inet_tcp, OID_AUTO, l4s_developer,
156 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_l4s_developer, 0,
157 "Developer L4S mode (0: system, 1: force enable L4S, 2: force disable L4S");
158
159 SYSCTL_SKMEM_TCP_INT(OID_AUTO, l4s,
160 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_l4s, 0,
161 "System L4S mode (0: disable, 1: enable L4S");
162
163 SYSCTL_SKMEM_TCP_INT(OID_AUTO, link_heuristics_flags,
164 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_link_heuristics_flags, TCP_LINK_HEURISTICS_DEFAULT,
165 "TCP LQM heuristics flags (1:rxmtcomp 2:noackpro 4:synrxmt 8:stealth 0x10:rtomin 0x20:notlp)");
166
167 SYSCTL_SKMEM_TCP_INT(OID_AUTO, link_heuristics_rto_min,
168 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_link_heuristics_rto_min, TCP_DEFAULT_LINK_HEUR_RTOMIN,
169 "");
170
171 SYSCTL_SKMEM_TCP_INT(OID_AUTO, allow_syn_prio,
172 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_allow_syn_prio, 0,
173 "");
174
175
176 // TO BE REMOVED
177 SYSCTL_SKMEM_TCP_INT(OID_AUTO, do_ack_compression,
178 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_do_ack_compression, 1,
179 "Enable TCP ACK compression (on (cell only): 1, off: 0, on (all interfaces): 2)");
180
181 SYSCTL_SKMEM_TCP_INT(OID_AUTO, ack_compression_rate,
182 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_ack_compression_rate, TCP_COMP_CHANGE_RATE,
183 "Rate at which we force sending new ACKs (in ms)");
184
185 SYSCTL_SKMEM_TCP_INT(OID_AUTO, randomize_timestamps,
186 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_randomize_timestamps, 1,
187 "Randomize TCP timestamps to prevent tracking (on: 1, off: 0)");
188
189 static int
190 sysctl_change_ecn_setting SYSCTL_HANDLER_ARGS
191 {
192 #pragma unused(oidp, arg1, arg2)
193 int i, err = 0, changed = 0;
194
195 err = sysctl_io_number(req, tcp_ecn, sizeof(int32_t),
196 &i, &changed);
197 if (err != 0 || req->newptr == USER_ADDR_NULL) {
198 return err;
199 }
200
201 if (changed) {
202 tcp_ecn = i;
203 SYSCTL_SKMEM_UPDATE_FIELD(tcp.ecn, tcp_ecn);
204 }
205 return err;
206 }
207
208 /* TODO: remove ecn_initiate_out once libnetcore ECN cleanup changes land */
209 int tcp_ecn_outbound = 2;
210 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, ecn_initiate_out,
211 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_ecn_outbound, 0,
212 sysctl_change_ecn_setting, "IU",
213 "Initiate ECN for outbound connections");
214
215 int tcp_ecn = 1;
216 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, ecn,
217 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_ecn, 0,
218 sysctl_change_ecn_setting, "IU",
219 "ECN system setting (0: disable, 1: enable)");
220
221 SYSCTL_SKMEM_TCP_INT(OID_AUTO, packetchain,
222 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_packet_chaining, 50,
223 "Enable TCP output packet chaining");
224
225 SYSCTL_SKMEM_TCP_INT(OID_AUTO, socket_unlocked_on_output,
226 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_output_unlocked, 1,
227 "Unlock TCP when sending packets down to IP");
228
229 SYSCTL_SKMEM_TCP_INT(OID_AUTO, min_iaj_win,
230 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_min_iaj_win, MIN_IAJ_WIN,
231 "Minimum recv win based on inter-packet arrival jitter");
232
233 SYSCTL_SKMEM_TCP_INT(OID_AUTO, acc_iaj_react_limit,
234 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_acc_iaj_react_limit,
235 ACC_IAJ_REACT_LIMIT, "Accumulated IAJ when receiver starts to react");
236
237 SYSCTL_SKMEM_TCP_INT(OID_AUTO, autosndbufinc,
238 CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_autosndbuf_inc,
239 8 * 1024, "Increment in send socket bufffer size");
240
241 SYSCTL_SKMEM_TCP_INT(OID_AUTO, autosndbufmax,
242 CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN, uint32_t, tcp_autosndbuf_max, 2 * 1024 * 1024,
243 "Maximum send socket buffer size");
244
245 SYSCTL_SKMEM_TCP_INT(OID_AUTO, rtt_recvbg,
246 CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_use_rtt_recvbg, 1,
247 "Use RTT for bg recv algorithm");
248
249 SYSCTL_SKMEM_TCP_INT(OID_AUTO, recv_throttle_minwin,
250 CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_recv_throttle_minwin, 16 * 1024,
251 "Minimum recv win for throttling");
252
253 SYSCTL_SKMEM_TCP_INT(OID_AUTO, enable_tlp,
254 CTLFLAG_RW | CTLFLAG_LOCKED,
255 int32_t, tcp_enable_tlp, 1, "Enable Tail loss probe");
256
257 static int32_t packchain_newlist = 0;
258 static int32_t packchain_looped = 0;
259 static int32_t packchain_sent = 0;
260
261 /* temporary: for testing */
262 #if IPSEC
263 extern int ipsec_bypass;
264 #endif
265
266 extern int slowlink_wsize; /* window correction for slow links */
267
268 extern u_int32_t kipf_count;
269
270 static int tcp_ip_output(struct socket *, struct tcpcb *, struct mbuf *,
271 int, struct mbuf *, int, int, boolean_t);
272 static int tcp_recv_throttle(struct tcpcb *tp);
273
274 __attribute__((noinline))
275 static int32_t
tcp_tfo_check(struct tcpcb * tp,int32_t len)276 tcp_tfo_check(struct tcpcb *tp, int32_t len)
277 {
278 struct socket *__single so = tp->t_inpcb->inp_socket;
279 unsigned int optlen = 0;
280 unsigned int cookie_len;
281
282 if (tp->t_flags & TF_NOOPT) {
283 goto fallback;
284 }
285
286 if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
287 !tcp_heuristic_do_tfo(tp)) {
288 tp->t_tfo_stats |= TFO_S_HEURISTICS_DISABLE;
289 tcpstat.tcps_tfo_heuristics_disable++;
290 goto fallback;
291 }
292
293 if (so->so_flags1 & SOF1_DATA_AUTHENTICATED) {
294 return len;
295 }
296
297 optlen += TCPOLEN_MAXSEG;
298
299 if (tp->t_flags & TF_REQ_SCALE) {
300 optlen += 4;
301 }
302
303 #if MPTCP
304 if ((so->so_flags & SOF_MP_SUBFLOW) && mptcp_enable &&
305 (tp->t_rxtshift <= mptcp_mpcap_retries ||
306 (tptomptp(tp)->mpt_mpte->mpte_flags & MPTE_FORCE_ENABLE))) {
307 optlen += sizeof(struct mptcp_mpcapable_opt_common) + sizeof(mptcp_key_t);
308 }
309 #endif /* MPTCP */
310
311 if (tp->t_flags & TF_REQ_TSTMP) {
312 optlen += TCPOLEN_TSTAMP_APPA;
313 }
314
315 if (SACK_ENABLED(tp)) {
316 optlen += TCPOLEN_SACK_PERMITTED;
317 }
318
319 /* Now, decide whether to use TFO or not */
320
321 /* Don't even bother trying if there is no space at all... */
322 if (MAX_TCPOPTLEN - optlen < TCPOLEN_FASTOPEN_REQ) {
323 goto fallback;
324 }
325
326 cookie_len = tcp_cache_get_cookie_len(tp);
327 if (cookie_len == 0) {
328 /* No cookie, so we request one */
329 return 0;
330 }
331
332 /* There is not enough space for the cookie, so we cannot do TFO */
333 if (MAX_TCPOPTLEN - optlen < cookie_len) {
334 goto fallback;
335 }
336
337 /* Do not send SYN+data if there is more in the queue than MSS */
338 if (so->so_snd.sb_cc > (tp->t_maxopd - MAX_TCPOPTLEN)) {
339 goto fallback;
340 }
341
342 /* Ok, everything looks good. We can go on and do TFO */
343 return len;
344
345 fallback:
346 tcp_disable_tfo(tp);
347 return 0;
348 }
349
350 /* Returns the number of bytes written to the TCP option-space */
351 __attribute__((noinline))
352 static unsigned int
353 tcp_tfo_write_cookie_rep(struct tcpcb *tp, unsigned int optlen,
354 u_char *__counted_by(optlen + 2 + TFO_COOKIE_LEN_DEFAULT) opt)
355 {
356 u_char out[CCAES_BLOCK_SIZE];
357 unsigned ret = 0;
358 u_char *bp;
359
360 if (MAX_TCPOPTLEN - optlen <
361 TCPOLEN_FASTOPEN_REQ + TFO_COOKIE_LEN_DEFAULT) {
362 return ret;
363 }
364
365 tcp_tfo_gen_cookie(tp->t_inpcb, out, sizeof(out));
366
367 bp = opt + optlen;
368
369 *bp++ = TCPOPT_FASTOPEN;
370 *bp++ = 2 + TFO_COOKIE_LEN_DEFAULT;
371 memcpy(bp, out, TFO_COOKIE_LEN_DEFAULT);
372 ret += 2 + TFO_COOKIE_LEN_DEFAULT;
373
374 tp->t_tfo_stats |= TFO_S_COOKIE_SENT;
375 tcpstat.tcps_tfo_cookie_sent++;
376
377 return ret;
378 }
379
380 __attribute__((noinline))
381 static unsigned int
tcp_tfo_write_cookie(struct tcpcb * tp,unsigned int optlen,int32_t len,u_char * __counted_by (TCP_MAXOLEN)opt)382 tcp_tfo_write_cookie(struct tcpcb *tp, unsigned int optlen, int32_t len,
383 u_char *__counted_by(TCP_MAXOLEN) opt)
384 {
385 uint8_t tfo_len;
386 struct socket *__single so = tp->t_inpcb->inp_socket;
387 unsigned ret = 0;
388 int res;
389 u_char *bp;
390
391 if (TCPOLEN_FASTOPEN_REQ > MAX_TCPOPTLEN - optlen) {
392 return 0;
393 }
394 tfo_len = (uint8_t)(MAX_TCPOPTLEN - optlen - TCPOLEN_FASTOPEN_REQ);
395
396 if (so->so_flags1 & SOF1_DATA_AUTHENTICATED) {
397 /* If there is some data, let's track it */
398 if (len > 0) {
399 tp->t_tfo_stats |= TFO_S_SYN_DATA_SENT;
400 tcpstat.tcps_tfo_syn_data_sent++;
401 }
402
403 return 0;
404 }
405
406 bp = opt + optlen;
407
408 /*
409 * The cookie will be copied in the appropriate place within the
410 * TCP-option space. That way we avoid the need for an intermediate
411 * variable.
412 */
413 res = tcp_cache_get_cookie(tp, bp + TCPOLEN_FASTOPEN_REQ, tfo_len, &tfo_len);
414 if (res == 0) {
415 *bp++ = TCPOPT_FASTOPEN;
416 *bp++ = TCPOLEN_FASTOPEN_REQ;
417 ret += TCPOLEN_FASTOPEN_REQ;
418
419 tp->t_tfo_flags |= TFO_F_COOKIE_REQ;
420
421 tp->t_tfo_stats |= TFO_S_COOKIE_REQ;
422 tcpstat.tcps_tfo_cookie_req++;
423 } else {
424 *bp++ = TCPOPT_FASTOPEN;
425 *bp++ = TCPOLEN_FASTOPEN_REQ + tfo_len;
426
427 ret += TCPOLEN_FASTOPEN_REQ + tfo_len;
428
429 tp->t_tfo_flags |= TFO_F_COOKIE_SENT;
430
431 /* If there is some data, let's track it */
432 if (len > 0) {
433 tp->t_tfo_stats |= TFO_S_SYN_DATA_SENT;
434 tcpstat.tcps_tfo_syn_data_sent++;
435 }
436 }
437
438 return ret;
439 }
440
441 static inline bool
tcp_send_ecn_flags_on_syn(struct tcpcb * tp)442 tcp_send_ecn_flags_on_syn(struct tcpcb *tp)
443 {
444 /* We allow Accurate ECN negotiation on first retransmission as well */
445 bool send_on_first_retrans = (tp->ecn_flags & TE_ACE_SETUPSENT) &&
446 (tp->t_rxtshift <= 1);
447
448 return !(tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) || send_on_first_retrans;
449 }
450
451 /*
452 * Returns the RTO deadline as future Mach time value
453 * based on the TCPT_REXMT timer, if set.
454 */
455 static uint64_t
tcp_calculate_rto_deadline(const struct tcpcb * tp,uint32_t local_tcp_now)456 tcp_calculate_rto_deadline(const struct tcpcb *tp, uint32_t local_tcp_now)
457 {
458 uint64_t rto_val = tp->t_timer[TCPT_REXMT];
459 uint64_t rto_deadline_hz;
460 uint64_t rto_offset_hz;
461 uint64_t rto_offset_nano;
462 uint64_t rto_deadline_mach;
463 int sojourn_factor = tcp_rto_sojourn_factor;
464
465 /*
466 * Check whether the TCPT_REXMT timer is set.
467 */
468 if (rto_val == 0) {
469 DTRACE_TCP3(rto_deadline, struct tcpcb *, tp, uint32_t, local_tcp_now, uint64_t, 0);
470 return 0;
471 }
472
473 /*
474 * Check whether the TCPT_REXMT timer has already expired.
475 */
476 rto_deadline_hz = tp->tentry.te_timer_start + rto_val;
477 if (rto_deadline_hz < local_tcp_now) {
478 DTRACE_TCP3(rto_deadline, struct tcpcb *, tp, uint32_t, local_tcp_now, uint64_t, 0);
479 return 0;
480 }
481
482 /*
483 * Sanity check the sojourn factor
484 */
485 if (sojourn_factor < 25) {
486 sojourn_factor = 25;
487 } else if (125 <= sojourn_factor) {
488 sojourn_factor = 125; /* For testing */
489 }
490
491 /*
492 * Convert the retransmit timer to Mach deadline in the future.
493 * This is done in two steps:
494 * 1. Convert the timer value from the TCP RETRANSHZ units to
495 * a wall-clock timestamp (in nanosecond resolution).
496 * 2. Convert the wall-clock timestamp to a Mach timestamp.
497 */
498 rto_offset_hz = rto_deadline_hz - local_tcp_now;
499 rto_offset_hz = (uint64_t)((rto_offset_hz * sojourn_factor) / 100);
500 rto_offset_nano = rto_offset_hz * TCP_RETRANSHZ_TO_USEC * NSEC_PER_USEC;
501 nanoseconds_to_deadline(rto_offset_nano, &rto_deadline_mach);
502
503 DTRACE_TCP3(rto_deadline, struct tcpcb *, tp, uint32_t, local_tcp_now, uint64_t, rto_deadline_mach);
504
505 return rto_deadline_mach;
506 }
507
508
509 void
tcp_set_l4s(struct tcpcb * tp,struct ifnet * ifp)510 tcp_set_l4s(struct tcpcb *tp, struct ifnet *ifp)
511 {
512 if (tp->t_state >= TCPS_ESTABLISHED) {
513 return;
514 }
515
516 /*
517 * L4S is enabled if,
518 * 1. It is not disabled explicitly by developer or interface setting or tcp options
519 * 2. It is enabled either by developer or interface setting or A/B deployment or tcp_options,
520 * It implicitly enables Accurate ECN which supports ACE and AccECN option for ECN feedback
521 */
522 bool l4s_disabled = (tcp_l4s_developer == tcp_l4s_developer_disable ||
523 (ifp != NULL && ifp->if_l4s_mode == IFRTYPE_L4S_DISABLE) ||
524 (tp->t_flagsext & TF_L4S_DISABLED) == 1);
525
526 tp->l4s_enabled = !l4s_disabled && (tcp_l4s_developer == tcp_l4s_developer_enable ||
527 (ifp != NULL && ifp->if_l4s_mode == IFRTYPE_L4S_ENABLE) || tcp_l4s == 1 ||
528 ((tp->t_flagsext & TF_L4S_ENABLED)));
529 }
530
531 void
tcp_set_accurate_ecn(struct tcpcb * tp)532 tcp_set_accurate_ecn(struct tcpcb *tp)
533 {
534 if ((tp->ecn_flags & TE_ACC_ECN_ON) == TE_ACC_ECN_ON) {
535 tp->accurate_ecn_on = true;
536 } else {
537 tp->accurate_ecn_on = false;
538 }
539 }
540
541 void
tcp_set_ecn(struct tcpcb * tp)542 tcp_set_ecn(struct tcpcb *tp)
543 {
544 bool ecn_enabled = tcp_ecn_enabled(tp->ecn_flags);
545
546 if (!ecn_enabled || !tcp_heuristic_do_ecn(tp)) {
547 tp->ecn_flags &= ~TE_ENABLE_ECN;
548 return;
549 }
550
551 /* ECN is enabled based on system settings */
552 tp->ecn_flags |= TE_ENABLE_ECN;
553
554 if (tp->l4s_enabled) {
555 /* Set the accurate ECN state */
556 if (tp->t_client_accecn_state == tcp_connection_client_accurate_ecn_feature_disabled) {
557 tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_feature_enabled;
558 }
559 if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_feature_disabled) {
560 tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_feature_enabled;
561 }
562 }
563 }
564
565 bool
tcp_ecn_enabled(uint32_t ecn_flags)566 tcp_ecn_enabled(uint32_t ecn_flags)
567 {
568 /*
569 * Socket option has precedence
570 */
571 if (ecn_flags & TE_ECN_MODE_ENABLE) {
572 return true;
573 }
574 if (ecn_flags & TE_ECN_MODE_DISABLE) {
575 return false;
576 }
577
578 /*
579 * System wide settings come last
580 */
581 if (tcp_ecn == 1) {
582 return true;
583 } else {
584 return false;
585 }
586 }
587
588 uint32_t
tcp_flight_size(struct tcpcb * tp)589 tcp_flight_size(struct tcpcb *tp)
590 {
591 int ret;
592
593 VERIFY(tp->sackhint.sack_bytes_acked >= 0);
594 VERIFY(tp->sackhint.sack_bytes_rexmit >= 0);
595
596 /*
597 * RFC6675, SetPipe (), SACK'd bytes are discounted. All the rest is still in-flight.
598 */
599 ret = tp->snd_nxt - tp->snd_una - tp->sackhint.sack_bytes_acked;
600
601 if (TCP_RACK_ENABLED(tp)) {
602 /* In flight is bytes sent - bytes that left the network + bytes retransmitted */
603 const uint32_t bytes_sent = SEQ_MAX(tp->snd_max, tp->snd_nxt) - tp->snd_una;
604 const uint32_t bytes_not_in_flight = tp->bytes_sacked + tp->bytes_lost;
605 ret = bytes_sent - bytes_not_in_flight + tp->bytes_retransmitted;
606 }
607
608 if (ret < 0) {
609 /* It shouldn't happen when RACK is enabled */
610 if (TCP_RACK_ENABLED(tp)) {
611 os_log_error(OS_LOG_DEFAULT, "flight_size (%d) can't be negative "
612 "(snd_nxt:%u snd_max:%u, snd_una:%u, sacked:%u lost:%u retransmitted:%u)",
613 ret, tp->snd_nxt, tp->snd_max, tp->snd_una,
614 tp->bytes_sacked, tp->bytes_lost, tp->bytes_retransmitted);
615 }
616 /*
617 * This happens when the RTO-timer fires because snd_nxt gets artificially
618 * decreased. If we then receive some SACK-blogs, sack_bytes_acked is
619 * going to be high.
620 */
621 ret = 0;
622 }
623
624 return ret;
625 }
626
627 /*
628 * Either of ECT0 or ECT1 flag should be set
629 * when this function is called
630 */
631 static void
tcp_add_accecn_option(struct tcpcb * tp,uint16_t flags,uint32_t * __indexable lp,uint8_t * optlen)632 tcp_add_accecn_option(struct tcpcb *tp, uint16_t flags, uint32_t *__indexable lp, uint8_t *optlen)
633 {
634 uint8_t max_len = TCP_MAXOLEN - *optlen;
635 uint8_t len = TCPOLEN_ACCECN_EMPTY;
636
637 uint32_t e1b = (uint32_t)(tp->t_aecn.t_rcv_ect1_bytes & TCP_ACO_MASK);
638 uint32_t e0b = (uint32_t)(tp->t_aecn.t_rcv_ect0_bytes & TCP_ACO_MASK);
639 uint32_t ceb = (uint32_t)(tp->t_aecn.t_rcv_ce_bytes & TCP_ACO_MASK);
640
641 if (max_len < TCPOLEN_ACCECN_EMPTY) {
642 TCP_LOG(tp, "not enough space to add any AccECN option");
643 return;
644 }
645
646 if (!(flags & TH_SYN || (tp->ecn_flags & TE_ACE_FINAL_ACK_3WHS) ||
647 tp->snd_una == tp->iss + 1 ||
648 tp->ecn_flags & (TE_ACO_ECT1 | TE_ACO_ECT0))) {
649 /*
650 * Since this is neither a SYN-ACK packet, nor the final ACK of
651 * the 3WHS (nor the first acked data segment) nor any of the ECT byte
652 * counter flags are set, no need to send the option.
653 */
654 return;
655 }
656
657 if ((flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK) &&
658 tp->t_rxtshift >= 1) {
659 /*
660 * If this is a SYN-ACK retransmission (first),
661 * retry without AccECN option and just with ACE fields.
662 * From second retransmission onwards, we don't send any
663 * Accurate ECN state.
664 */
665 return;
666 }
667
668 if (max_len < (TCPOLEN_ACCECN_EMPTY + 1 * TCPOLEN_ACCECN_COUNTER)) {
669 /* Can carry EMPTY option (2 bytes) which can be used to test path in SYN-ACK packet */
670 if (flags & TH_SYN) {
671 *(uint16_t *)lp++ = htons((TCPOPT_ACCECN1 << 8) | len);
672 *optlen += len;
673 }
674 } else if (max_len < (TCPOLEN_ACCECN_EMPTY + 2 * TCPOLEN_ACCECN_COUNTER)) {
675 /* Can carry one option */
676 len += 1 * TCPOLEN_ACCECN_COUNTER;
677 if (tp->ecn_flags & TE_ACO_ECT1) {
678 *lp++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) | ((e1b >> 8) & 0xffff));
679 *(uint16_t *)lp++ = htons((uint16_t)((e1b & 0xff) << 8) | TCPOPT_NOP);
680 } else {
681 *lp++ = htonl((TCPOPT_ACCECN0 << 24) | (len << 16) | ((e0b >> 8) & 0xffff));
682 *(uint16_t *)lp++ = htons((uint16_t)((e0b & 0xff) << 8) | TCPOPT_NOP);
683 }
684 *optlen += len + 1; /* 1 NOPs */
685 } else if (max_len < (TCPOLEN_ACCECN_EMPTY + 3 * TCPOLEN_ACCECN_COUNTER)) {
686 /* Can carry two options */
687 len += 2 * TCPOLEN_ACCECN_COUNTER;
688 if (tp->ecn_flags & TE_ACO_ECT1) {
689 *lp++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) | ((e1b >> 8) & 0xffff));
690 *lp++ = htonl(((e1b & 0xff) << 24) | (ceb & 0xffffff));
691 } else {
692 *lp++ = htonl((TCPOPT_ACCECN0 << 24) | (len << 16) | ((e0b >> 8) & 0xffff));
693 *lp++ = htonl(((e0b & 0xff) << 24) | (ceb & 0xffffff));
694 }
695 *optlen += len; /* 0 NOPs */
696 } else {
697 /*
698 * TCP option sufficient to hold full AccECN option
699 * but send counter that changed during the entire connection.
700 */
701 len += 3 * TCPOLEN_ACCECN_COUNTER;
702 /* Can carry all three options */
703 if (tp->ecn_flags & TE_ACO_ECT1) {
704 *lp++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) | ((e1b >> 8) & 0xffff));
705 *lp++ = htonl(((e1b & 0xff) << 24) | (ceb & 0xffffff));
706 *lp++ = htonl(((e0b & 0xffffff) << 8) | TCPOPT_NOP);
707 } else {
708 *lp++ = htonl((TCPOPT_ACCECN0 << 24) | (len << 16) | ((e0b >> 8) & 0xffff));
709 *lp++ = htonl(((e0b & 0xff) << 24) | (ceb & 0xffffff));
710 *lp++ = htonl(((e1b & 0xffffff) << 8) | TCPOPT_NOP);
711 }
712 *optlen += len + 1; /* 1 NOP */
713 }
714 }
715
716 /*
717 * Insert TCP options according to the supplied parameters to the place
718 * optp in a consistent way. Can handle unaligned destinations.
719 *
720 * The order of the option processing is crucial for optimal packing and
721 * alignment for the scarce option space.
722 *
723 * The optimal order for a SYN/SYN-ACK segment is:
724 * MSS (4) + NOP (1) + Window scale (3) + SACK permitted (2) +
725 * Timestamp (10) + Signature (18) = 38 bytes out of a maximum of 40.
726 *
727 * The SACK options should be last. SACK blocks consume 8*n+2 bytes.
728 * So a full size SACK blocks option is 34 bytes (with 4 SACK blocks).
729 * At minimum we need 10 bytes (to generate 1 SACK block). If both
730 * TCP Timestamps (12 bytes) and TCP Signatures (18 bytes) are present,
731 * we only have 10 bytes for SACK options (40 - (12 + 18)).
732 */
733 uint8_t
tcp_addoptions(struct tcpopt * to,u_char * __ended_by (optend)optp,u_char * optend)734 tcp_addoptions(struct tcpopt *to, u_char * __ended_by(optend) optp, u_char * optend)
735 {
736 uint32_t mask;
737 uint8_t optlen = 0;
738
739 for (mask = 1; mask < TOF_MAXOPT; mask <<= 1) {
740 if ((to->to_flags & mask) != mask) {
741 continue;
742 }
743 if (optlen == TCP_MAXOLEN) {
744 break;
745 }
746 switch (to->to_flags & mask) {
747 case TOF_MSS:
748 while (optlen % 4) {
749 optlen += TCPOLEN_NOP;
750 *optp++ = TCPOPT_NOP;
751 }
752 if (TCP_MAXOLEN - optlen < TCPOLEN_MAXSEG) {
753 continue;
754 }
755 optlen += TCPOLEN_MAXSEG;
756 *optp++ = TCPOPT_MAXSEG;
757 *optp++ = TCPOLEN_MAXSEG;
758 to->to_mss = htons(to->to_mss);
759 bcopy((u_char *)&to->to_mss, optp, sizeof(to->to_mss));
760 optp += sizeof(to->to_mss);
761 optend = optend;
762 break;
763 case TOF_SCALE:
764 while (!optlen || optlen % 2 != 1) {
765 optlen += TCPOLEN_NOP;
766 *optp++ = TCPOPT_NOP;
767 }
768 if (TCP_MAXOLEN - optlen < TCPOLEN_WINDOW) {
769 continue;
770 }
771 optlen += TCPOLEN_WINDOW;
772 *optp++ = TCPOPT_WINDOW;
773 *optp++ = TCPOLEN_WINDOW;
774 *optp++ = to->to_wscale;
775 break;
776 case TOF_SACKPERM:
777 while (optlen % 2) {
778 optlen += TCPOLEN_NOP;
779 *optp++ = TCPOPT_NOP;
780 }
781 if (TCP_MAXOLEN - optlen < TCPOLEN_SACK_PERMITTED) {
782 continue;
783 }
784 optlen += TCPOLEN_SACK_PERMITTED;
785 *optp++ = TCPOPT_SACK_PERMITTED;
786 *optp++ = TCPOLEN_SACK_PERMITTED;
787 break;
788 case TOF_TS:
789 while (!optlen || optlen % 4 != 2) {
790 optlen += TCPOLEN_NOP;
791 *optp++ = TCPOPT_NOP;
792 }
793 if (TCP_MAXOLEN - optlen < TCPOLEN_TIMESTAMP) {
794 continue;
795 }
796 optlen += TCPOLEN_TIMESTAMP;
797 *optp++ = TCPOPT_TIMESTAMP;
798 *optp++ = TCPOLEN_TIMESTAMP;
799 to->to_tsval = htonl(to->to_tsval);
800 to->to_tsecr = htonl(to->to_tsecr);
801 bcopy((u_char *)&to->to_tsval, optp, sizeof(to->to_tsval));
802 optp += sizeof(to->to_tsval);
803 optend = optend;
804 bcopy((u_char *)&to->to_tsecr, optp, sizeof(to->to_tsecr));
805 optp += sizeof(to->to_tsecr);
806 optend = optend;
807 break;
808 case TOF_SACK:
809 {
810 int sackblks = 0;
811 struct sackblk *sack = (struct sackblk *)(void *)to->to_sacks;
812 tcp_seq sack_seq;
813
814 while (!optlen || optlen % 4 != 2) {
815 optlen += TCPOLEN_NOP;
816 *optp++ = TCPOPT_NOP;
817 }
818 if (TCP_MAXOLEN - optlen < TCPOLEN_SACKHDR + TCPOLEN_SACK) {
819 continue;
820 }
821 optlen += TCPOLEN_SACKHDR;
822 *optp++ = TCPOPT_SACK;
823 sackblks = min(to->to_nsacks,
824 (TCP_MAXOLEN - optlen) / TCPOLEN_SACK);
825 *optp++ = TCPOLEN_SACKHDR + (uint8_t)sackblks * TCPOLEN_SACK;
826 while (sackblks--) {
827 sack_seq = htonl(sack->start);
828 bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq));
829 optp += sizeof(sack_seq);
830 optend = optend;
831 sack_seq = htonl(sack->end);
832 bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq));
833 optp += sizeof(sack_seq);
834 optend = optend;
835 optlen += TCPOLEN_SACK;
836 sack++;
837 }
838 tcpstat.tcps_sack_send_blocks++;
839 break;
840 }
841 default:
842 /* SYN cookies are disabled when TFO is used */
843 break;
844 }
845 }
846
847 /* Terminate and pad TCP options to a 4 byte boundary. */
848 if (optlen % 4) {
849 optlen += TCPOLEN_EOL;
850 *optp++ = TCPOPT_EOL;
851 }
852 /*
853 * According to RFC 793 (STD0007):
854 * "The content of the header beyond the End-of-Option option
855 * must be header padding (i.e., zero)."
856 * and later: "The padding is composed of zeros."
857 */
858 while (optlen % 4) {
859 optlen += TCPOLEN_EOL;
860 *optp++ = TCPOPT_EOL;
861 }
862
863 ASSERT(optlen <= TCP_MAXOLEN);
864 return optlen;
865 }
866 /*
867 * Set up the ECN information for the <SYN,ACK> from
868 * client SYN information.
869 */
870 static uint16_t
tcp_accecn_synack_respond(struct tcpcb * tp,uint16_t thflags)871 tcp_accecn_synack_respond(struct tcpcb * tp, uint16_t thflags)
872 {
873 /* Server received either legacy or Accurate ECN setup SYN */
874 if (tp->ecn_flags & (TE_SETUPRECEIVED | TE_ACE_SETUPRECEIVED)) {
875 if (tcp_send_ecn_flags_on_syn(tp)) {
876 if (tp->l4s_enabled && (tp->ecn_flags & TE_ACE_SETUPRECEIVED)) {
877 /*
878 * Accurate ECN mode is on. Initialize packet and byte counters
879 * for the server sending SYN-ACK. Although s_cep will be initialized
880 * during input processing of ACK of SYN-ACK, initialize here as well
881 * in case ACK gets lost.
882 *
883 * Non-zero initial values are used to
884 * support a stateless handshake (see
885 * Section 5.1 of AccECN draft) and to be
886 * distinct from cases where the fields
887 * are incorrectly zeroed.
888 */
889 tp->t_aecn.t_rcv_ce_packets = 5;
890 tp->t_aecn.t_snd_ce_packets = 5;
891
892 /* Initialize CE byte counter to 0 */
893 tp->t_aecn.t_rcv_ce_bytes = tp->t_aecn.t_snd_ce_bytes = 0;
894
895 if (tp->ecn_flags & TE_ACE_SETUP_NON_ECT) {
896 tp->t_prev_ace_flags = TH_CWR;
897 thflags |= tp->t_prev_ace_flags;
898 /* Remove the setup flag as it is also used for final ACK */
899 tp->ecn_flags &= ~TE_ACE_SETUP_NON_ECT;
900 tcpstat.tcps_ecn_ace_syn_not_ect++;
901 } else if (tp->ecn_flags & TE_ACE_SETUP_ECT1) {
902 tp->t_prev_ace_flags = (TH_CWR | TH_ECE);
903 thflags |= tp->t_prev_ace_flags;
904 tp->ecn_flags &= ~TE_ACE_SETUP_ECT1;
905 tcpstat.tcps_ecn_ace_syn_ect1++;
906 } else if (tp->ecn_flags & TE_ACE_SETUP_ECT0) {
907 tp->t_prev_ace_flags = TH_AE;
908 thflags |= tp->t_prev_ace_flags;
909 tp->ecn_flags &= ~TE_ACE_SETUP_ECT0;
910 tcpstat.tcps_ecn_ace_syn_ect0++;
911 } else if (tp->ecn_flags & TE_ACE_SETUP_CE) {
912 tp->t_prev_ace_flags = (TH_AE | TH_CWR);
913 thflags |= tp->t_prev_ace_flags;
914 tp->ecn_flags &= ~TE_ACE_SETUP_CE;
915 /*
916 * Receive counter is updated on
917 * all acceptable packets except
918 * CE on SYN packets (SYN=1, ACK=0)
919 */
920 tcpstat.tcps_ecn_ace_syn_ce++;
921 } else {
922 if (tp->t_prev_ace_flags != 0) {
923 /* Set the flags for retransmitted SYN-ACK same as the previous one */
924 thflags |= tp->t_prev_ace_flags;
925 } else {
926 /* We shouldn't come here */
927 panic("ECN flags (0x%x) not set correctly", tp->ecn_flags);
928 }
929 }
930 /*
931 * We now send ECT1 packets when
932 * L4S and Accurate ECN mode is on
933 */
934 tp->ecn_flags |= TE_ACE_SETUPSENT;
935 if (tp->l4s_enabled) {
936 tp->ecn_flags |= TE_SENDIPECT;
937 tcp_set_accurate_ecn(tp);
938 }
939 } else if (tp->ecn_flags & TE_SETUPRECEIVED) {
940 /*
941 * Setting TH_ECE makes this an ECN-setup
942 * SYN-ACK
943 */
944 thflags |= TH_ECE;
945 /*
946 * Record that we sent the ECN-setup and
947 * default to setting IP ECT.
948 */
949 tp->ecn_flags |= (TE_SETUPSENT | TE_SENDIPECT);
950 }
951 tcpstat.tcps_ecn_server_setup++;
952 tcpstat.tcps_ecn_server_success++;
953 } else {
954 /*
955 * For classic ECN, we sent an ECN-setup SYN-ACK but it was
956 * dropped. Fallback to non-ECN-setup
957 * SYN-ACK and clear flag to indicate that
958 * we should not send data with IP ECT set
959 *
960 * Pretend we didn't receive an
961 * ECN-setup SYN.
962 *
963 * We already incremented the counter
964 * assuming that the ECN setup will
965 * succeed. Decrementing here
966 * tcps_ecn_server_success to correct it.
967 *
968 * For Accurate ECN, we don't yet remove TE_ACE_SETUPRECEIVED
969 * as the client might have received Accurate ECN SYN-ACK.
970 * We decide Accurate ECN's state on processing last ACK from the client.
971 */
972 if (tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) {
973 tcpstat.tcps_ecn_lost_synack++;
974 tcpstat.tcps_ecn_server_success--;
975 tp->ecn_flags |= TE_LOST_SYNACK;
976 }
977 if (!tp->l4s_enabled) {
978 /* Do this only for classic ECN. */
979 tp->ecn_flags &=
980 ~(TE_SETUPRECEIVED | TE_SENDIPECT |
981 TE_SENDCWR);
982 }
983 }
984 }
985 return thflags;
986 }
987
988 /*
989 * Tcp output routine: figure out what should be sent and send it.
990 *
991 * Returns: 0 Success
992 * EADDRNOTAVAIL
993 * ENOBUFS
994 * EMSGSIZE
995 * EHOSTUNREACH
996 * ENETDOWN
997 * ip_output_list:ENOMEM
998 * ip_output_list:EADDRNOTAVAIL
999 * ip_output_list:ENETUNREACH
1000 * ip_output_list:EHOSTUNREACH
1001 * ip_output_list:EACCES
1002 * ip_output_list:EMSGSIZE
1003 * ip_output_list:ENOBUFS
1004 * ip_output_list:??? [ignorable: mostly IPSEC/firewall/DLIL]
1005 * ip6_output_list:EINVAL
1006 * ip6_output_list:EOPNOTSUPP
1007 * ip6_output_list:EHOSTUNREACH
1008 * ip6_output_list:EADDRNOTAVAIL
1009 * ip6_output_list:ENETUNREACH
1010 * ip6_output_list:EMSGSIZE
1011 * ip6_output_list:ENOBUFS
1012 * ip6_output_list:??? [ignorable: mostly IPSEC/firewall/DLIL]
1013 */
1014 int
tcp_output(struct tcpcb * tp)1015 tcp_output(struct tcpcb *tp)
1016 {
1017 uint32_t tcp_now_local = os_access_once(tcp_now);
1018 uint32_t *tsvalptr;
1019 uint64_t pacing_tx_time;
1020 struct inpcb *__single inp = tp->t_inpcb;
1021 struct socket *__single so = inp->inp_socket;
1022 int32_t len, recwin, sendwin, off;
1023 uint32_t max_len = 0;
1024 uint16_t flags;
1025 int error;
1026 mbuf_ref_t m;
1027 struct ip *ip = NULL;
1028 struct ip6_hdr *ip6 = NULL;
1029 struct tcphdr *th;
1030 u_char opt[TCP_MAXOLEN];
1031 unsigned int ipoptlen, optlen, hdrlen;
1032 int idle, sendalot, lost = 0;
1033 int sendalot_cnt = 0;
1034 int i, rack_sack_rxmit = 0;
1035 int tso = 0;
1036 int sack_bytes_rxmt;
1037 tcp_seq old_snd_nxt = 0;
1038 struct sackhole *p;
1039 struct tcp_seg_sent *seg;
1040 #if IPSEC
1041 size_t ipsec_optlen = 0;
1042 #endif /* IPSEC */
1043 int idle_time = 0;
1044 struct mbuf *__single packetlist = NULL;
1045 struct mbuf *__single tp_inp_options = inp->inp_depend4.inp4_options;
1046 int isipv6 = inp->inp_vflag & INP_IPV6;
1047 int packchain_listadd = 0;
1048 int so_options = so->so_options;
1049 rtentry_ref_t rt;
1050 u_int32_t svc_flags = 0, allocated_len;
1051 #if MPTCP
1052 boolean_t mptcp_acknow;
1053 #endif /* MPTCP */
1054 stats_functional_type ifnet_count_type = stats_functional_type_unclassified;
1055 int sotc = so->so_traffic_class;
1056 boolean_t do_not_compress = FALSE;
1057 bool sack_rescue_rxt = false;
1058 bool sack_rxmted = false;
1059 bool link_heuristics_enabled = false;
1060
1061 struct ifnet *outifp = inp != NULL ? inp->inp_last_outifp : NULL;
1062
1063 /*
1064 * Determine length of data that should be transmitted,
1065 * and flags that will be used.
1066 * If there is some data or critical controls (SYN, RST)
1067 * to send, then transmit; otherwise, investigate further.
1068 */
1069 idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
1070
1071 /* Since idle_time is signed integer, the following integer subtraction
1072 * will take care of wrap around of tcp_now
1073 */
1074 idle_time = tcp_now_local - tp->t_rcvtime;
1075 if (idle && idle_time >= TCP_IDLETIMEOUT(tp)) {
1076 if (CC_ALGO(tp)->after_idle != NULL &&
1077 ((tp->tcp_cc_index != TCP_CC_ALGO_CUBIC_INDEX &&
1078 tp->tcp_cc_index != TCP_CC_ALGO_PRAGUE_INDEX) ||
1079 idle_time >= TCP_CC_CWND_NONVALIDATED_PERIOD)) {
1080 CC_ALGO(tp)->after_idle(tp);
1081 tcp_ccdbg_trace(tp, NULL, TCP_CC_IDLE_TIMEOUT);
1082 }
1083
1084 /*
1085 * Do some other tasks that need to be done after
1086 * idle time
1087 */
1088 if (!SLIST_EMPTY(&tp->t_rxt_segments)) {
1089 tcp_rxtseg_clean(tp);
1090 }
1091
1092 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
1093 }
1094 tp->t_flags &= ~TF_LASTIDLE;
1095 if (idle) {
1096 if (tp->t_flags & TF_MORETOCOME) {
1097 tp->t_flags |= TF_LASTIDLE;
1098 idle = 0;
1099 }
1100 }
1101 #if MPTCP
1102 if (tp->t_mpflags & TMPF_RESET) {
1103 tcp_check_timer_state(tp);
1104 /*
1105 * Once a RST has been sent for an MPTCP subflow,
1106 * the subflow socket stays around until deleted.
1107 * No packets such as FINs must be sent after RST.
1108 */
1109 return 0;
1110 }
1111 #endif /* MPTCP */
1112
1113 link_heuristics_enabled = if_link_heuristics_enabled(outifp);
1114
1115 again:
1116 tcp_now_local = os_access_once(tcp_now);
1117 pacing_tx_time = 0;
1118 tsvalptr = NULL;
1119 #if MPTCP
1120 mptcp_acknow = FALSE;
1121
1122 if (so->so_flags & SOF_MP_SUBFLOW && SEQ_LT(tp->snd_nxt, tp->snd_una)) {
1123 os_log_error(mptcp_log_handle, "%s - %lx: snd_nxt is %u and snd_una is %u, cnt %d\n",
1124 __func__, (unsigned long)VM_KERNEL_ADDRPERM(tp->t_mpsub->mpts_mpte),
1125 tp->snd_nxt, tp->snd_una, sendalot_cnt);
1126 }
1127 #endif
1128 do_not_compress = FALSE;
1129 sendalot_cnt++;
1130
1131 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_START, 0, 0, 0, 0, 0);
1132
1133 if (isipv6) {
1134 KERNEL_DEBUG(DBG_LAYER_BEG,
1135 ((inp->inp_fport << 16) | inp->inp_lport),
1136 (((inp->in6p_laddr.s6_addr16[0] & 0xffff) << 16) |
1137 (inp->in6p_faddr.s6_addr16[0] & 0xffff)),
1138 sendalot, 0, 0);
1139 } else {
1140 KERNEL_DEBUG(DBG_LAYER_BEG,
1141 ((inp->inp_fport << 16) | inp->inp_lport),
1142 (((inp->inp_laddr.s_addr & 0xffff) << 16) |
1143 (inp->inp_faddr.s_addr & 0xffff)),
1144 sendalot, 0, 0);
1145 }
1146 /*
1147 * If the route generation id changed, we need to check that our
1148 * local (source) IP address is still valid. If it isn't either
1149 * return error or silently do nothing (assuming the address will
1150 * come back before the TCP connection times out).
1151 */
1152 rt = inp->inp_route.ro_rt;
1153 if (rt != NULL && ROUTE_UNUSABLE(&tp->t_inpcb->inp_route)) {
1154 struct ifnet *ifp;
1155 struct in_ifaddr *ia = NULL;
1156 struct in6_ifaddr *ia6 = NULL;
1157 int found_srcaddr = 0;
1158
1159 /* disable multipages at the socket */
1160 somultipages(so, FALSE);
1161
1162 /* Disable TSO for the socket until we know more */
1163 tp->t_flags &= ~TF_TSO;
1164
1165 soif2kcl(so, FALSE);
1166
1167 if (isipv6) {
1168 ia6 = ifa_foraddr6(&inp->in6p_laddr);
1169 if (ia6 != NULL) {
1170 found_srcaddr = 1;
1171 }
1172 } else {
1173 ia = ifa_foraddr(inp->inp_laddr.s_addr);
1174 if (ia != NULL) {
1175 found_srcaddr = 1;
1176 }
1177 }
1178
1179 /* check that the source address is still valid */
1180 if (found_srcaddr == 0) {
1181 soevent(so,
1182 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_NOSRCADDR));
1183
1184 if (tp->t_state >= TCPS_CLOSE_WAIT) {
1185 tcp_drop(tp, EADDRNOTAVAIL);
1186 return EADDRNOTAVAIL;
1187 }
1188
1189 /*
1190 * Set retransmit timer if it wasn't set,
1191 * reset Persist timer and shift register as the
1192 * advertised peer window may not be valid anymore
1193 */
1194 if (tp->t_timer[TCPT_REXMT] == 0) {
1195 tcp_set_rto(tp);
1196 if (tp->t_timer[TCPT_PERSIST] != 0) {
1197 tp->t_timer[TCPT_PERSIST] = 0;
1198 tp->t_persist_stop = 0;
1199 TCP_RESET_REXMT_STATE(tp);
1200 }
1201 }
1202
1203 if (tp->t_pktlist_head != NULL) {
1204 m_drop_list(tp->t_pktlist_head, NULL, DROPTAP_FLAG_DIR_OUT | DROPTAP_FLAG_L2_MISSING, DROP_REASON_TCP_SRC_ADDR_NOT_AVAIL, NULL, 0);
1205 }
1206 TCP_PKTLIST_CLEAR(tp);
1207
1208 /* drop connection if source address isn't available */
1209 if (so->so_flags & SOF_NOADDRAVAIL) {
1210 tcp_drop(tp, EADDRNOTAVAIL);
1211 return EADDRNOTAVAIL;
1212 } else {
1213 TCP_LOG_OUTPUT(tp, "no source address silently ignored");
1214 tcp_check_timer_state(tp);
1215 return 0; /* silently ignore, keep data in socket: address may be back */
1216 }
1217 }
1218 if (ia != NULL) {
1219 ifa_remref(&ia->ia_ifa);
1220 }
1221
1222 if (ia6 != NULL) {
1223 ifa_remref(&ia6->ia_ifa);
1224 }
1225
1226 /*
1227 * Address is still valid; check for multipages capability
1228 * again in case the outgoing interface has changed.
1229 */
1230 RT_LOCK(rt);
1231 if ((ifp = rt->rt_ifp) != NULL) {
1232 somultipages(so, (ifp->if_hwassist & IFNET_MULTIPAGES));
1233 tcp_set_tso(tp, ifp);
1234 soif2kcl(so, (ifp->if_eflags & IFEF_2KCL));
1235 /* Don't do ECN for Loopback & Cellular */
1236 if ((rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0 && !IFNET_IS_CELLULAR(ifp)) {
1237 tcp_set_ecn(tp);
1238 }
1239
1240 /*
1241 * If the route changes, we cannot use the link heuristics
1242 * based on the previous outgoing interface
1243 */
1244 if (rt->rt_ifp != tp->t_inpcb->inp_last_outifp) {
1245 link_heuristics_enabled = false;
1246 tp->t_comp_rxmt_gencnt = 0;
1247 }
1248 }
1249 if (rt->rt_flags & RTF_UP) {
1250 RT_GENID_SYNC(rt);
1251 }
1252 /*
1253 * See if we should do MTU discovery. Don't do it if:
1254 * 1) it is disabled via the sysctl
1255 * 2) the route isn't up
1256 * 3) the MTU is locked (if it is, then discovery
1257 * has been disabled)
1258 */
1259
1260 if (!path_mtu_discovery || ((rt != NULL) &&
1261 (!(rt->rt_flags & RTF_UP) ||
1262 (rt->rt_rmx.rmx_locks & RTV_MTU)))) {
1263 tp->t_flags &= ~TF_PMTUD;
1264 } else {
1265 tp->t_flags |= TF_PMTUD;
1266 }
1267
1268 RT_UNLOCK(rt);
1269 }
1270
1271 if (rt != NULL) {
1272 ifnet_count_type = IFNET_COUNT_TYPE(rt->rt_ifp);
1273 }
1274
1275 /*
1276 * If we've recently taken a timeout, snd_max will be greater than
1277 * snd_nxt. There may be SACK information that allows us to avoid
1278 * resending already delivered data. Adjust snd_nxt accordingly.
1279 * It is ok to use this function with RACK as well as it is estimating
1280 * max_len based on a SACK hole.
1281 */
1282 if (SACK_ENABLED(tp) && SEQ_LT(tp->snd_nxt, tp->snd_max)) {
1283 if (TCP_RACK_ENABLED(tp)) {
1284 /*
1285 * Calculated in the same manner as when rack_in_recovery
1286 * is set and new data is transmitted after retransmitted data
1287 */
1288 int32_t cwin = tp->snd_cwnd - tcp_flight_size(tp);
1289 if (cwin > 0) {
1290 max_len = tcp_rack_adjust(tp, (uint32_t)cwin);
1291 }
1292 } else {
1293 max_len = tcp_sack_adjust(tp);
1294 }
1295 }
1296 sendalot = 0;
1297 off = tp->snd_nxt - tp->snd_una;
1298 sendwin = min(tp->snd_wnd, tp->snd_cwnd);
1299
1300 if (tp->t_flags & TF_SLOWLINK && slowlink_wsize > 0) {
1301 sendwin = min(sendwin, slowlink_wsize);
1302 }
1303
1304 flags = tcp_outflags[tp->t_state];
1305 /*
1306 * Send any SACK-generated retransmissions. If we're explicitly
1307 * trying to send out new data (when sendalot is 1), bypass this
1308 * function. If we retransmit in fast recovery mode, decrement
1309 * snd_cwnd, since we're replacing a (future) new transmission
1310 * with a retransmission now, and we previously incremented
1311 * snd_cwnd in tcp_input().
1312 */
1313 /*
1314 * Still in sack recovery, reset rxmit flag to zero.
1315 */
1316 rack_sack_rxmit = 0;
1317 sack_bytes_rxmt = 0;
1318 len = 0;
1319 p = NULL;
1320 seg = NULL;
1321
1322 if (SACK_ENABLED(tp) && IN_FASTRECOVERY(tp)) {
1323 int32_t cwin = min(tp->snd_wnd, tp->snd_cwnd) - tcp_flight_size(tp);
1324 if (cwin <= 0 && sack_rxmted == false) {
1325 /* Allow to clock out at least on per period */
1326 cwin = tp->t_maxseg;
1327 }
1328
1329 sack_rxmted = true;
1330 if (cwin < 0) {
1331 cwin = 0;
1332 }
1333
1334 if (TCP_RACK_ENABLED(tp)) {
1335 uint16_t rack_seg_len = 0;
1336 if ((seg = tcp_rack_output(tp, cwin, &rack_seg_len)) != NULL) {
1337 len = min(cwin, rack_seg_len);
1338
1339 if (len > 0) {
1340 off = seg->start_seq - tp->snd_una;
1341 rack_sack_rxmit = 1;
1342 sendalot = 1;
1343 tcpstat.tcps_rack_rexmits++;
1344 } else {
1345 seg = NULL;
1346 }
1347 }
1348 } else if ((p = tcp_sack_output(tp, &sack_bytes_rxmt)) != NULL) {
1349 /* Do not retransmit SACK segments beyond snd_recover */
1350 if (SEQ_GT(p->end, tp->snd_recover)) {
1351 /*
1352 * (At least) part of sack hole extends beyond
1353 * snd_recover. Check to see if we can rexmit data
1354 * for this hole.
1355 */
1356 if (SEQ_GEQ(p->rxmit, tp->snd_recover)) {
1357 /*
1358 * Can't rexmit any more data for this hole.
1359 * That data will be rexmitted in the next
1360 * sack recovery episode, when snd_recover
1361 * moves past p->rxmit.
1362 */
1363 p = NULL;
1364 goto after_sack_rexmit;
1365 } else {
1366 /* Can rexmit part of the current hole */
1367 len = ((int32_t)min(cwin,
1368 tp->snd_recover - p->rxmit));
1369 }
1370 } else {
1371 len = ((int32_t)min(cwin, p->end - p->rxmit));
1372 }
1373 if (len > 0) {
1374 off = p->rxmit - tp->snd_una;
1375 rack_sack_rxmit = 1;
1376 sendalot = 1;
1377 /*
1378 * Optimization to avoid double retransmission due to SACK recovery
1379 * and when tp->snd_nxt points to already retransmitted segments
1380 */
1381 if (SEQ_LT(tp->snd_nxt, tp->snd_max) && SEQ_LEQ(tp->snd_nxt, p->rxmit) &&
1382 (uint32_t)len <= max_len) {
1383 sendalot = 0;
1384 }
1385
1386 tcpstat.tcps_sack_rexmits++;
1387 tcpstat.tcps_sack_rexmit_bytes +=
1388 min(len, tp->t_maxseg);
1389 } else {
1390 len = 0;
1391 }
1392 }
1393 }
1394 after_sack_rexmit:
1395 /*
1396 * Get standard flags, and add SYN or FIN if requested by 'hidden'
1397 * state flags.
1398 */
1399 if (tp->t_flags & TF_NEEDFIN) {
1400 flags |= TH_FIN;
1401 }
1402
1403 /*
1404 * If in persist timeout with window of 0, send 1 byte.
1405 * Otherwise, if window is small but nonzero
1406 * and timer expired, we will send what we can
1407 * and go to transmit state.
1408 */
1409 if (tp->t_flagsext & TF_FORCE) {
1410 if (sendwin == 0) {
1411 /*
1412 * If we still have some data to send, then
1413 * clear the FIN bit. Usually this would
1414 * happen below when it realizes that we
1415 * aren't sending all the data. However,
1416 * if we have exactly 1 byte of unsent data,
1417 * then it won't clear the FIN bit below,
1418 * and if we are in persist state, we wind
1419 * up sending the packet without recording
1420 * that we sent the FIN bit.
1421 *
1422 * We can't just blindly clear the FIN bit,
1423 * because if we don't have any more data
1424 * to send then the probe will be the FIN
1425 * itself.
1426 */
1427 if (off < so->so_snd.sb_cc) {
1428 flags &= ~TH_FIN;
1429 }
1430 sendwin = 1;
1431 } else {
1432 tp->t_timer[TCPT_PERSIST] = 0;
1433 tp->t_persist_stop = 0;
1434 TCP_RESET_REXMT_STATE(tp);
1435 }
1436 }
1437
1438 /*
1439 * If snd_nxt == snd_max and we have transmitted a FIN, the
1440 * offset will be > 0 even if so_snd.sb_cc is 0, resulting in
1441 * a negative length. This can also occur when TCP opens up
1442 * its congestion window while receiving additional duplicate
1443 * acks after fast-retransmit because TCP will reset snd_nxt
1444 * to snd_max after the fast-retransmit.
1445 *
1446 * In the normal retransmit-FIN-only case, however, snd_nxt will
1447 * be set to snd_una, the offset will be 0, and the length may
1448 * wind up 0.
1449 *
1450 * If sack_rxmit or rack_rxmit is true we are retransmitting from
1451 * the scoreboard in which case len is already set.
1452 */
1453 bool rack_in_recovery = TCP_RACK_ENABLED(tp) && IN_FASTRECOVERY(tp);
1454 if (rack_sack_rxmit == 0) {
1455 if (sack_bytes_rxmt == 0 && !rack_in_recovery) {
1456 len = min(so->so_snd.sb_cc, sendwin) - off;
1457 } else {
1458 int32_t cwin = tp->snd_cwnd - tcp_flight_size(tp);
1459 if (cwin < 0) {
1460 cwin = 0;
1461 }
1462 /*
1463 * We are inside of a SACK recovery episode and are
1464 * sending new data, having retransmitted all the
1465 * data possible in the scoreboard.
1466 */
1467 len = min(so->so_snd.sb_cc, tp->snd_wnd) - off;
1468 /*
1469 * Don't remove this (len > 0) check !
1470 * We explicitly check for len > 0 here (although it
1471 * isn't really necessary), to work around a gcc
1472 * optimization issue - to force gcc to compute
1473 * len above. Without this check, the computation
1474 * of len is bungled by the optimizer.
1475 */
1476 if (len > 0) {
1477 len = imin(len, cwin);
1478 } else {
1479 len = 0;
1480 }
1481 /*
1482 * At this point SACK recovery can not send any
1483 * data from scoreboard or any new data. Check
1484 * if we can do a rescue retransmit towards the
1485 * tail end of recovery window.
1486 * We don't do rescue retransmit for RACK.
1487 */
1488 if (len == 0 && cwin > 0 &&
1489 SEQ_LT(tp->snd_fack, tp->snd_recover) &&
1490 !(tp->t_flagsext & TF_RESCUE_RXT) && !TCP_RACK_ENABLED(tp)) {
1491 len = min((tp->snd_recover - tp->snd_fack),
1492 tp->t_maxseg);
1493 len = imin(len, cwin);
1494 old_snd_nxt = tp->snd_nxt;
1495 sack_rescue_rxt = true;
1496 tp->snd_nxt = tp->snd_recover - len;
1497 /*
1498 * If FIN has been sent, snd_max
1499 * must have been advanced to cover it.
1500 */
1501 if ((tp->t_flags & TF_SENTFIN) &&
1502 tp->snd_max == tp->snd_recover) {
1503 tp->snd_nxt--;
1504 }
1505
1506 off = tp->snd_nxt - tp->snd_una;
1507 sendalot = 0;
1508 tp->t_flagsext |= TF_RESCUE_RXT;
1509 }
1510 }
1511 }
1512
1513 if (max_len != 0 && len > 0) {
1514 len = min(len, max_len);
1515 }
1516
1517 /*
1518 * Lop off SYN bit if it has already been sent. However, if this
1519 * is SYN-SENT state and if segment contains data and if we don't
1520 * know that foreign host supports TAO, suppress sending segment.
1521 */
1522 if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
1523 if (tp->t_state == TCPS_SYN_RECEIVED && TFO_ENABLED(tp) && tp->snd_nxt == tp->snd_una + 1) {
1524 /* We are sending the SYN again! */
1525 off--;
1526 len++;
1527 } else {
1528 if (tp->t_state != TCPS_SYN_RECEIVED || TFO_ENABLED(tp)) {
1529 flags &= ~TH_SYN;
1530 }
1531
1532 off--;
1533 len++;
1534 if (len > 0 && tp->t_state == TCPS_SYN_SENT) {
1535 while (inp->inp_sndinprog_cnt == 0 &&
1536 tp->t_pktlist_head != NULL) {
1537 packetlist = tp->t_pktlist_head;
1538 packchain_listadd = tp->t_lastchain;
1539 packchain_sent++;
1540 TCP_PKTLIST_CLEAR(tp);
1541
1542 error = tcp_ip_output(so, tp, packetlist,
1543 packchain_listadd, tp_inp_options,
1544 (so_options & SO_DONTROUTE),
1545 (rack_sack_rxmit || (sack_bytes_rxmt != 0)),
1546 isipv6);
1547 }
1548
1549 /*
1550 * tcp was closed while we were in ip,
1551 * resume close
1552 */
1553 if (inp->inp_sndinprog_cnt == 0 &&
1554 (tp->t_flags & TF_CLOSING)) {
1555 tp->t_flags &= ~TF_CLOSING;
1556 (void) tcp_close(tp);
1557 } else {
1558 tcp_check_timer_state(tp);
1559 }
1560 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END,
1561 0, 0, 0, 0, 0);
1562 return 0;
1563 }
1564 }
1565 }
1566
1567 /*
1568 * Be careful not to send data and/or FIN on SYN segments.
1569 * This measure is needed to prevent interoperability problems
1570 * with not fully conformant TCP implementations.
1571 *
1572 * In case of TFO, we handle the setting of the len in
1573 * tcp_tfo_check. In case TFO is not enabled, never ever send
1574 * SYN+data.
1575 */
1576 if ((flags & TH_SYN) && !TFO_ENABLED(tp)) {
1577 len = 0;
1578 flags &= ~TH_FIN;
1579 }
1580
1581 /*
1582 * Don't send a RST with data.
1583 */
1584 if (flags & TH_RST) {
1585 len = 0;
1586 }
1587
1588 if ((flags & TH_SYN) && tp->t_state <= TCPS_SYN_SENT && TFO_ENABLED(tp)) {
1589 len = tcp_tfo_check(tp, len);
1590 }
1591
1592 if ((tp->tcp_cc_index == TCP_CC_ALGO_PRAGUE_INDEX || inp->inp_max_pacing_rate != UINT64_MAX) &&
1593 tp->t_pacer.tso_burst_size != 0 && len > 0 &&
1594 (uint32_t)len > tp->t_pacer.tso_burst_size) {
1595 len = tp->t_pacer.tso_burst_size;
1596 sendalot = 1;
1597 }
1598
1599 /*
1600 * The check here used to be (len < 0). Some times len is zero
1601 * when the congestion window is closed and we need to check
1602 * if persist timer has to be set in that case. But don't set
1603 * persist until connection is established.
1604 */
1605 if (len <= 0 && !(flags & TH_SYN)) {
1606 /*
1607 * If FIN has been sent but not acked,
1608 * but we haven't been called to retransmit,
1609 * len will be < 0. Otherwise, window shrank
1610 * after we sent into it. If window shrank to 0,
1611 * cancel pending retransmit, pull snd_nxt back
1612 * to (closed) window, and set the persist timer
1613 * if it isn't already going. If the window didn't
1614 * close completely, just wait for an ACK.
1615 */
1616 len = 0;
1617 if (sendwin == 0) {
1618 tp->t_timer[TCPT_REXMT] = 0;
1619 tp->t_timer[TCPT_PTO] = 0;
1620 TCP_RESET_REXMT_STATE(tp);
1621 tp->snd_nxt = tp->snd_una;
1622 off = 0;
1623 if (tp->t_timer[TCPT_PERSIST] == 0) {
1624 tcp_setpersist(tp);
1625 }
1626 }
1627 }
1628
1629 /*
1630 * Automatic sizing of send socket buffer. Increase the send
1631 * socket buffer size if all of the following criteria are met
1632 * 1. the receiver has enough buffer space for this data
1633 * 2. send buffer is filled to 7/8th with data (so we actually
1634 * have data to make use of it);
1635 * 3. our send window (slow start and congestion controlled) is
1636 * larger than sent but unacknowledged data in send buffer.
1637 */
1638 if (!INP_WAIT_FOR_IF_FEEDBACK(inp) && !IN_FASTRECOVERY(tp) &&
1639 (so->so_snd.sb_flags & (SB_AUTOSIZE | SB_TRIM)) == SB_AUTOSIZE) {
1640 if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat &&
1641 so->so_snd.sb_cc >= (so->so_snd.sb_hiwat / 8 * 7) &&
1642 sendwin >= (so->so_snd.sb_cc - (tp->snd_nxt - tp->snd_una))) {
1643 if (sbreserve(&so->so_snd,
1644 min(so->so_snd.sb_hiwat + tcp_autosndbuf_inc,
1645 tcp_autosndbuf_max)) == 1) {
1646 so->so_snd.sb_idealsize = so->so_snd.sb_hiwat;
1647 }
1648 }
1649 }
1650
1651 /*
1652 * Truncate to the maximum segment length or enable TCP Segmentation
1653 * Offloading (if supported by hardware) and ensure that FIN is removed
1654 * if the length no longer contains the last data byte.
1655 *
1656 * TSO may only be used if we are in a pure bulk sending state.
1657 * The presence of TCP-MD5, SACK retransmits, SACK advertizements,
1658 * filters and IP options, as well as disabling hardware checksum
1659 * offload prevent using TSO. With TSO the TCP header is the same
1660 * (except for the sequence number) for all generated packets. This
1661 * makes it impossible to transmit any options which vary per generated
1662 * segment or packet.
1663 *
1664 * The length of TSO bursts is limited to TCP_MAXWIN. That limit and
1665 * removal of FIN (if not already catched here) are handled later after
1666 * the exact length of the TCP options are known.
1667 */
1668 #if IPSEC
1669 /*
1670 * Pre-calculate here as we save another lookup into the darknesses
1671 * of IPsec that way and can actually decide if TSO is ok.
1672 */
1673 if (ipsec_bypass == 0) {
1674 ipsec_optlen = ipsec_hdrsiz_tcp(tp);
1675 }
1676 #endif
1677 if (len > tp->t_maxseg) {
1678 if ((tp->t_flags & TF_TSO) && tcp_do_tso && hwcksum_tx &&
1679 kipf_count == 0 &&
1680 tp->rcv_numsacks == 0 && rack_sack_rxmit == 0 &&
1681 sack_bytes_rxmt == 0 &&
1682 inp->inp_options == NULL &&
1683 inp->in6p_options == NULL
1684 #if IPSEC
1685 && ipsec_optlen == 0
1686 #endif
1687 ) {
1688 tso = 1;
1689 sendalot = 0;
1690 } else {
1691 len = tp->t_maxseg;
1692 sendalot = 1;
1693 tso = 0;
1694 }
1695 } else {
1696 tso = 0;
1697 }
1698
1699 /* Send one segment or less as a tail loss probe */
1700 if (tp->t_flagsext & TF_SENT_TLPROBE) {
1701 len = min(len, tp->t_maxseg);
1702 sendalot = 0;
1703 tso = 0;
1704 }
1705
1706 #if MPTCP
1707 if (so->so_flags & SOF_MP_SUBFLOW && off < 0) {
1708 os_log_error(mptcp_log_handle, "%s - %lx: offset is negative! len %d off %d\n",
1709 __func__, (unsigned long)VM_KERNEL_ADDRPERM(tp->t_mpsub->mpts_mpte),
1710 len, off);
1711 }
1712
1713 if ((so->so_flags & SOF_MP_SUBFLOW) &&
1714 !(tp->t_mpflags & TMPF_TCP_FALLBACK)) {
1715 int newlen = len;
1716 struct mptcb *mp_tp = tptomptp(tp);
1717 if (tp->t_state >= TCPS_ESTABLISHED &&
1718 (tp->t_mpflags & TMPF_SND_MPPRIO ||
1719 tp->t_mpflags & TMPF_SND_REM_ADDR ||
1720 tp->t_mpflags & TMPF_SND_MPFAIL ||
1721 (tp->t_mpflags & TMPF_SND_KEYS &&
1722 mp_tp->mpt_version == MPTCP_VERSION_0) ||
1723 tp->t_mpflags & TMPF_SND_JACK ||
1724 tp->t_mpflags & TMPF_MPTCP_ECHO_ADDR)) {
1725 if (len > 0) {
1726 len = 0;
1727 tso = 0;
1728 }
1729 /*
1730 * On a new subflow, don't try to send again, because
1731 * we are still waiting for the fourth ack.
1732 */
1733 if (!(tp->t_mpflags & TMPF_PREESTABLISHED)) {
1734 sendalot = 1;
1735 }
1736 mptcp_acknow = TRUE;
1737 } else {
1738 mptcp_acknow = FALSE;
1739 }
1740 /*
1741 * The contiguous bytes in the subflow socket buffer can be
1742 * discontiguous at the MPTCP level. Since only one DSS
1743 * option can be sent in one packet, reduce length to match
1744 * the contiguous MPTCP level. Set sendalot to send remainder.
1745 */
1746 if (len > 0 && off >= 0) {
1747 newlen = mptcp_adj_sendlen(so, off);
1748 }
1749
1750 if (newlen < len) {
1751 len = newlen;
1752 if (len <= tp->t_maxseg) {
1753 tso = 0;
1754 }
1755 }
1756 }
1757 #endif /* MPTCP */
1758
1759 if (rack_sack_rxmit) {
1760 if (TCP_RACK_ENABLED(tp)) {
1761 if (SEQ_LT(seg->start_seq + len, tp->snd_una + so->so_snd.sb_cc)) {
1762 flags &= ~TH_FIN;
1763 }
1764 } else {
1765 if (SEQ_LT(p->rxmit + len, tp->snd_una + so->so_snd.sb_cc)) {
1766 flags &= ~TH_FIN;
1767 }
1768 }
1769 } else {
1770 if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc)) {
1771 flags &= ~TH_FIN;
1772 }
1773 }
1774 /*
1775 * Compare available window to amount of window
1776 * known to peer (as advertised window less
1777 * next expected input). If the difference is at least two
1778 * max size segments, or at least 25% of the maximum possible
1779 * window, then want to send a window update to peer.
1780 */
1781 recwin = tcp_sbspace(tp);
1782
1783 if (!(so->so_flags & SOF_MP_SUBFLOW)) {
1784 if (recwin < (int32_t)(so->so_rcv.sb_hiwat / 4) &&
1785 recwin < (int)tp->t_maxseg) {
1786 recwin = 0;
1787 }
1788 } else {
1789 struct mptcb *mp_tp = tptomptp(tp);
1790 struct socket *mp_so = mptetoso(mp_tp->mpt_mpte);
1791
1792 if (recwin < (int32_t)(mp_so->so_rcv.sb_hiwat / 4) &&
1793 recwin < (int)tp->t_maxseg) {
1794 recwin = 0;
1795 }
1796 }
1797
1798 #if TRAFFIC_MGT
1799 if (tcp_recv_bg == 1 || IS_TCP_RECV_BG(so)) {
1800 /*
1801 * Timestamp MUST be supported to use rledbat unless we haven't
1802 * yet negotiated it.
1803 */
1804 if (TCP_RLEDBAT_ENABLED(tp) || (tcp_rledbat && tp->t_state <
1805 TCPS_ESTABLISHED)) {
1806 if (recwin > 0 && tcp_cc_rledbat.get_rlwin != NULL) {
1807 /* Min of flow control window and rledbat window */
1808 recwin = imin(recwin, tcp_cc_rledbat.get_rlwin(tp));
1809 }
1810 } else if (recwin > 0 && tcp_recv_throttle(tp)) {
1811 uint32_t min_iaj_win = tcp_min_iaj_win * tp->t_maxseg;
1812 uint32_t bg_rwintop = tp->rcv_adv;
1813 if (SEQ_LT(bg_rwintop, tp->rcv_nxt + min_iaj_win)) {
1814 bg_rwintop = tp->rcv_nxt + min_iaj_win;
1815 }
1816 recwin = imin((int32_t)(bg_rwintop - tp->rcv_nxt),
1817 recwin);
1818 if (recwin < 0) {
1819 recwin = 0;
1820 }
1821 }
1822 }
1823 #endif /* TRAFFIC_MGT */
1824
1825 if (recwin > (int32_t)(TCP_MAXWIN << tp->rcv_scale)) {
1826 recwin = (int32_t)(TCP_MAXWIN << tp->rcv_scale);
1827 }
1828
1829 if (!(so->so_flags & SOF_MP_SUBFLOW)) {
1830 if (recwin < (int32_t)(tp->rcv_adv - tp->rcv_nxt)) {
1831 recwin = (int32_t)(tp->rcv_adv - tp->rcv_nxt);
1832 }
1833 } else {
1834 struct mptcb *mp_tp = tptomptp(tp);
1835 int64_t recwin_announced = (int64_t)(mp_tp->mpt_rcvadv - mp_tp->mpt_rcvnxt);
1836
1837 /* Don't remove what we announced at the MPTCP-layer */
1838 VERIFY(recwin_announced < INT32_MAX && recwin_announced > INT32_MIN);
1839 if (recwin < (int32_t)recwin_announced) {
1840 recwin = (int32_t)recwin_announced;
1841 }
1842
1843 if (mp_tp->mpt_flags & MPTCPF_FALLBACK_TO_TCP) {
1844 if (recwin < (int32_t)(tp->rcv_adv - tp->rcv_nxt)) {
1845 recwin = (int32_t)(tp->rcv_adv - tp->rcv_nxt);
1846 }
1847 }
1848 }
1849
1850 /* One day we should have a single ROUNDUP macro across xnu... */
1851 #ifndef ROUNDUP
1852 #define ROUNDUP(a, b) (((a) + ((b) - 1)) & (~((b) - 1)))
1853 #endif
1854 recwin = ROUNDUP(recwin, (1 << tp->rcv_scale));
1855 #undef ROUNDUP
1856
1857 /*
1858 * Sender silly window avoidance. We transmit under the following
1859 * conditions when len is non-zero:
1860 *
1861 * - we've timed out (e.g. persist timer)
1862 * - we need to retransmit
1863 * - We have a full segment (or more with TSO)
1864 * - This is the last buffer in a write()/send() and we are
1865 * either idle or running NODELAY
1866 * - we have more then 1/2 the maximum send window's worth of
1867 * data (receiver may be limited the window size)
1868 */
1869 if (len) {
1870 if (tp->t_flagsext & TF_FORCE) {
1871 goto send;
1872 }
1873 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
1874 if (TCP_RACK_ENABLED(tp) && rack_sack_rxmit == 0) {
1875 len = min(len, tp->snd_max - tp->snd_nxt);
1876 }
1877 goto send;
1878 }
1879 if (rack_sack_rxmit) {
1880 goto send;
1881 }
1882
1883 /*
1884 * If this here is the first segment after SYN/ACK and TFO
1885 * is being used, then we always send it, regardless of Nagle,...
1886 */
1887 if (tp->t_state == TCPS_SYN_RECEIVED &&
1888 TFO_ENABLED(tp) &&
1889 (tp->t_tfo_flags & TFO_F_COOKIE_VALID) &&
1890 tp->snd_nxt == tp->iss + 1) {
1891 goto send;
1892 }
1893
1894 /*
1895 * Send new data on the connection only if it is
1896 * not flow controlled
1897 */
1898 if (!INP_WAIT_FOR_IF_FEEDBACK(inp) ||
1899 tp->t_state != TCPS_ESTABLISHED) {
1900 if (off + len == tp->snd_wnd) {
1901 /* We are limited by the receiver's window... */
1902 if (tp->t_rcvwnd_limited_start_time == 0) {
1903 tp->t_rcvwnd_limited_start_time = net_uptime_us();
1904 }
1905 } else {
1906 /* We are no more limited by the receiver's window... */
1907 if (tp->t_rcvwnd_limited_start_time != 0) {
1908 uint64_t now = net_uptime_us();
1909
1910 ASSERT(now >= tp->t_rcvwnd_limited_start_time);
1911
1912 tp->t_rcvwnd_limited_total_time += (now - tp->t_rcvwnd_limited_start_time);
1913
1914 tp->t_rcvwnd_limited_start_time = 0;
1915 }
1916 }
1917
1918 if (len >= tp->t_maxseg) {
1919 goto send;
1920 }
1921
1922 if (!(tp->t_flags & TF_MORETOCOME) &&
1923 (idle || tp->t_flags & TF_NODELAY ||
1924 (tp->t_flags & TF_MAXSEGSNT) ||
1925 ALLOW_LIMITED_TRANSMIT(tp)) &&
1926 (tp->t_flags & TF_NOPUSH) == 0 &&
1927 (len + off >= so->so_snd.sb_cc ||
1928 /*
1929 * MPTCP needs to respect the DSS-mappings. So, it
1930 * may be sending data that *could* have been
1931 * coalesced, but cannot because of
1932 * mptcp_adj_sendlen().
1933 */
1934 so->so_flags & SOF_MP_SUBFLOW)) {
1935 goto send;
1936 }
1937 if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
1938 goto send;
1939 }
1940 } else {
1941 tcpstat.tcps_fcholdpacket++;
1942 }
1943 }
1944
1945 if (recwin > 0) {
1946 /*
1947 * "adv" is the amount we can increase the window,
1948 * taking into account that we are limited by
1949 * TCP_MAXWIN << tp->rcv_scale.
1950 */
1951 int32_t adv, oldwin = 0;
1952 adv = imin(recwin, (int)TCP_MAXWIN << tp->rcv_scale) -
1953 (tp->rcv_adv - tp->rcv_nxt);
1954
1955 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
1956 oldwin = tp->rcv_adv - tp->rcv_nxt;
1957 }
1958
1959 if (adv >= (int32_t) (2 * tp->t_maxseg)) {
1960 /*
1961 * ACK every second full-sized segment, if the
1962 * ACK is advancing or the window becomes bigger
1963 */
1964 if (so->so_rcv.sb_cc < so->so_rcv.sb_lowat &&
1965 (tp->last_ack_sent != tp->rcv_nxt ||
1966 ((oldwin + adv) >> tp->rcv_scale) >
1967 (oldwin >> tp->rcv_scale))) {
1968 goto send;
1969 }
1970 } else if (tp->t_flags & TF_DELACK) {
1971 /*
1972 * If we delayed the ACK and the window
1973 * is not advancing by a lot (< 2MSS), ACK
1974 * immediately if the last incoming packet had
1975 * the push flag set and we emptied the buffer.
1976 *
1977 * This takes care of a sender doing small
1978 * repeated writes with Nagle enabled.
1979 */
1980 if (so->so_rcv.sb_cc == 0 &&
1981 tp->last_ack_sent != tp->rcv_nxt &&
1982 (tp->t_flagsext & TF_LAST_IS_PSH)) {
1983 goto send;
1984 }
1985 }
1986
1987 if (4 * adv >= (int32_t) so->so_rcv.sb_hiwat) {
1988 goto send;
1989 }
1990 }
1991
1992 /*
1993 * Send if we owe the peer an ACK, RST, SYN, or urgent data. ACKNOW
1994 * is also a catch-all for the retransmit timer timeout case.
1995 */
1996 if (tp->t_flags & TF_ACKNOW) {
1997 if (tp->t_forced_acks > 0) {
1998 tp->t_forced_acks--;
1999 }
2000 goto send;
2001 }
2002 if ((flags & TH_RST) || (flags & TH_SYN)) {
2003 goto send;
2004 }
2005 if (SEQ_GT(tp->snd_up, tp->snd_una)) {
2006 goto send;
2007 }
2008 #if MPTCP
2009 if (mptcp_acknow) {
2010 goto send;
2011 }
2012 #endif /* MPTCP */
2013 /*
2014 * If our state indicates that FIN should be sent
2015 * and we have not yet done so, then we need to send.
2016 */
2017 if ((flags & TH_FIN) &&
2018 (!(tp->t_flags & TF_SENTFIN) || tp->snd_nxt == tp->snd_una)) {
2019 goto send;
2020 }
2021 /*
2022 * In SACK, it is possible for tcp_output to fail to send a segment
2023 * after the retransmission timer has been turned off. Make sure
2024 * that the retransmission timer is set.
2025 */
2026 if (SACK_ENABLED(tp) && (tp->t_state >= TCPS_ESTABLISHED) &&
2027 SEQ_GT(tp->snd_max, tp->snd_una) &&
2028 tp->t_timer[TCPT_REXMT] == 0 &&
2029 tp->t_timer[TCPT_PERSIST] == 0) {
2030 tcp_set_rto(tp);
2031 goto just_return;
2032 }
2033 /*
2034 * TCP window updates are not reliable, rather a polling protocol
2035 * using ``persist'' packets is used to insure receipt of window
2036 * updates. The three ``states'' for the output side are:
2037 * idle not doing retransmits or persists
2038 * persisting to move a small or zero window
2039 * (re)transmitting and thereby not persisting
2040 *
2041 * tp->t_timer[TCPT_PERSIST]
2042 * is set when we are in persist state.
2043 * tp->t_force
2044 * is set when we are called to send a persist packet.
2045 * tp->t_timer[TCPT_REXMT]
2046 * is set when we are retransmitting
2047 * The output side is idle when both timers are zero.
2048 *
2049 * If send window is too small, there is data to transmit, and no
2050 * retransmit or persist is pending, then go to persist state.
2051 * If nothing happens soon, send when timer expires:
2052 * if window is nonzero, transmit what we can,
2053 * otherwise force out a byte.
2054 */
2055 if (so->so_snd.sb_cc && tp->t_timer[TCPT_REXMT] == 0 &&
2056 tp->t_timer[TCPT_PERSIST] == 0) {
2057 TCP_RESET_REXMT_STATE(tp);
2058 tcp_setpersist(tp);
2059 }
2060 just_return:
2061 /*
2062 * If there is no reason to send a segment, just return.
2063 * but if there is some packets left in the packet list, send them now.
2064 */
2065 while (inp->inp_sndinprog_cnt == 0 &&
2066 tp->t_pktlist_head != NULL) {
2067 packetlist = tp->t_pktlist_head;
2068 packchain_listadd = tp->t_lastchain;
2069 packchain_sent++;
2070 TCP_PKTLIST_CLEAR(tp);
2071
2072 error = tcp_ip_output(so, tp, packetlist,
2073 packchain_listadd,
2074 tp_inp_options, (so_options & SO_DONTROUTE),
2075 (rack_sack_rxmit || (sack_bytes_rxmt != 0)), isipv6);
2076 }
2077 /* tcp was closed while we were in ip; resume close */
2078 if (inp->inp_sndinprog_cnt == 0 &&
2079 (tp->t_flags & TF_CLOSING)) {
2080 tp->t_flags &= ~TF_CLOSING;
2081 (void) tcp_close(tp);
2082 } else {
2083 tcp_check_timer_state(tp);
2084 }
2085 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
2086 return 0;
2087
2088 send:
2089 /*
2090 * Set TF_MAXSEGSNT flag if the segment size is greater than
2091 * the max segment size.
2092 */
2093 if (len > 0) {
2094 do_not_compress = TRUE;
2095
2096 if (len >= tp->t_maxseg) {
2097 tp->t_flags |= TF_MAXSEGSNT;
2098 } else {
2099 tp->t_flags &= ~TF_MAXSEGSNT;
2100 }
2101 }
2102 /*
2103 * If we are connected and no segment has been ACKed or SACKed yet and we
2104 * hit a retransmission timeout, then we should disable AccECN option
2105 * for the rest of the connection.
2106 */
2107 if (tp->accurate_ecn_on && tp->t_state == TCPS_ESTABLISHED &&
2108 tp->snd_una == tp->iss + 1 && (tp->snd_fack == tp->iss)
2109 && tp->t_rxtshift > 0) {
2110 if ((tp->ecn_flags & TE_RETRY_WITHOUT_ACO) == 0) {
2111 tp->ecn_flags |= TE_RETRY_WITHOUT_ACO;
2112 }
2113 }
2114
2115 /*
2116 * Before ESTABLISHED, force sending of initial options
2117 * unless TCP set not to do any options.
2118 * NOTE: we assume that the IP/TCP header plus TCP options
2119 * always fit in a single mbuf, leaving room for a maximum
2120 * link header, i.e.
2121 * max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
2122 */
2123 optlen = 0;
2124 if (isipv6) {
2125 hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
2126 } else {
2127 hdrlen = sizeof(struct tcpiphdr);
2128 }
2129 if (flags & TH_SYN) {
2130 tp->snd_nxt = tp->iss;
2131 tp->snd_fack = tp->iss;
2132 if ((tp->t_flags & TF_NOOPT) == 0) {
2133 u_short mss;
2134
2135 opt[0] = TCPOPT_MAXSEG;
2136 opt[1] = TCPOLEN_MAXSEG;
2137 mss = htons((u_short) tcp_mssopt(tp));
2138 (void)memcpy(opt + 2, &mss, sizeof(mss));
2139 optlen = TCPOLEN_MAXSEG;
2140
2141 if ((tp->t_flags & TF_REQ_SCALE) &&
2142 ((flags & TH_ACK) == 0 ||
2143 (tp->t_flags & TF_RCVD_SCALE))) {
2144 *((u_int32_t *)(void *)(opt + optlen)) = htonl(
2145 TCPOPT_NOP << 24 |
2146 TCPOPT_WINDOW << 16 |
2147 TCPOLEN_WINDOW << 8 |
2148 tp->request_r_scale);
2149 optlen += 4;
2150 }
2151 /* Check if L4S is enabled after outifp has been set and update the CC */
2152 if (tp->l4s_enabled && tp->tcp_cc_index == TCP_CC_ALGO_CUBIC_INDEX) {
2153 tcp_set_foreground_cc(so);
2154 }
2155 #if MPTCP
2156 if (mptcp_enable && (so->so_flags & SOF_MP_SUBFLOW)) {
2157 optlen = mptcp_setup_syn_opts(so, opt, opt + sizeof(opt), optlen);
2158 }
2159 #endif /* MPTCP */
2160 }
2161 }
2162
2163 /*
2164 * Send a timestamp and echo-reply if this is a SYN and our side
2165 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
2166 * and our peer have sent timestamps in our SYN's.
2167 */
2168 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
2169 (flags & TH_RST) == 0 &&
2170 ((flags & TH_ACK) == 0 ||
2171 (tp->t_flags & TF_RCVD_TSTMP))) {
2172 uint32_t *lp = (u_int32_t *)(void *)(opt + optlen);
2173
2174 /* Form timestamp option as shown in appendix A of RFC 1323. */
2175 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
2176
2177 tsvalptr = lp;
2178 lp++; /* tsval will be set later (see access to tsvalptr) */
2179 *lp = htonl(tp->ts_recent);
2180 optlen += TCPOLEN_TSTAMP_APPA;
2181 }
2182
2183 if (SACK_ENABLED(tp) && ((tp->t_flags & TF_NOOPT) == 0)) {
2184 /*
2185 * Tack on the SACK permitted option *last*.
2186 * And do padding of options after tacking this on.
2187 * This is because of MSS, TS, WinScale and Signatures are
2188 * all present, we have just 2 bytes left for the SACK
2189 * permitted option, which is just enough.
2190 */
2191 /*
2192 * If this is the first SYN of connection (not a SYN
2193 * ACK), include SACK permitted option. If this is a
2194 * SYN ACK, include SACK permitted option if peer has
2195 * already done so. This is only for active connect,
2196 * since the syncookie takes care of the passive connect.
2197 */
2198 if ((flags & TH_SYN) &&
2199 (!(flags & TH_ACK) || (tp->t_flags & TF_SACK_PERMIT))) {
2200 u_char *bp;
2201 bp = (u_char *)opt + optlen;
2202
2203 *bp++ = TCPOPT_SACK_PERMITTED;
2204 *bp++ = TCPOLEN_SACK_PERMITTED;
2205 optlen += TCPOLEN_SACK_PERMITTED;
2206 }
2207 }
2208 #if MPTCP
2209 if (so->so_flags & SOF_MP_SUBFLOW) {
2210 /*
2211 * Its important to piggyback acks with data as ack only packets
2212 * may get lost and data packets that don't send Data ACKs
2213 * still advance the subflow level ACK and therefore make it
2214 * hard for the remote end to recover in low cwnd situations.
2215 */
2216 if (len != 0) {
2217 tp->t_mpflags |= (TMPF_SEND_DSN |
2218 TMPF_MPTCP_ACKNOW);
2219 } else {
2220 tp->t_mpflags |= TMPF_MPTCP_ACKNOW;
2221 }
2222 optlen = mptcp_setup_opts(tp, off, opt, opt + TCP_MAXOLEN, optlen, flags,
2223 len, &mptcp_acknow, &do_not_compress);
2224 tp->t_mpflags &= ~TMPF_SEND_DSN;
2225 }
2226 #endif /* MPTCP */
2227
2228 if (TFO_ENABLED(tp) && !(tp->t_flags & TF_NOOPT) &&
2229 (flags & (TH_SYN | TH_ACK)) == TH_SYN) {
2230 optlen += tcp_tfo_write_cookie(tp, optlen, len, opt);
2231 }
2232
2233 if (TFO_ENABLED(tp) &&
2234 (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK) &&
2235 (tp->t_tfo_flags & TFO_F_OFFER_COOKIE)) {
2236 optlen += tcp_tfo_write_cookie_rep(tp, optlen, opt);
2237 }
2238
2239 if (SACK_ENABLED(tp) && ((tp->t_flags & TF_NOOPT) == 0)) {
2240 /*
2241 * Send SACKs if necessary. This should be the last
2242 * option processed. Only as many SACKs are sent as
2243 * are permitted by the maximum options size.
2244 *
2245 * In general, SACK blocks consume 8*n+2 bytes.
2246 * So a full size SACK blocks option is 34 bytes
2247 * (to generate 4 SACK blocks). At a minimum,
2248 * we need 10 bytes (to generate 1 SACK block).
2249 * If TCP Timestamps (12 bytes) and TCP Signatures
2250 * (18 bytes) are both present, we'll just have
2251 * 10 bytes for SACK options 40 - (12 + 18).
2252 */
2253 if (TCPS_HAVEESTABLISHED(tp->t_state) &&
2254 (tp->t_flags & TF_SACK_PERMIT) &&
2255 (tp->rcv_numsacks > 0 || TCP_SEND_DSACK_OPT(tp)) &&
2256 MAX_TCPOPTLEN - optlen >= TCPOLEN_SACK + 2) {
2257 unsigned int sackoptlen = 0;
2258 int nsack, padlen;
2259 u_char *bp = (u_char *)opt + optlen;
2260 u_int32_t *lp;
2261
2262 nsack = (MAX_TCPOPTLEN - optlen - 2) / TCPOLEN_SACK;
2263 /*
2264 * Send lesser SACK blocks when we want
2265 * to send the smallest recommended AccECN Option
2266 * if the space wouldn't permit sending all blocks.
2267 */
2268 if (nsack > 2 && tp->accurate_ecn_on &&
2269 (tp->ecn_flags & TE_RETRY_WITHOUT_ACO) == 0 &&
2270 tp->ecn_flags & (TE_ACO_ECT1 | TE_ACO_ECT0)) {
2271 nsack--;
2272 }
2273 nsack = min(nsack, (tp->rcv_numsacks +
2274 (TCP_SEND_DSACK_OPT(tp) ? 1 : 0)));
2275 sackoptlen = (2 + nsack * TCPOLEN_SACK);
2276 VERIFY(sackoptlen < UINT8_MAX);
2277
2278 /*
2279 * First we need to pad options so that the
2280 * SACK blocks can start at a 4-byte boundary
2281 * (sack option and length are at a 2 byte offset).
2282 */
2283 padlen = (MAX_TCPOPTLEN - optlen - sackoptlen) % 4;
2284 optlen += padlen;
2285 while (padlen-- > 0) {
2286 *bp++ = TCPOPT_NOP;
2287 }
2288
2289 tcpstat.tcps_sack_send_blocks++;
2290 *bp++ = TCPOPT_SACK;
2291 *bp++ = (uint8_t)sackoptlen;
2292 lp = (u_int32_t *)(void *)bp;
2293
2294 /*
2295 * First block of SACK option should represent
2296 * DSACK. Prefer to send SACK information if there
2297 * is space for only one SACK block. This will
2298 * allow for faster recovery.
2299 */
2300 if (TCP_SEND_DSACK_OPT(tp) && nsack > 0 &&
2301 (tp->rcv_numsacks == 0 || nsack > 1)) {
2302 *lp++ = htonl(tp->t_dsack_lseq);
2303 *lp++ = htonl(tp->t_dsack_rseq);
2304 tcpstat.tcps_dsack_sent++;
2305 tp->t_dsack_sent++;
2306 nsack--;
2307 }
2308 VERIFY(nsack == 0 || tp->rcv_numsacks >= nsack);
2309 for (i = 0; i < nsack; i++) {
2310 struct sackblk sack = tp->sackblks[i];
2311 *lp++ = htonl(sack.start);
2312 *lp++ = htonl(sack.end);
2313 }
2314 optlen += sackoptlen;
2315
2316 /* Make sure we didn't write too much */
2317 VERIFY((u_char *)lp - opt <= MAX_TCPOPTLEN);
2318 }
2319 }
2320
2321 /*
2322 * AccECN option - after SACK
2323 * Don't send on <SYN>,
2324 * send only on <SYN,ACK> before ACCECN is negotiated when
2325 * the client requests it or
2326 * when doing an AccECN session. Don't send AccECN option
2327 * if retransmitting a SYN-ACK or a data segment
2328 */
2329 if ((tp->accurate_ecn_on ||
2330 (tp->l4s_enabled && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK) &&
2331 (tp->ecn_flags & TE_ACE_SETUPRECEIVED))) &&
2332 (tp->ecn_flags & TE_RETRY_WITHOUT_ACO) == 0) {
2333 uint32_t *lp = (uint32_t *)(void *)(opt + optlen);
2334 /* lp will become outdated after options are added */
2335 tcp_add_accecn_option(tp, flags, lp, (uint8_t *)&optlen);
2336 /* Make sure we didn't write more than 40 bytes */
2337 ASSERT((u_char *)lp - opt <= MAX_TCPOPTLEN);
2338 }
2339 /* Pad TCP options to a 4 byte boundary */
2340 if (optlen < MAX_TCPOPTLEN && (optlen % sizeof(u_int32_t))) {
2341 int pad = sizeof(u_int32_t) - (optlen % sizeof(u_int32_t));
2342 u_char *bp = (u_char *)opt + optlen;
2343
2344 optlen += pad;
2345 while (pad) {
2346 *bp++ = TCPOPT_EOL;
2347 pad--;
2348 }
2349 }
2350
2351 /*
2352 * For Accurate ECN, send ACE flag based on r.cep, if
2353 * We have completed handshake and are in ESTABLISHED state, and
2354 * This is not the final ACK of 3WHS.
2355 */
2356 if (tp->accurate_ecn_on && TCPS_HAVEESTABLISHED(tp->t_state) &&
2357 (tp->ecn_flags & TE_ACE_FINAL_ACK_3WHS) == 0) {
2358 uint8_t ace = tp->t_aecn.t_rcv_ce_packets & TCP_ACE_MASK;
2359 if (ace & 0x01) {
2360 flags |= TH_ECE;
2361 } else {
2362 flags &= ~TH_ECE;
2363 }
2364 if (ace & 0x02) {
2365 flags |= TH_CWR;
2366 } else {
2367 flags &= ~TH_CWR;
2368 }
2369 if (ace & 0x04) {
2370 flags |= TH_AE;
2371 } else {
2372 flags &= ~TH_AE;
2373 }
2374 }
2375
2376 /*
2377 * RFC 3168 states that:
2378 * - If you ever sent an ECN-setup SYN/SYN-ACK you must be prepared
2379 * to handle the TCP ECE flag, even if you also later send a
2380 * non-ECN-setup SYN/SYN-ACK.
2381 * - If you ever send a non-ECN-setup SYN/SYN-ACK, you must not set
2382 * the ip ECT flag.
2383 *
2384 * It is not clear how the ECE flag would ever be set if you never
2385 * set the IP ECT flag on outbound packets. All the same, we use
2386 * the TE_SETUPSENT to indicate that we have committed to handling
2387 * the TCP ECE flag correctly. We use the TE_SENDIPECT to indicate
2388 * whether or not we should set the IP ECT flag on outbound packet
2389 *
2390 * For a SYN-ACK, send an ECN setup SYN-ACK
2391 *
2392 * Below we send ECN for three different handhshake states:
2393 * 1. Server received SYN and is sending a SYN-ACK (state->TCPS_SYN_RECEIVED)
2394 * - both classic and Accurate ECN have special encoding
2395 * 2. Client is sending SYN packet (state->SYN_SENT)
2396 * - both classic and Accurate ECN have special encoding
2397 * 3. Client is sending final ACK of 3WHS (state->ESTABLISHED)
2398 * - Only Accurate ECN has special encoding
2399 */
2400 if ((flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK) &&
2401 (tp->ecn_flags & TE_ENABLE_ECN)) {
2402 flags = tcp_accecn_synack_respond(tp, flags);
2403 } else if ((flags & (TH_SYN | TH_ACK)) == TH_SYN &&
2404 (tp->ecn_flags & TE_ENABLE_ECN)) {
2405 if (tcp_send_ecn_flags_on_syn(tp)) {
2406 if (tp->l4s_enabled) {
2407 /*
2408 * We are negotiating AccECN in SYN.
2409 * We only set TE_SENDIPECT after the handshake
2410 * is complete.
2411 */
2412 flags |= TH_ACE;
2413 tp->ecn_flags |= (TE_ACE_SETUPSENT);
2414 } else {
2415 /*
2416 * Setting TH_ECE and TH_CWR makes this an
2417 * ECN-setup SYN
2418 */
2419 flags |= (TH_ECE | TH_CWR);
2420 /*
2421 * Record that we sent the ECN-setup and default to
2422 * setting IP ECT.
2423 */
2424 tp->ecn_flags |= (TE_SETUPSENT | TE_SENDIPECT);
2425 }
2426 tcpstat.tcps_ecn_client_setup++;
2427 tp->ecn_flags |= TE_CLIENT_SETUP;
2428 } else {
2429 /*
2430 * We sent an ECN-setup SYN but it was dropped.
2431 * Fall back to non-ECN and clear flag indicating
2432 * we should send data with IP ECT set.
2433 */
2434 if (tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) {
2435 tcpstat.tcps_ecn_lost_syn++;
2436 tp->ecn_flags |= TE_LOST_SYN;
2437 }
2438 tp->ecn_flags &= ~TE_SENDIPECT;
2439 }
2440 } else if (tp->accurate_ecn_on && (tp->ecn_flags & TE_ACE_FINAL_ACK_3WHS) &&
2441 len == 0 && (flags & (TH_FLAGS_ALL)) == TH_ACK) {
2442 /*
2443 * Client has processed SYN-ACK and moved to ESTABLISHED.
2444 * This is the final ACK of 3WHS. If ACC_ECN has been negotiated,
2445 * then send the handshake encoding as per Table 3 of Accurate ECN draft.
2446 * We are clearing the ACE flags just in case if they were set before.
2447 * TODO: if client has to carry data in the 3WHS ACK, then we need to send a pure ACK first
2448 */
2449 flags &= ~(TH_AE | TH_CWR | TH_ECE);
2450 if (tp->ecn_flags & TE_ACE_SETUP_NON_ECT) {
2451 flags |= TH_CWR;
2452 tp->ecn_flags &= ~TE_ACE_SETUP_NON_ECT;
2453 } else if (tp->ecn_flags & TE_ACE_SETUP_ECT1) {
2454 flags |= (TH_CWR | TH_ECE);
2455 tp->ecn_flags &= ~TE_ACE_SETUP_ECT1;
2456 } else if (tp->ecn_flags & TE_ACE_SETUP_ECT0) {
2457 flags |= TH_AE;
2458 tp->ecn_flags &= ~TE_ACE_SETUP_ECT0;
2459 } else if (tp->ecn_flags & TE_ACE_SETUP_CE) {
2460 flags |= (TH_AE | TH_CWR);
2461 tp->ecn_flags &= ~TE_ACE_SETUP_CE;
2462 }
2463 tp->ecn_flags &= ~(TE_ACE_FINAL_ACK_3WHS);
2464 }
2465
2466 /*
2467 * Check if we should set the TCP CWR flag.
2468 * CWR flag is sent when we reduced the congestion window because
2469 * we received a TCP ECE or we performed a fast retransmit. We
2470 * never set the CWR flag on retransmitted packets. We only set
2471 * the CWR flag on data packets. Pure acks don't have this set.
2472 */
2473 if ((tp->ecn_flags & TE_SENDCWR) != 0 && len != 0 &&
2474 !SEQ_LT(tp->snd_nxt, tp->snd_max) && !rack_sack_rxmit) {
2475 flags |= TH_CWR;
2476 tp->ecn_flags &= ~TE_SENDCWR;
2477 }
2478
2479 /*
2480 * Check if we should set the TCP ECE flag.
2481 */
2482 if ((tp->ecn_flags & TE_SENDECE) != 0 && len == 0) {
2483 flags |= TH_ECE;
2484 tcpstat.tcps_ecn_sent_ece++;
2485 }
2486
2487 hdrlen += optlen;
2488
2489 /* Reset DSACK sequence numbers */
2490 tp->t_dsack_lseq = 0;
2491 tp->t_dsack_rseq = 0;
2492
2493 if (isipv6) {
2494 ipoptlen = ip6_optlen(inp);
2495 } else {
2496 if (tp_inp_options) {
2497 ipoptlen = tp_inp_options->m_len -
2498 offsetof(struct ipoption, ipopt_list);
2499 } else {
2500 ipoptlen = 0;
2501 }
2502 }
2503 #if IPSEC
2504 ipoptlen += ipsec_optlen;
2505 #endif
2506
2507 /*
2508 * Adjust data length if insertion of options will
2509 * bump the packet length beyond the t_maxopd length.
2510 * Clear the FIN bit because we cut off the tail of
2511 * the segment.
2512 *
2513 * When doing TSO limit a burst to TCP_MAXWIN minus the
2514 * IP, TCP and Options length to keep ip->ip_len from
2515 * overflowing. Prevent the last segment from being
2516 * fractional thus making them all equal sized and set
2517 * the flag to continue sending. TSO is disabled when
2518 * IP options or IPSEC are present.
2519 */
2520 if (len + optlen + ipoptlen > tp->t_maxopd) {
2521 /*
2522 * If there is still more to send,
2523 * don't close the connection.
2524 */
2525 flags &= ~TH_FIN;
2526 if (tso) {
2527 int32_t tso_maxlen;
2528
2529 tso_maxlen = tp->tso_max_segment_size ?
2530 tp->tso_max_segment_size : TCP_MAXWIN;
2531
2532 /* hdrlen includes optlen */
2533 if (len > tso_maxlen - hdrlen) {
2534 len = tso_maxlen - hdrlen;
2535 sendalot = 1;
2536 } else if (tp->t_flags & TF_NEEDFIN) {
2537 sendalot = 1;
2538 }
2539
2540 if (len % (tp->t_maxopd - optlen) != 0) {
2541 len = len - (len % (tp->t_maxopd - optlen));
2542 sendalot = 1;
2543 }
2544 } else {
2545 len = tp->t_maxopd - optlen - ipoptlen;
2546 sendalot = 1;
2547 }
2548 }
2549
2550 if (!(flags & TH_SYN) &&
2551 ((tp->accurate_ecn_on && (tp->ecn_flags & TE_SENDIPECT) != 0) ||
2552 inp->inp_max_pacing_rate != UINT64_MAX)) {
2553 uint32_t pacing_delay;
2554
2555 pacing_delay = tcp_pacer_get_packet_tx_time(tp, len, &pacing_tx_time);
2556
2557 if (TSTMP_GT(tcp_now_local + pacing_delay, tp->t_latest_tx)) {
2558 /*
2559 * We need to make sure that time never moves backwards. This is
2560 * needed because `tcp_now` is not the same as `microuptime`
2561 * and thus two threads trying to send (one from the app, one
2562 * from dlil_input) may end up with different views on the time
2563 * and thus we may end up going backwards...
2564 * So, make sure t_latest_tx is strictly increasing.
2565 */
2566 tp->t_latest_tx = tcp_now_local + pacing_delay;
2567 }
2568 } else {
2569 if (TSTMP_GT(tcp_now_local, tp->t_latest_tx)) {
2570 tp->t_latest_tx = tcp_now_local;
2571 }
2572 }
2573
2574 if (tsvalptr != NULL) {
2575 uint32_t tsval;
2576
2577 /*
2578 * pacing_delay is folded into t_latest_tx, so that our
2579 * RTT-estimate is not artificially inflated.
2580 */
2581 tsval = tp->t_ts_offset + tp->t_latest_tx;
2582 *tsvalptr = htonl(tsval);
2583 }
2584
2585 if (max_linkhdr + hdrlen > MCLBYTES) {
2586 panic("tcphdr too big");
2587 }
2588
2589 /* Check if there is enough data in the send socket
2590 * buffer to start measuring bandwidth
2591 */
2592 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
2593 (tp->t_bwmeas != NULL) &&
2594 (tp->t_flagsext & TF_BWMEAS_INPROGRESS) == 0) {
2595 tp->t_bwmeas->bw_size = min(min(
2596 (so->so_snd.sb_cc - (tp->snd_max - tp->snd_una)),
2597 tp->snd_cwnd), tp->snd_wnd);
2598 if (tp->t_bwmeas->bw_minsize > 0 &&
2599 tp->t_bwmeas->bw_size < tp->t_bwmeas->bw_minsize) {
2600 tp->t_bwmeas->bw_size = 0;
2601 }
2602 if (tp->t_bwmeas->bw_maxsize > 0) {
2603 tp->t_bwmeas->bw_size = min(tp->t_bwmeas->bw_size,
2604 tp->t_bwmeas->bw_maxsize);
2605 }
2606 if (tp->t_bwmeas->bw_size > 0) {
2607 tp->t_flagsext |= TF_BWMEAS_INPROGRESS;
2608 tp->t_bwmeas->bw_start = tp->snd_max;
2609 tp->t_bwmeas->bw_ts = tcp_now_local;
2610 }
2611 }
2612
2613 VERIFY(inp->inp_flowhash != 0);
2614 /*
2615 * Grab a header mbuf, attaching a copy of data to
2616 * be transmitted, and initialize the header from
2617 * the template for sends on this connection.
2618 */
2619 if (len) {
2620 /* Remember what the last head-of-line packet-size was */
2621 if (tp->t_pmtud_lastseg_size == 0 && tp->snd_nxt == tp->snd_una) {
2622 ASSERT(len + optlen + ipoptlen <= IP_MAXPACKET);
2623 tp->t_pmtud_lastseg_size = (uint16_t)(len + optlen + ipoptlen);
2624 }
2625 if ((tp->t_flagsext & TF_FORCE) && len == 1) {
2626 tcpstat.tcps_sndprobe++;
2627 } else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || rack_sack_rxmit) {
2628 tcpstat.tcps_sndrexmitpack++;
2629 tcpstat.tcps_sndrexmitbyte += len;
2630 if (nstat_collect) {
2631 nstat_route_tx(inp->inp_route.ro_rt, 1,
2632 len, NSTAT_TX_FLAG_RETRANSMIT);
2633 INP_ADD_TXSTAT(inp, ifnet_count_type, 1, len);
2634 tp->t_stat.txretransmitbytes += len;
2635 tp->t_stat.rxmitpkts++;
2636 }
2637 if (tp->ecn_flags & TE_SENDIPECT) {
2638 tp->t_ecn_capable_packets_lost++;
2639 }
2640 } else {
2641 tcpstat.tcps_sndpack++;
2642 tcpstat.tcps_sndbyte += len;
2643
2644 if (nstat_collect) {
2645 INP_ADD_TXSTAT(inp, ifnet_count_type, 1, len);
2646 }
2647 if (tp->ecn_flags & TE_SENDIPECT) {
2648 tp->t_ecn_capable_packets_sent++;
2649 }
2650 inp_decr_sndbytes_unsent(so, len);
2651 }
2652 #if MPTCP
2653 if (tp->t_mpflags & TMPF_MPTCP_TRUE) {
2654 tcpstat.tcps_mp_sndpacks++;
2655 tcpstat.tcps_mp_sndbytes += len;
2656 }
2657 #endif /* MPTCP */
2658 /*
2659 * try to use the new interface that allocates all
2660 * the necessary mbuf hdrs under 1 mbuf lock and
2661 * avoids rescanning the socket mbuf list if
2662 * certain conditions are met. This routine can't
2663 * be used in the following cases...
2664 * 1) the protocol headers exceed the capacity of
2665 * of a single mbuf header's data area (no cluster attached)
2666 * 2) the length of the data being transmitted plus
2667 * the protocol headers fits into a single mbuf header's
2668 * data area (no cluster attached)
2669 */
2670 m = NULL;
2671
2672 /* minimum length we are going to allocate */
2673 allocated_len = MHLEN;
2674 if (MHLEN < hdrlen + max_linkhdr) {
2675 MGETHDR(m, M_DONTWAIT, MT_HEADER);
2676 if (m == NULL) {
2677 error = ENOBUFS;
2678 TCP_LOG(tp, "MGETHDR error ENOBUFS");
2679 goto out;
2680 }
2681 MCLGET(m, M_DONTWAIT);
2682 if ((m->m_flags & M_EXT) == 0) {
2683 m_freem(m);
2684 error = ENOBUFS;
2685 TCP_LOG(tp, "MCLGET error ENOBUFS");
2686 goto out;
2687 }
2688 m->m_data += max_linkhdr;
2689 m->m_len = hdrlen;
2690 allocated_len = MCLBYTES;
2691 }
2692 if (len <= allocated_len - hdrlen - max_linkhdr) {
2693 if (m == NULL) {
2694 VERIFY(allocated_len <= MHLEN);
2695 MGETHDR(m, M_DONTWAIT, MT_HEADER);
2696 if (m == NULL) {
2697 error = ENOBUFS;
2698 TCP_LOG(tp, "MGETHDR error ENOBUFS");
2699 goto out;
2700 }
2701 m->m_data += max_linkhdr;
2702 m->m_len = hdrlen;
2703 }
2704 /* makes sure we still have data left to be sent at this point */
2705 if (so->so_snd.sb_mb == NULL || off < 0) {
2706 if (m != NULL) {
2707 m_freem(m);
2708 }
2709 error = 0; /* should we return an error? */
2710 goto out;
2711 }
2712 m_copydata(so->so_snd.sb_mb, off, (int) len,
2713 mtod(m, caddr_t) + hdrlen);
2714 m->m_len += len;
2715 } else {
2716 uint32_t copymode;
2717 /*
2718 * Retain packet header metadata at the socket
2719 * buffer if this is is an MPTCP subflow,
2720 * otherwise move it.
2721 */
2722 copymode = M_COPYM_MOVE_HDR;
2723 #if MPTCP
2724 if (so->so_flags & SOF_MP_SUBFLOW) {
2725 copymode = M_COPYM_NOOP_HDR;
2726 }
2727 #endif /* MPTCP */
2728 if (m != NULL) {
2729 if (so->so_snd.sb_flags & SB_SENDHEAD) {
2730 VERIFY(so->so_snd.sb_flags & SB_SENDHEAD);
2731 VERIFY(so->so_snd.sb_sendoff <= so->so_snd.sb_cc);
2732
2733 m->m_next = m_copym_mode(so->so_snd.sb_mb,
2734 off, (int)len, M_DONTWAIT,
2735 &so->so_snd.sb_sendhead,
2736 &so->so_snd.sb_sendoff, copymode);
2737
2738 VERIFY(so->so_snd.sb_sendoff <= so->so_snd.sb_cc);
2739 } else {
2740 m->m_next = m_copym_mode(so->so_snd.sb_mb,
2741 off, (int)len, M_DONTWAIT,
2742 NULL, NULL, copymode);
2743 }
2744 if (m->m_next == NULL) {
2745 (void) m_free(m);
2746 error = ENOBUFS;
2747 TCP_LOG(tp, "m_copym_mode error ENOBUFS");
2748 goto out;
2749 }
2750 } else {
2751 /*
2752 * make sure we still have data left
2753 * to be sent at this point
2754 */
2755 if (so->so_snd.sb_mb == NULL) {
2756 error = 0; /* should we return an error? */
2757 goto out;
2758 }
2759
2760 /*
2761 * m_copym_with_hdrs will always return the
2762 * last mbuf pointer and the offset into it that
2763 * it acted on to fullfill the current request,
2764 * whether a valid 'hint' was passed in or not.
2765 */
2766 if (so->so_snd.sb_flags & SB_SENDHEAD) {
2767 VERIFY(so->so_snd.sb_flags & SB_SENDHEAD);
2768 VERIFY(so->so_snd.sb_sendoff <= so->so_snd.sb_cc);
2769
2770 m = m_copym_with_hdrs(so->so_snd.sb_mb,
2771 off, len, M_DONTWAIT, &so->so_snd.sb_sendhead,
2772 &so->so_snd.sb_sendoff, copymode);
2773
2774 VERIFY(so->so_snd.sb_sendoff <= so->so_snd.sb_cc);
2775 } else {
2776 m = m_copym_with_hdrs(so->so_snd.sb_mb,
2777 off, len, M_DONTWAIT, NULL,
2778 NULL, copymode);
2779 }
2780 if (m == NULL) {
2781 error = ENOBUFS;
2782 TCP_LOG(tp, "m_copym_with_hdrs error ENOBUFS");
2783 goto out;
2784 }
2785 m->m_data += max_linkhdr;
2786 m->m_len = hdrlen;
2787 }
2788 }
2789 /*
2790 * If we're sending everything we've got, set PUSH.
2791 * (This will keep happy those implementations which only
2792 * give data to the user when a buffer fills or
2793 * a PUSH comes in.)
2794 *
2795 * On SYN-segments we should not add the PUSH-flag.
2796 */
2797 if (off + len == so->so_snd.sb_cc && !(flags & TH_SYN)) {
2798 flags |= TH_PUSH;
2799 }
2800 } else {
2801 if (tp->t_flags & TF_ACKNOW) {
2802 tcpstat.tcps_sndacks++;
2803 } else if (flags & (TH_SYN | TH_FIN | TH_RST)) {
2804 tcpstat.tcps_sndctrl++;
2805 } else if (SEQ_GT(tp->snd_up, tp->snd_una)) {
2806 tcpstat.tcps_sndurg++;
2807 } else {
2808 tcpstat.tcps_sndwinup++;
2809 }
2810
2811 MGETHDR(m, M_DONTWAIT, MT_HEADER); /* MAC-OK */
2812 if (m == NULL) {
2813 error = ENOBUFS;
2814 TCP_LOG(tp, "MGETHDR error ENOBUFS");
2815 goto out;
2816 }
2817 if (MHLEN < (hdrlen + max_linkhdr)) {
2818 MCLGET(m, M_DONTWAIT);
2819 if ((m->m_flags & M_EXT) == 0) {
2820 m_freem(m);
2821 error = ENOBUFS;
2822 TCP_LOG(tp, "MCLGET error ENOBUFS");
2823 goto out;
2824 }
2825 }
2826 m->m_data += max_linkhdr;
2827 m->m_len = hdrlen;
2828 }
2829 m->m_pkthdr.rcvif = 0;
2830 m_add_crumb(m, PKT_CRUMB_TCP_OUTPUT);
2831
2832 /* Any flag other than pure-ACK: Do not compress! */
2833 if (flags & ~(TH_ACK)) {
2834 do_not_compress = TRUE;
2835 }
2836
2837 if (tp->rcv_scale == 0) {
2838 do_not_compress = TRUE;
2839 }
2840
2841 if (do_not_compress) {
2842 m->m_pkthdr.comp_gencnt = 0;
2843 } else {
2844 if (TSTMP_LT(tp->t_comp_ack_lastinc + tcp_ack_compression_rate, tcp_now_local)) {
2845 tp->t_comp_ack_gencnt++;
2846 /*
2847 * 0 means no compression, and ACK gencnt is encoded on 31 bits
2848 */
2849 if (tp->t_comp_ack_gencnt <= TCP_ACK_COMPRESSION_DUMMY ||
2850 tp->t_comp_ack_gencnt > INT_MAX) {
2851 tp->t_comp_ack_gencnt = TCP_ACK_COMPRESSION_DUMMY + 1;
2852 }
2853 tp->t_comp_ack_lastinc = tcp_now_local;
2854 }
2855 m->m_pkthdr.comp_gencnt = tp->t_comp_ack_gencnt;
2856 }
2857
2858 if (isipv6) {
2859 ip6 = mtod(m, struct ip6_hdr *);
2860 th = (struct tcphdr *)(void *)(ip6 + 1);
2861 tcp_fillheaders(m, tp, ip6, th, NULL, NULL);
2862
2863 if (tp->accurate_ecn_on) {
2864 /* We send ECT1 for ALL packets (data, control, fast retransmits, RTO) */
2865 if ((tp->ecn_flags & TE_SENDIPECT) != 0 && !(flags & TH_SYN)) {
2866 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT1 << 20);
2867 }
2868 } else {
2869 if ((tp->ecn_flags & TE_SENDIPECT) != 0 && len &&
2870 !SEQ_LT(tp->snd_nxt, tp->snd_max) && !rack_sack_rxmit) {
2871 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
2872 }
2873 }
2874 svc_flags |= PKT_SCF_IPV6;
2875 #if PF_ECN
2876 m_pftag(m)->pftag_hdr = (void *)ip6;
2877 m_pftag(m)->pftag_flags |= PF_TAG_HDR_INET6;
2878 #endif /* PF_ECN */
2879 } else {
2880 ip = mtod(m, struct ip *);
2881 th = (struct tcphdr *)(void *)(ip + 1);
2882 /* this picks up the pseudo header (w/o the length) */
2883 tcp_fillheaders(m, tp, ip, th, NULL, NULL);
2884
2885 if (tp->accurate_ecn_on) {
2886 /* We send ECT1 for ALL packets (data, control, fast retransmits, RTO) */
2887 if ((tp->ecn_flags & TE_SENDIPECT) != 0 && !(flags & TH_SYN)) {
2888 ip->ip_tos |= IPTOS_ECN_ECT1;
2889 }
2890 } else {
2891 if ((tp->ecn_flags & TE_SENDIPECT) != 0 && len &&
2892 !SEQ_LT(tp->snd_nxt, tp->snd_max) &&
2893 !rack_sack_rxmit && !(flags & TH_SYN)) {
2894 ip->ip_tos |= IPTOS_ECN_ECT0;
2895 }
2896 }
2897 #if PF_ECN
2898 m_pftag(m)->pftag_hdr = (void *)ip;
2899 m_pftag(m)->pftag_flags |= PF_TAG_HDR_INET;
2900 #endif /* PF_ECN */
2901 }
2902
2903 if (pacing_tx_time) {
2904 mbuf_set_tx_time(m, pacing_tx_time);
2905 }
2906
2907 /*
2908 * Fill in fields, remembering maximum advertised
2909 * window for use in delaying messages about window sizes.
2910 * If resending a FIN, be sure not to use a new sequence number.
2911 */
2912 if ((flags & TH_FIN) && (tp->t_flags & TF_SENTFIN) &&
2913 tp->snd_nxt == tp->snd_max) {
2914 tp->snd_nxt--;
2915 }
2916 /*
2917 * If we are doing retransmissions, then snd_nxt will
2918 * not reflect the first unsent octet. For ACK only
2919 * packets, we do not want the sequence number of the
2920 * retransmitted packet, we want the sequence number
2921 * of the next unsent octet. So, if there is no data
2922 * (and no SYN or FIN), use snd_max instead of snd_nxt
2923 * when filling in ti_seq. But if we are in persist
2924 * state, snd_max might reflect one byte beyond the
2925 * right edge of the window, so use snd_nxt in that
2926 * case, since we know we aren't doing a retransmission.
2927 * (retransmit and persist are mutually exclusive...)
2928 *
2929 * Note the state of this retransmit segment to detect spurious
2930 * retransmissions.
2931 */
2932 if (rack_sack_rxmit == 0) {
2933 if (len || (flags & (TH_SYN | TH_FIN)) ||
2934 tp->t_timer[TCPT_PERSIST]) {
2935 th->th_seq = htonl(tp->snd_nxt);
2936 if (len > 0) {
2937 m->m_pkthdr.tx_start_seq = tp->snd_nxt;
2938 m->m_pkthdr.pkt_flags |= PKTF_START_SEQ;
2939 }
2940 if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
2941 if (SACK_ENABLED(tp) && len > 1 &&
2942 !(tp->t_flagsext & TF_SENT_TLPROBE)) {
2943 tcp_rxtseg_insert(tp, tp->snd_nxt,
2944 (tp->snd_nxt + len - 1));
2945 }
2946 if (len > 0) {
2947 m->m_pkthdr.pkt_flags |=
2948 PKTF_TCP_REXMT;
2949 }
2950 }
2951 } else {
2952 th->th_seq = htonl(tp->snd_max);
2953 }
2954 } else {
2955 /* Use RACK if enabled otherwise use SACK */
2956 if (TCP_RACK_ENABLED(tp)) {
2957 th->th_seq = htonl(seg->start_seq);
2958 tcp_rxtseg_insert(tp, seg->start_seq, (seg->start_seq + len - 1));
2959 } else {
2960 th->th_seq = htonl(p->rxmit);
2961 tcp_rxtseg_insert(tp, p->rxmit, (p->rxmit + len - 1));
2962 p->rxmit += len;
2963 tp->sackhint.sack_bytes_rexmit += len;
2964 }
2965 if (len > 0) {
2966 m->m_pkthdr.tx_start_seq = ntohl(th->th_seq);
2967 m->m_pkthdr.pkt_flags |=
2968 (PKTF_TCP_REXMT | PKTF_START_SEQ);
2969 }
2970 }
2971 th->th_ack = htonl(tp->rcv_nxt);
2972 tp->last_ack_sent = tp->rcv_nxt;
2973 if (optlen) {
2974 bcopy(opt, th + 1, optlen);
2975 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
2976 }
2977 /* Separate AE from flags */
2978 tcp_set_flags(th, flags);
2979 th->th_win = htons((u_short) (recwin >> tp->rcv_scale));
2980 tp->t_last_recwin = recwin;
2981 if (!(so->so_flags & SOF_MP_SUBFLOW)) {
2982 if (recwin > 0 && SEQ_LT(tp->rcv_adv, tp->rcv_nxt + recwin)) {
2983 tp->rcv_adv = tp->rcv_nxt + recwin;
2984 }
2985 } else {
2986 struct mptcb *mp_tp = tptomptp(tp);
2987 if (recwin > 0) {
2988 tp->rcv_adv = tp->rcv_nxt + recwin;
2989 }
2990
2991 if (recwin > 0 && MPTCP_SEQ_LT(mp_tp->mpt_rcvadv, mp_tp->mpt_rcvnxt + recwin)) {
2992 mp_tp->mpt_rcvadv = mp_tp->mpt_rcvnxt + recwin;
2993 }
2994 }
2995
2996 /*
2997 * Adjust the RXWIN0SENT flag - indicate that we have advertised
2998 * a 0 window. This may cause the remote transmitter to stall. This
2999 * flag tells soreceive() to disable delayed acknowledgements when
3000 * draining the buffer. This can occur if the receiver is attempting
3001 * to read more data then can be buffered prior to transmitting on
3002 * the connection.
3003 */
3004 if (th->th_win == 0) {
3005 tp->t_flags |= TF_RXWIN0SENT;
3006 } else {
3007 tp->t_flags &= ~TF_RXWIN0SENT;
3008 }
3009
3010 if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
3011 th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
3012 th->th_flags |= TH_URG;
3013 } else {
3014 /*
3015 * If no urgent pointer to send, then we pull
3016 * the urgent pointer to the left edge of the send window
3017 * so that it doesn't drift into the send window on sequence
3018 * number wraparound.
3019 */
3020 tp->snd_up = tp->snd_una; /* drag it along */
3021 }
3022
3023 /*
3024 * Put TCP length in extended header, and then
3025 * checksum extended header and data.
3026 */
3027 m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
3028
3029 /*
3030 * If this is potentially the last packet on the stream, then mark
3031 * it in order to enable some optimizations in the underlying
3032 * layers
3033 */
3034 if (tp->t_state != TCPS_ESTABLISHED &&
3035 (tp->t_state == TCPS_CLOSING || tp->t_state == TCPS_TIME_WAIT
3036 || tp->t_state == TCPS_LAST_ACK || (th->th_flags & TH_RST))) {
3037 m->m_pkthdr.pkt_flags |= PKTF_LAST_PKT;
3038 }
3039
3040 if (isipv6) {
3041 /*
3042 * ip6_plen is not need to be filled now, and will be filled
3043 * in ip6_output.
3044 */
3045 m->m_pkthdr.csum_flags = CSUM_TCPIPV6;
3046 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
3047 if (len + optlen) {
3048 th->th_sum = in_addword(th->th_sum,
3049 htons((u_short)(optlen + len)));
3050 }
3051 } else {
3052 m->m_pkthdr.csum_flags = CSUM_TCP;
3053 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
3054 if (len + optlen) {
3055 th->th_sum = in_addword(th->th_sum,
3056 htons((u_short)(optlen + len)));
3057 }
3058 }
3059
3060 /*
3061 * Enable TSO and specify the size of the segments.
3062 * The TCP pseudo header checksum is always provided.
3063 */
3064 if (tso) {
3065 if (isipv6) {
3066 m->m_pkthdr.csum_flags |= CSUM_TSO_IPV6;
3067 } else {
3068 m->m_pkthdr.csum_flags |= CSUM_TSO_IPV4;
3069 }
3070
3071 m->m_pkthdr.tso_segsz = (uint16_t)(tp->t_maxopd - optlen);
3072 m->m_pkthdr.tx_hdr_len = (uint16_t)hdrlen;
3073 } else {
3074 m->m_pkthdr.tso_segsz = 0;
3075 }
3076
3077 /*
3078 * In transmit state, time the transmission and arrange for
3079 * the retransmit. In persist state, just set snd_max.
3080 */
3081 if (!(tp->t_flagsext & TF_FORCE)
3082 || tp->t_timer[TCPT_PERSIST] == 0) {
3083 tcp_seq startseq = tp->snd_nxt;
3084
3085 /*
3086 * Advance snd_nxt over sequence space of this segment.
3087 */
3088 if (flags & (TH_SYN | TH_FIN)) {
3089 if (flags & TH_SYN) {
3090 tp->snd_nxt++;
3091 }
3092 if ((flags & TH_FIN) &&
3093 !(tp->t_flags & TF_SENTFIN)) {
3094 tp->snd_nxt++;
3095 tp->t_flags |= TF_SENTFIN;
3096 }
3097 }
3098 if (rack_sack_rxmit) {
3099 goto timer;
3100 }
3101 if (sack_rescue_rxt == true) {
3102 tp->snd_nxt = old_snd_nxt;
3103 sack_rescue_rxt = false;
3104 tcpstat.tcps_pto_in_recovery++;
3105 } else {
3106 tp->snd_nxt += len;
3107 }
3108 if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
3109 tp->snd_max = tp->snd_nxt;
3110 tp->t_sndtime = tp->t_latest_tx;
3111 /*
3112 * Time this transmission if not a retransmission and
3113 * not currently timing anything.
3114 */
3115 if (tp->t_rtttime == 0) {
3116 tp->t_rtttime = tp->t_latest_tx;
3117 tp->t_rtseq = startseq;
3118 tcpstat.tcps_segstimed++;
3119
3120 /* update variables related to pipe ack */
3121 tp->t_pipeack_lastuna = tp->snd_una;
3122 }
3123 }
3124
3125 /*
3126 * Set retransmit timer if not currently set,
3127 * and not doing an ack or a keep-alive probe.
3128 */
3129 timer:
3130 if (tp->t_timer[TCPT_REXMT] == 0 &&
3131 ((rack_sack_rxmit && tp->snd_nxt != tp->snd_max) ||
3132 tp->snd_nxt != tp->snd_una || (flags & TH_FIN))) {
3133 if (tp->t_timer[TCPT_PERSIST]) {
3134 tp->t_timer[TCPT_PERSIST] = 0;
3135 tp->t_persist_stop = 0;
3136 TCP_RESET_REXMT_STATE(tp);
3137 }
3138 tcp_set_rto(tp);
3139 }
3140
3141 if (tcp_enable_tlp && len != 0) {
3142 tcp_set_pto(tp);
3143 }
3144 } else {
3145 /*
3146 * Persist case, update snd_max but since we are in
3147 * persist mode (no window) we do not update snd_nxt.
3148 */
3149 int xlen = len;
3150 if (flags & TH_SYN) {
3151 ++xlen;
3152 }
3153 if ((flags & TH_FIN) &&
3154 !(tp->t_flags & TF_SENTFIN)) {
3155 ++xlen;
3156 tp->t_flags |= TF_SENTFIN;
3157 }
3158 if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max)) {
3159 tp->snd_max = tp->snd_nxt + len;
3160 tp->t_sndtime = tp->t_latest_tx;
3161 }
3162 }
3163
3164 /*
3165 * Fill in IP length and desired time to live and
3166 * send to IP level. There should be a better way
3167 * to handle ttl and tos; we could keep them in
3168 * the template, but need a way to checksum without them.
3169 */
3170 /*
3171 * m->m_pkthdr.len should have been set before cksum calcuration,
3172 * because in6_cksum() need it.
3173 */
3174 if (isipv6) {
3175 /*
3176 * we separately set hoplimit for every segment, since the
3177 * user might want to change the value via setsockopt.
3178 * Also, desired default hop limit might be changed via
3179 * Neighbor Discovery.
3180 */
3181 ip6->ip6_hlim = in6_selecthlim(inp, inp->in6p_route.ro_rt ?
3182 inp->in6p_route.ro_rt->rt_ifp : NULL);
3183
3184 /* Don't set ECT bit if requested by an app */
3185
3186 /* Set ECN bits for testing purposes */
3187 if (tp->ecn_flags & TE_FORCE_ECT1) {
3188 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT1 << 20);
3189 } else if (tp->ecn_flags & TE_FORCE_ECT0) {
3190 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
3191 }
3192
3193 KERNEL_DEBUG(DBG_LAYER_BEG,
3194 ((inp->inp_fport << 16) | inp->inp_lport),
3195 (((inp->in6p_laddr.s6_addr16[0] & 0xffff) << 16) |
3196 (inp->in6p_faddr.s6_addr16[0] & 0xffff)),
3197 sendalot, 0, 0);
3198 } else {
3199 ASSERT(m->m_pkthdr.len <= IP_MAXPACKET);
3200 ip->ip_len = (u_short)m->m_pkthdr.len;
3201 ip->ip_ttl = inp->inp_ip_ttl; /* XXX */
3202
3203 /* Don't set ECN bit if requested by an app */
3204 ip->ip_tos |= (inp->inp_ip_tos & ~IPTOS_ECN_MASK);
3205
3206 /* Set ECN bits for testing purposes */
3207 if (tp->ecn_flags & TE_FORCE_ECT1) {
3208 ip->ip_tos |= IPTOS_ECN_ECT1;
3209 } else if (tp->ecn_flags & TE_FORCE_ECT0) {
3210 ip->ip_tos |= IPTOS_ECN_ECT0;
3211 }
3212
3213 KERNEL_DEBUG(DBG_LAYER_BEG,
3214 ((inp->inp_fport << 16) | inp->inp_lport),
3215 (((inp->inp_laddr.s_addr & 0xffff) << 16) |
3216 (inp->inp_faddr.s_addr & 0xffff)), 0, 0, 0);
3217 }
3218
3219 /*
3220 * See if we should do MTU discovery.
3221 * Look at the flag updated on the following criterias:
3222 * 1) Path MTU discovery is authorized by the sysctl
3223 * 2) The route isn't set yet (unlikely but could happen)
3224 * 3) The route is up
3225 * 4) the MTU is not locked (if it is, then discovery has been
3226 * disabled for that route)
3227 */
3228 if (!isipv6) {
3229 if (path_mtu_discovery && (tp->t_flags & TF_PMTUD)) {
3230 ip->ip_off |= IP_DF;
3231 }
3232 }
3233
3234 #if NECP
3235 {
3236 necp_kernel_policy_id policy_id;
3237 necp_kernel_policy_id skip_policy_id;
3238 u_int32_t route_rule_id;
3239 u_int32_t pass_flags;
3240 if (!necp_socket_is_allowed_to_send_recv(inp, NULL, 0, &policy_id, &route_rule_id, &skip_policy_id, &pass_flags)) {
3241 TCP_LOG_DROP_NECP(isipv6 ? (void *)ip6 : (void *)ip, th, tp, true);
3242 m_drop_if(m, outifp, DROPTAP_FLAG_DIR_OUT | DROPTAP_FLAG_L2_MISSING, DROP_REASON_TCP_NECP, NULL, 0);
3243 error = EHOSTUNREACH;
3244 goto out;
3245 }
3246 necp_mark_packet_from_socket(m, inp, policy_id, route_rule_id, skip_policy_id, pass_flags);
3247
3248 if (net_qos_policy_restricted != 0) {
3249 necp_socket_update_qos_marking(inp, inp->inp_route.ro_rt, route_rule_id);
3250 }
3251 }
3252 #endif /* NECP */
3253
3254 #if IPSEC
3255 if (inp->inp_sp != NULL) {
3256 ipsec_setsocket(m, so);
3257 }
3258 #endif /*IPSEC*/
3259
3260 /*
3261 * The socket is kept locked while sending out packets in ip_output, even if packet chaining is not active.
3262 */
3263 lost = 0;
3264
3265 /*
3266 * Embed the flow hash in pkt hdr and mark the packet as
3267 * capable of flow controlling
3268 */
3269 m->m_pkthdr.pkt_flowsrc = FLOWSRC_INPCB;
3270 m->m_pkthdr.pkt_flowid = inp->inp_flowhash;
3271 m->m_pkthdr.pkt_flags |= (PKTF_FLOW_ID | PKTF_FLOW_LOCALSRC | PKTF_FLOW_ADV);
3272 m->m_pkthdr.pkt_proto = IPPROTO_TCP;
3273 m->m_pkthdr.tx_tcp_pid = so->last_pid;
3274 if (so->so_flags & SOF_DELEGATED) {
3275 m->m_pkthdr.tx_tcp_e_pid = so->e_pid;
3276 } else {
3277 m->m_pkthdr.tx_tcp_e_pid = 0;
3278 }
3279
3280 m->m_nextpkt = NULL;
3281
3282 if (outifp != NULL &&
3283 !(outifp->if_flags & IFF_LOOPBACK)) {
3284 /* Hint to prioritize this packet if
3285 * 1. if the packet has no data
3286 * 2. the interface supports transmit-start model and did
3287 * not disable ACK prioritization.
3288 * 3. Only ACK flag is set.
3289 * 4. there is no outstanding data on this connection.
3290 * 5. Link heuristics are not enabled for the interface
3291 */
3292 if (len == 0 && (outifp->if_eflags & (IFEF_TXSTART | IFEF_NOACKPRI)) == IFEF_TXSTART) {
3293 if (link_heuristics_enabled && (tcp_link_heuristics_flags & TCP_LINK_HEUR_NOACKPRI) != 0) {
3294 IF_TCP_STATINC(outifp, linkheur_noackpri);
3295 } else {
3296 if (th->th_flags == TH_ACK &&
3297 tp->snd_una == tp->snd_max &&
3298 tp->t_timer[TCPT_REXMT] == 0) {
3299 svc_flags |= PKT_SCF_TCP_ACK;
3300 }
3301 if (tcp_allow_syn_prio == 1 && (th->th_flags & TH_SYN)) {
3302 svc_flags |= PKT_SCF_TCP_SYN;
3303 }
3304 }
3305 }
3306 set_packet_service_class(m, so, sotc, svc_flags);
3307 } else {
3308 /*
3309 * Optimization for loopback just set the mbuf
3310 * service class
3311 */
3312 (void) m_set_service_class(m, so_tc2msc(sotc));
3313 }
3314
3315 tp->t_pktlist_sentlen += len;
3316 tp->t_lastchain++;
3317
3318 if (isipv6) {
3319 DTRACE_TCP5(send, struct mbuf *, m, struct inpcb *, inp,
3320 struct ip6 *, ip6, struct tcpcb *, tp, struct tcphdr *,
3321 th);
3322 } else {
3323 DTRACE_TCP5(send, struct mbuf *, m, struct inpcb *, inp,
3324 struct ip *, ip, struct tcpcb *, tp, struct tcphdr *, th);
3325 }
3326
3327 if (tp->t_pktlist_head != NULL) {
3328 tp->t_pktlist_tail->m_nextpkt = m;
3329 tp->t_pktlist_tail = m;
3330 } else {
3331 packchain_newlist++;
3332 tp->t_pktlist_head = tp->t_pktlist_tail = m;
3333 }
3334
3335 /* Append segment to time-ordered list and RB tree used for RACK */
3336 if (TCP_RACK_ENABLED(tp) && len != 0) {
3337 uint8_t retransmit_flag = 0;
3338 if (tp->t_flagsext & TF_SENT_TLPROBE) {
3339 /* Only set the at least once retransmitted flag */
3340 retransmit_flag = (m->m_pkthdr.pkt_flags & PKTF_TCP_REXMT) ? TCP_SEGMENT_RETRANSMITTED_ATLEAST_ONCE : 0;
3341 } else {
3342 /* Set both RACK and EVER retransmitted flags */
3343 retransmit_flag = (m->m_pkthdr.pkt_flags & PKTF_TCP_REXMT) ? TCP_SEGMENT_RETRANSMITTED : 0;
3344 }
3345 tcp_seg_sent_insert(tp, seg, ntohl(th->th_seq),
3346 ntohl(th->th_seq) + len, tp->t_latest_tx, retransmit_flag);
3347 }
3348
3349 if ((th->th_flags & TH_SYN) != 0) {
3350 (void)os_add_overflow(tp->t_syn_sent, 1, &tp->t_syn_sent);
3351 if (tp->t_rxtshift > 0) {
3352 m->m_pkthdr.pkt_flags |= PKTF_TCP_REXMT;
3353 }
3354 }
3355 if ((th->th_flags & TH_FIN) != 0) {
3356 (void)os_add_overflow(tp->t_fin_sent, 1, &tp->t_fin_sent);
3357 if (tp->t_rxtshift > 0) {
3358 m->m_pkthdr.pkt_flags |= PKTF_TCP_REXMT;
3359 }
3360 }
3361 if ((th->th_flags & TH_RST) != 0) {
3362 (void)os_add_overflow(tp->t_rst_sent, 1, &tp->t_rst_sent);
3363 if (tp->t_rxtshift > 0) {
3364 m->m_pkthdr.pkt_flags |= PKTF_TCP_REXMT;
3365 }
3366 }
3367 TCP_LOG_TH_FLAGS(isipv6 ? (void *)ip6 : (void *)ip, th, tp, true,
3368 outifp != NULL ? outifp : inp->inp_boundifp);
3369
3370 if (__improbable((th->th_flags & TH_RST) != 0 && inp->inp_sndinprog_cnt == 0 &&
3371 sendalot == 0 && tp->t_pktlist_head == m)) {
3372 if (tcp_rst_rlc_compress(mtod(m, void *), m->m_len, th) == true) {
3373 error = 0;
3374 goto out;
3375 }
3376 }
3377
3378 if (link_heuristics_enabled && (tcp_link_heuristics_flags & TCP_LINK_HEUR_RXMT_COMP) != 0 &&
3379 (len != 0 || (th->th_flags & TH_FIN) != 0)) {
3380 /*
3381 * Set compression flag if gencnt of segment is the same as the last sent segment
3382 * otherwise record the gencnt of the segment that we are sending
3383 */
3384 uint32_t gencnt = ntohl(th->th_seq) & TCP_COMP_RXMT_GENCNT_MASK;
3385
3386 if ((m->m_pkthdr.pkt_flags & PKTF_TCP_REXMT) != 0 && gencnt == tp->t_comp_rxmt_gencnt) {
3387 IF_TCP_STATINC(outifp, linkheur_comprxmt);
3388 m->m_pkthdr.comp_gencnt = gencnt;
3389 } else {
3390 tp->t_comp_rxmt_gencnt = gencnt;
3391 }
3392 }
3393
3394 if (sendalot == 0 || (tp->t_state != TCPS_ESTABLISHED) ||
3395 (tp->t_flags & TF_ACKNOW) ||
3396 (tp->t_flagsext & TF_FORCE) ||
3397 tp->t_lastchain >= tcp_packet_chaining) {
3398 error = 0;
3399 while (inp->inp_sndinprog_cnt == 0 &&
3400 tp->t_pktlist_head != NULL) {
3401 packetlist = tp->t_pktlist_head;
3402 packchain_listadd = tp->t_lastchain;
3403 packchain_sent++;
3404 lost = tp->t_pktlist_sentlen;
3405 TCP_PKTLIST_CLEAR(tp);
3406
3407 error = tcp_ip_output(so, tp, packetlist,
3408 packchain_listadd, tp_inp_options,
3409 (so_options & SO_DONTROUTE),
3410 (rack_sack_rxmit || (sack_bytes_rxmt != 0)), isipv6);
3411 if (error) {
3412 /*
3413 * Take into account the rest of unsent
3414 * packets in the packet list for this tcp
3415 * into "lost", since we're about to free
3416 * the whole list below.
3417 */
3418 lost += tp->t_pktlist_sentlen;
3419 break;
3420 } else {
3421 lost = 0;
3422 }
3423 }
3424 /* tcp was closed while we were in ip; resume close */
3425 if (inp->inp_sndinprog_cnt == 0 &&
3426 (tp->t_flags & TF_CLOSING)) {
3427 tp->t_flags &= ~TF_CLOSING;
3428 (void) tcp_close(tp);
3429 return 0;
3430 }
3431 } else {
3432 error = 0;
3433 packchain_looped++;
3434 tcpstat.tcps_sndtotal++;
3435
3436 goto again;
3437 }
3438 if (error) {
3439 /*
3440 * Assume that the packets were lost, so back out the
3441 * sequence number advance, if any. Note that the "lost"
3442 * variable represents the amount of user data sent during
3443 * the recent call to ip_output_list() plus the amount of
3444 * user data in the packet list for this tcp at the moment.
3445 */
3446 if (!(tp->t_flagsext & TF_FORCE)
3447 || tp->t_timer[TCPT_PERSIST] == 0) {
3448 /*
3449 * No need to check for TH_FIN here because
3450 * the TF_SENTFIN flag handles that case.
3451 */
3452 if ((flags & TH_SYN) == 0) {
3453 /*
3454 * RACK will mark these segments lost on its own
3455 * when new ACK arrives, no need to adjust anything here.
3456 * In fact doing so would be wrong, as RACK segments are
3457 * ordered in time (not sequence number).
3458 */
3459 if (rack_sack_rxmit && !TCP_RACK_ENABLED(tp)) {
3460 if (SEQ_GT((p->rxmit - lost),
3461 tp->snd_una)) {
3462 p->rxmit -= lost;
3463
3464 if (SEQ_LT(p->rxmit, p->start)) {
3465 p->rxmit = p->start;
3466 }
3467 } else {
3468 lost = p->rxmit - tp->snd_una;
3469 p->rxmit = tp->snd_una;
3470
3471 if (SEQ_LT(p->rxmit, p->start)) {
3472 p->rxmit = p->start;
3473 }
3474 }
3475 tp->sackhint.sack_bytes_rexmit -= lost;
3476 if (tp->sackhint.sack_bytes_rexmit < 0) {
3477 tp->sackhint.sack_bytes_rexmit = 0;
3478 }
3479 } else {
3480 if (SEQ_GT((tp->snd_nxt - lost),
3481 tp->snd_una)) {
3482 tp->snd_nxt -= lost;
3483 } else {
3484 tp->snd_nxt = tp->snd_una;
3485 }
3486 }
3487 }
3488 }
3489 out:
3490 if (tp->t_pktlist_head != NULL) {
3491 m_drop_list(tp->t_pktlist_head, outifp, DROPTAP_FLAG_DIR_OUT | DROPTAP_FLAG_L2_MISSING, DROP_REASON_TCP_PKT_UNSENT, NULL, 0);
3492 }
3493 TCP_PKTLIST_CLEAR(tp);
3494
3495 if (error == ENOBUFS) {
3496 /*
3497 * Set retransmit timer if not currently set
3498 * when we failed to send a segment that can be
3499 * retransmitted (i.e. not pure ack or rst)
3500 */
3501 if (tp->t_timer[TCPT_REXMT] == 0 &&
3502 tp->t_timer[TCPT_PERSIST] == 0 &&
3503 (len != 0 || (flags & (TH_SYN | TH_FIN)) != 0 ||
3504 so->so_snd.sb_cc > 0)) {
3505 tcp_set_rto(tp);
3506 }
3507 tp->snd_cwnd = tp->t_maxseg;
3508 tp->t_bytes_acked = 0;
3509 tcp_check_timer_state(tp);
3510 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3511
3512 TCP_LOG_OUTPUT(tp, "error ENOBUFS silently handled");
3513
3514 tcp_ccdbg_trace(tp, NULL, TCP_CC_OUTPUT_ERROR);
3515 return 0;
3516 }
3517 if (error == EMSGSIZE) {
3518 /*
3519 * ip_output() will have already fixed the route
3520 * for us. tcp_mtudisc() will, as its last action,
3521 * initiate retransmission, so it is important to
3522 * not do so here.
3523 *
3524 * If TSO was active we either got an interface
3525 * without TSO capabilits or TSO was turned off.
3526 * Disable it for this connection as too and
3527 * immediatly retry with MSS sized segments generated
3528 * by this function.
3529 */
3530 if (tso) {
3531 tp->t_flags &= ~TF_TSO;
3532 }
3533
3534 tcp_mtudisc(inp, 0);
3535 tcp_check_timer_state(tp);
3536
3537 TCP_LOG_OUTPUT(tp, "error EMSGSIZE silently handled");
3538
3539 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3540 return 0;
3541 }
3542 /*
3543 * Unless this is due to interface restriction policy,
3544 * treat EHOSTUNREACH/ENETDOWN/EADDRNOTAVAIL as a soft error.
3545 */
3546 if ((error == EHOSTUNREACH || error == ENETDOWN || error == EADDRNOTAVAIL) &&
3547 TCPS_HAVERCVDSYN(tp->t_state) &&
3548 !inp_restricted_send(inp, outifp)) {
3549 tp->t_softerror = error;
3550 TCP_LOG_OUTPUT(tp, "soft error %d silently handled", error);
3551 error = 0;
3552 } else {
3553 TCP_LOG_OUTPUT(tp, "error %d", error);
3554 }
3555 tcp_check_timer_state(tp);
3556 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3557 return error;
3558 }
3559
3560 tcpstat.tcps_sndtotal++;
3561
3562 KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3563 if (sendalot) {
3564 goto again;
3565 }
3566
3567 tcp_check_timer_state(tp);
3568
3569 return 0;
3570 }
3571
3572 static int
tcp_set_rto_deadline(struct tcpcb * tp,struct mbuf * pkt,int isipv6,uint32_t tcp_now_local)3573 tcp_set_rto_deadline(struct tcpcb *tp, struct mbuf *pkt, int isipv6, uint32_t tcp_now_local)
3574 {
3575 struct tcphdr *th;
3576 int th_offset = isipv6 ? sizeof(struct ip6_hdr) : sizeof(struct ip);
3577
3578 /*
3579 * Determine whether the RTO should be set
3580 */
3581 if (tp->t_timer[TCPT_REXMT] == 0) {
3582 /*
3583 * RTO is not set for the TP, can not set
3584 * the deadline.
3585 */
3586 return ENOENT;
3587 }
3588
3589 /*
3590 * RTO deadline is not applicable to pure ACK packets,
3591 * as well as to the SYN/RST/FIN packets.
3592 */
3593 th = (struct tcphdr *)(void*)(mtod(pkt, caddr_t) + th_offset);
3594
3595 /*
3596 * Check whether the packet has any TCP payload, or is a pure ACK.
3597 */
3598 if (pkt->m_pkthdr.len <= th_offset + (th->th_off << 2)) {
3599 return ENOENT;
3600 }
3601
3602 /*
3603 * Check whether this is an SYN/RST/FIN packet
3604 */
3605 if ((th->th_flags & (TH_SYN | TH_RST | TH_FIN)) != 0) {
3606 return ENOENT;
3607 }
3608
3609 /*
3610 * Set the deadline.
3611 */
3612 pkt->m_pkthdr.pkt_deadline = tcp_calculate_rto_deadline(tp, tcp_now_local);
3613
3614 return 0;
3615 }
3616
3617 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)3618 tcp_ip_output(struct socket *so, struct tcpcb *tp, struct mbuf *pkt,
3619 int cnt, struct mbuf *opt, int flags, int sack_in_progress, boolean_t isipv6)
3620 {
3621 int error = 0;
3622 boolean_t chain;
3623 boolean_t unlocked = FALSE;
3624 boolean_t ifdenied = FALSE;
3625 struct inpcb *__single inp = tp->t_inpcb;
3626 struct ifnet *__single outif = NULL;
3627 bool check_qos_marking_again = (so->so_flags1 & SOF1_QOSMARKING_POLICY_OVERRIDE) ? FALSE : TRUE;
3628 bool fadv_congested = FALSE;
3629 uint32_t tcp_now_local = os_access_once(tcp_now);
3630
3631 union {
3632 struct route _ro;
3633 struct route_in6 _ro6;
3634 } route_u_ = {};
3635 #define ro route_u_._ro
3636 #define ro6 route_u_._ro6
3637
3638 union {
3639 struct ip_out_args _ipoa;
3640 struct ip6_out_args _ip6oa;
3641 } out_args_u_ = {};
3642 #define ipoa out_args_u_._ipoa
3643 #define ip6oa out_args_u_._ip6oa
3644
3645 if (isipv6) {
3646 ip6oa.ip6oa_boundif = IFSCOPE_NONE;
3647 ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR;
3648 ip6oa.ip6oa_sotc = SO_TC_UNSPEC;
3649 ip6oa.ip6oa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
3650 } else {
3651 ipoa.ipoa_boundif = IFSCOPE_NONE;
3652 ipoa.ipoa_flags = IPOAF_SELECT_SRCIF | IPOAF_BOUND_SRCADDR;
3653 ipoa.ipoa_sotc = SO_TC_UNSPEC;
3654 ipoa.ipoa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
3655 }
3656
3657 struct flowadv *__single adv =
3658 (isipv6 ? &ip6oa.ip6oa_flowadv : &ipoa.ipoa_flowadv);
3659
3660 /* If socket was bound to an ifindex, tell ip_output about it */
3661 if (inp->inp_flags & INP_BOUND_IF) {
3662 if (isipv6) {
3663 ip6oa.ip6oa_boundif = inp->inp_boundifp->if_index;
3664 ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
3665 } else {
3666 ipoa.ipoa_boundif = inp->inp_boundifp->if_index;
3667 ipoa.ipoa_flags |= IPOAF_BOUND_IF;
3668 }
3669 } else if (!in6_embedded_scope && isipv6 && (IN6_IS_SCOPE_EMBED(&inp->in6p_faddr))) {
3670 ip6oa.ip6oa_boundif = inp->inp_fifscope;
3671 ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
3672 }
3673
3674 if (INP_NO_CELLULAR(inp)) {
3675 if (isipv6) {
3676 ip6oa.ip6oa_flags |= IP6OAF_NO_CELLULAR;
3677 } else {
3678 ipoa.ipoa_flags |= IPOAF_NO_CELLULAR;
3679 }
3680 }
3681 if (INP_NO_EXPENSIVE(inp)) {
3682 if (isipv6) {
3683 ip6oa.ip6oa_flags |= IP6OAF_NO_EXPENSIVE;
3684 } else {
3685 ipoa.ipoa_flags |= IPOAF_NO_EXPENSIVE;
3686 }
3687 }
3688 if (INP_NO_CONSTRAINED(inp)) {
3689 if (isipv6) {
3690 ip6oa.ip6oa_flags |= IP6OAF_NO_CONSTRAINED;
3691 } else {
3692 ipoa.ipoa_flags |= IPOAF_NO_CONSTRAINED;
3693 }
3694 }
3695 if (INP_AWDL_UNRESTRICTED(inp)) {
3696 if (isipv6) {
3697 ip6oa.ip6oa_flags |= IP6OAF_AWDL_UNRESTRICTED;
3698 } else {
3699 ipoa.ipoa_flags |= IPOAF_AWDL_UNRESTRICTED;
3700 }
3701 }
3702 if (INP_INTCOPROC_ALLOWED(inp) && isipv6) {
3703 ip6oa.ip6oa_flags |= IP6OAF_INTCOPROC_ALLOWED;
3704 }
3705 if (INP_MANAGEMENT_ALLOWED(inp)) {
3706 if (isipv6) {
3707 ip6oa.ip6oa_flags |= IP6OAF_MANAGEMENT_ALLOWED;
3708 } else {
3709 ipoa.ipoa_flags |= IPOAF_MANAGEMENT_ALLOWED;
3710 }
3711 }
3712 if (INP_ULTRA_CONSTRAINED_ALLOWED(inp)) {
3713 if (isipv6) {
3714 ip6oa.ip6oa_flags |= IP6OAF_ULTRA_CONSTRAINED_ALLOWED;
3715 } else {
3716 ipoa.ipoa_flags |= IPOAF_ULTRA_CONSTRAINED_ALLOWED;
3717 }
3718 }
3719 if (isipv6) {
3720 ip6oa.ip6oa_sotc = so->so_traffic_class;
3721 ip6oa.ip6oa_netsvctype = so->so_netsvctype;
3722 ip6oa.qos_marking_gencount = inp->inp_policyresult.results.qos_marking_gencount;
3723 } else {
3724 ipoa.ipoa_sotc = so->so_traffic_class;
3725 ipoa.ipoa_netsvctype = so->so_netsvctype;
3726 ipoa.qos_marking_gencount = inp->inp_policyresult.results.qos_marking_gencount;
3727 }
3728 if ((so->so_flags1 & SOF1_QOSMARKING_ALLOWED)) {
3729 if (isipv6) {
3730 ip6oa.ip6oa_flags |= IP6OAF_QOSMARKING_ALLOWED;
3731 } else {
3732 ipoa.ipoa_flags |= IPOAF_QOSMARKING_ALLOWED;
3733 }
3734 }
3735 if (check_qos_marking_again) {
3736 if (isipv6) {
3737 ip6oa.ip6oa_flags |= IP6OAF_REDO_QOSMARKING_POLICY;
3738 } else {
3739 ipoa.ipoa_flags |= IPOAF_REDO_QOSMARKING_POLICY;
3740 }
3741 }
3742 if (isipv6) {
3743 flags |= IPV6_OUTARGS;
3744 } else {
3745 flags |= IP_OUTARGS;
3746 }
3747
3748 /* Copy the cached route and take an extra reference */
3749 if (isipv6) {
3750 in6p_route_copyout(inp, &ro6);
3751 } else {
3752 inp_route_copyout(inp, &ro);
3753 }
3754 #if (DEBUG || DEVELOPMENT)
3755 if ((so->so_flags & SOF_MARK_WAKE_PKT) && pkt != NULL) {
3756 so->so_flags &= ~SOF_MARK_WAKE_PKT;
3757 pkt->m_pkthdr.pkt_flags |= PKTF_WAKE_PKT;
3758 }
3759 #endif /* (DEBUG || DEVELOPMENT) */
3760
3761 /*
3762 * Make sure ACK/DELACK conditions are cleared before
3763 * we unlock the socket.
3764 */
3765 tp->last_ack_sent = tp->rcv_nxt;
3766 tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
3767 tp->t_timer[TCPT_DELACK] = 0;
3768 tp->t_unacksegs = 0;
3769 tp->t_unacksegs_ce = 0;
3770
3771 /* Increment the count of outstanding send operations */
3772 inp->inp_sndinprog_cnt++;
3773
3774 /*
3775 * If allowed, unlock TCP socket while in IP
3776 * but only if the connection is established and
3777 * in a normal mode where reentrancy on the tcpcb won't be
3778 * an issue:
3779 * - there is no SACK episode
3780 * - we're not in Fast Recovery mode
3781 * - if we're not sending from an upcall.
3782 */
3783 if (tcp_output_unlocked && !so->so_upcallusecount &&
3784 (tp->t_state == TCPS_ESTABLISHED) && (sack_in_progress == 0) &&
3785 !IN_FASTRECOVERY(tp) && !(so->so_flags & SOF_MP_SUBFLOW)) {
3786 unlocked = TRUE;
3787 socket_unlock(so, 0);
3788 }
3789
3790 /*
3791 * Don't send down a chain of packets when:
3792 * - TCP chaining is disabled
3793 * - there is an IPsec rule set
3794 * - there is a non default rule set for the firewall
3795 */
3796
3797 chain = tcp_packet_chaining > 1
3798 #if IPSEC
3799 && ipsec_bypass
3800 #endif
3801 ; // I'm important, not extraneous
3802
3803 while (pkt != NULL) {
3804 struct mbuf *npkt = pkt->m_nextpkt;
3805
3806 /*
3807 * If enabled, set the RTO deadline for the packet.
3808 */
3809 if (tcp_use_rto_deadline) {
3810 tcp_set_rto_deadline(tp, pkt, isipv6, tcp_now_local);
3811 }
3812
3813 if (!chain) {
3814 pkt->m_nextpkt = NULL;
3815 /*
3816 * If we are not chaining, make sure to set the packet
3817 * list count to 0 so that IP takes the right path;
3818 * this is important for cases such as IPsec where a
3819 * single mbuf might result in multiple mbufs as part
3820 * of the encapsulation. If a non-zero count is passed
3821 * down to IP, the head of the chain might change and
3822 * we could end up skipping it (thus generating bogus
3823 * packets). Fixing it in IP would be desirable, but
3824 * for now this would do it.
3825 */
3826 cnt = 0;
3827 }
3828 if (isipv6) {
3829 error = ip6_output_list(pkt, cnt,
3830 inp->in6p_outputopts, &ro6, flags, NULL, NULL,
3831 &ip6oa);
3832 ifdenied = (ip6oa.ip6oa_flags & IP6OAF_R_IFDENIED);
3833 } else {
3834 error = ip_output_list(pkt, cnt, opt, &ro, flags, NULL,
3835 &ipoa);
3836 ifdenied = (ipoa.ipoa_flags & IPOAF_R_IFDENIED);
3837 }
3838
3839 if (adv->code == FADV_CONGESTED) {
3840 fadv_congested = TRUE;
3841 }
3842
3843 if (chain || error) {
3844 /*
3845 * If we sent down a chain then we are done since
3846 * the callee had taken care of everything; else
3847 * we need to free the rest of the chain ourselves.
3848 */
3849 if (!chain) {
3850 m_drop_list(npkt, NULL, DROPTAP_FLAG_DIR_OUT | DROPTAP_FLAG_L2_MISSING, DROP_REASON_TCP_PKT_UNSENT, NULL, 0);
3851 }
3852 break;
3853 }
3854 pkt = npkt;
3855 }
3856
3857 if (unlocked) {
3858 socket_lock(so, 0);
3859 }
3860
3861 /*
3862 * Enter flow controlled state if the connection is established
3863 * and is not in recovery. Flow control is allowed only if there
3864 * is outstanding data.
3865 *
3866 * A connection will enter suspended state even if it is in
3867 * recovery.
3868 */
3869 if (((adv->code == FADV_FLOW_CONTROLLED && !IN_FASTRECOVERY(tp)) ||
3870 adv->code == FADV_SUSPENDED) &&
3871 !(tp->t_flags & TF_CLOSING) &&
3872 tp->t_state == TCPS_ESTABLISHED &&
3873 SEQ_GT(tp->snd_max, tp->snd_una)) {
3874 int rc;
3875 rc = inp_set_fc_state(inp, adv->code);
3876
3877 if (rc == 1) {
3878 tcp_ccdbg_trace(tp, NULL,
3879 ((adv->code == FADV_FLOW_CONTROLLED) ?
3880 TCP_CC_FLOW_CONTROL : TCP_CC_SUSPEND));
3881 if (adv->code == FADV_FLOW_CONTROLLED) {
3882 TCP_LOG_OUTPUT(tp, "flow controlled");
3883 } else {
3884 TCP_LOG_OUTPUT(tp, "flow suspended");
3885 }
3886 }
3887 }
3888
3889 if (fadv_congested && !IN_FASTRECOVERY(tp) && !(tp->t_flags & TF_CLOSING) &&
3890 tp->t_state == TCPS_ESTABLISHED) {
3891 TCP_LOG_OUTPUT(tp, "flow congestion notified");
3892 tcp_local_congestion_notification(tp);
3893 tcp_ccdbg_trace(tp, NULL, TCP_CC_FLOW_CONGESTION_NOTIFIED);
3894 }
3895
3896 /*
3897 * When an interface queue gets suspended, some of the
3898 * packets are dropped. Return ENOBUFS, to update the
3899 * pcb state.
3900 */
3901 if (adv->code == FADV_SUSPENDED) {
3902 error = ENOBUFS;
3903 }
3904
3905 VERIFY(inp->inp_sndinprog_cnt > 0);
3906 if (--inp->inp_sndinprog_cnt == 0) {
3907 inp->inp_flags &= ~(INP_FC_FEEDBACK);
3908 if (inp->inp_sndingprog_waiters > 0) {
3909 wakeup(&inp->inp_sndinprog_cnt);
3910 }
3911 }
3912
3913 if (isipv6) {
3914 /*
3915 * When an NECP IP tunnel policy forces the outbound interface,
3916 * ip6_output_list() informs the transport layer what is the actual
3917 * outgoing interface
3918 */
3919 if (ip6oa.ip6oa_flags & IP6OAF_BOUND_IF) {
3920 ifnet_head_lock_shared();
3921 outif = ifindex2ifnet[ip6oa.ip6oa_boundif];
3922 ifnet_head_done();
3923 } else if (ro6.ro_rt != NULL) {
3924 outif = ro6.ro_rt->rt_ifp;
3925 }
3926 } else {
3927 if (ro.ro_rt != NULL) {
3928 outif = ro.ro_rt->rt_ifp;
3929 }
3930 }
3931 if (check_qos_marking_again) {
3932 uint32_t qos_marking_gencount;
3933 bool allow_qos_marking;
3934 if (isipv6) {
3935 qos_marking_gencount = ip6oa.qos_marking_gencount;
3936 allow_qos_marking = ip6oa.ip6oa_flags & IP6OAF_QOSMARKING_ALLOWED ? TRUE : FALSE;
3937 } else {
3938 qos_marking_gencount = ipoa.qos_marking_gencount;
3939 allow_qos_marking = ipoa.ipoa_flags & IPOAF_QOSMARKING_ALLOWED ? TRUE : FALSE;
3940 }
3941 inp->inp_policyresult.results.qos_marking_gencount = qos_marking_gencount;
3942 if (allow_qos_marking == TRUE) {
3943 inp->inp_socket->so_flags1 |= SOF1_QOSMARKING_ALLOWED;
3944 } else {
3945 inp->inp_socket->so_flags1 &= ~SOF1_QOSMARKING_ALLOWED;
3946 }
3947 }
3948
3949 if (outif != NULL && outif != inp->inp_last_outifp) {
3950 /* Update the send byte count */
3951 if (so->so_snd.sb_cc > 0 && so->so_snd.sb_flags & SB_SNDBYTE_CNT) {
3952 inp_decr_sndbytes_total(so, so->so_snd.sb_cc);
3953 inp_decr_sndbytes_allunsent(so, tp->snd_una);
3954 so->so_snd.sb_flags &= ~SB_SNDBYTE_CNT;
3955 }
3956 inp->inp_last_outifp = outif;
3957 #if SKYWALK
3958 if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
3959 netns_set_ifnet(&inp->inp_netns_token, inp->inp_last_outifp);
3960 }
3961 #endif /* SKYWALK */
3962 }
3963
3964 if (error != 0 && ifdenied &&
3965 (INP_NO_CELLULAR(inp) || INP_NO_EXPENSIVE(inp) || INP_NO_CONSTRAINED(inp))) {
3966 soevent(so,
3967 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_IFDENIED));
3968 }
3969
3970 /* Synchronize cached PCB route & options */
3971 if (isipv6) {
3972 in6p_route_copyin(inp, &ro6);
3973 } else {
3974 inp_route_copyin(inp, &ro);
3975 }
3976
3977 if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift == 0 &&
3978 tp->t_inpcb->inp_route.ro_rt != NULL) {
3979 /* If we found the route and there is an rtt on it
3980 * reset the retransmit timer
3981 */
3982 tcp_getrt_rtt(tp, tp->t_inpcb->in6p_route.ro_rt);
3983 tcp_set_rto(tp);
3984 }
3985 return error;
3986 #undef ro
3987 #undef ro6
3988 #undef ipoa
3989 #undef ip6oa
3990 }
3991
3992 int tcptv_persmin_val = TCPTV_PERSMIN;
3993
3994 void
tcp_setpersist(struct tcpcb * tp)3995 tcp_setpersist(struct tcpcb *tp)
3996 {
3997 int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
3998
3999 /* If a PERSIST_TIMER option was set we will limit the
4000 * time the persist timer will be active for that connection
4001 * in order to avoid DOS by using zero window probes.
4002 * see rdar://5805356
4003 */
4004
4005 if (tp->t_persist_timeout != 0 &&
4006 tp->t_timer[TCPT_PERSIST] == 0 &&
4007 tp->t_persist_stop == 0) {
4008 tp->t_persist_stop = tcp_now + tp->t_persist_timeout;
4009 }
4010
4011 /*
4012 * Start/restart persistance timer.
4013 */
4014 TCPT_RANGESET(tp->t_timer[TCPT_PERSIST],
4015 t * tcp_backoff[tp->t_rxtshift],
4016 tcptv_persmin_val, TCPTV_PERSMAX, 0);
4017 tp->t_timer[TCPT_PERSIST] = tcp_offset_from_start(tp, tp->t_timer[TCPT_PERSIST]);
4018
4019 if (tp->t_rxtshift < TCP_MAXRXTSHIFT) {
4020 tp->t_rxtshift++;
4021 }
4022 }
4023
4024 static int
tcp_recv_throttle(struct tcpcb * tp)4025 tcp_recv_throttle(struct tcpcb *tp)
4026 {
4027 uint32_t base_rtt, newsize;
4028 struct sockbuf *__single sbrcv = &tp->t_inpcb->inp_socket->so_rcv;
4029
4030 if (tcp_use_rtt_recvbg == 1 &&
4031 TSTMP_SUPPORTED(tp)) {
4032 /*
4033 * Timestamps are supported on this connection. Use
4034 * RTT to look for an increase in latency.
4035 */
4036
4037 /*
4038 * If the connection is already being throttled, leave it
4039 * in that state until rtt comes closer to base rtt
4040 */
4041 if (tp->t_flagsext & TF_RECV_THROTTLE) {
4042 return 1;
4043 }
4044
4045 base_rtt = get_base_rtt(tp);
4046
4047 if (base_rtt != 0 && tp->t_rttcur != 0) {
4048 /*
4049 * if latency increased on a background flow,
4050 * return 1 to start throttling.
4051 */
4052 if (tp->t_rttcur > (base_rtt + target_qdelay)) {
4053 tp->t_flagsext |= TF_RECV_THROTTLE;
4054 if (tp->t_recv_throttle_ts == 0) {
4055 tp->t_recv_throttle_ts = tcp_now;
4056 }
4057 /*
4058 * Reduce the recv socket buffer size to
4059 * minimize latecy.
4060 */
4061 if (sbrcv->sb_idealsize >
4062 tcp_recv_throttle_minwin) {
4063 newsize = sbrcv->sb_idealsize >> 1;
4064 /* Set a minimum of 16 K */
4065 newsize =
4066 max(newsize,
4067 tcp_recv_throttle_minwin);
4068 sbrcv->sb_idealsize = newsize;
4069 }
4070 return 1;
4071 } else {
4072 return 0;
4073 }
4074 }
4075 }
4076
4077 /*
4078 * Timestamps are not supported or there is no good RTT
4079 * measurement. Use IPDV in this case.
4080 */
4081 if (tp->acc_iaj > tcp_acc_iaj_react_limit) {
4082 return 1;
4083 }
4084
4085 return 0;
4086 }
4087