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