staticbool tcp_write_xmit(struct sock *sk, unsignedint mss_now, int nonagle, int push_one, gfp_t gfp);
/* Account for new data that has been sent to the network. */ staticvoid tcp_event_new_data_sent(struct sock *sk, struct sk_buff *skb)
{ struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); unsignedint prior_packets = tp->packets_out;
/* SND.NXT, if window was not shrunk or the amount of shrunk was less than one *windowscalingfactorduetolossofprecision. *Ifwindowhasbeenshrunk,whatshouldwemake?Itisnotclearatall. *UsingSND.UNAwewillfailtoopenwindow,SND.NXTisoutofwindow.:-( *AnythinginbetweenSND.UNA...SND.UNA+SND.WNDalsocanbealready *invalid.OK,let'smakethisfornow:
*/ staticinline __u32 tcp_acceptable_seq(conststruct sock *sk)
{ conststruct tcp_sock *tp = tcp_sk(sk);
/* Congestion state accounting after a packet has been sent. */ staticvoid tcp_event_data_sent(struct tcp_sock *tp, struct sock *sk)
{ struct inet_connection_sock *icsk = inet_csk(sk); const u32 now = tcp_jiffies32;
if (tcp_packets_in_flight(tp) == 0)
tcp_ca_event(sk, CA_EVENT_TX_START);
tp->lsndtime = now;
/* If it is a reply for ato after last received *packet,increasepingpongcount.
*/ if ((u32)(now - icsk->icsk_ack.lrcvtime) < icsk->icsk_ack.ato)
inet_csk_inc_pingpong_cnt(sk);
}
/* Account for an ACK we sent. */ staticinlinevoid tcp_event_ack_sent(struct sock *sk, u32 rcv_nxt)
{ struct tcp_sock *tp = tcp_sk(sk);
if (unlikely(tp->compressed_ack)) {
NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPACKCOMPRESSED,
tp->compressed_ack);
tp->compressed_ack = 0; if (hrtimer_try_to_cancel(&tp->compressed_ack_timer) == 1)
__sock_put(sk);
}
if (unlikely(rcv_nxt != tp->rcv_nxt)) return; /* Special ACK sent by DCTCP to reflect ECN */
tcp_dec_quickack_mode(sk);
inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK);
}
/* Determine a window scaling and initial window to offer. *Basedontheassumptionthatthegivenamountofspace *willbeoffered.Storetheresultsinthetpstructure. *NOTE:forsmoothoperationinitialspaceofferingshould *beamultipleofmssifpossible.Weassumeherethatmss>=1. *ThisMUSTbeenforcedbyallcallers.
*/ void tcp_select_initial_window(conststruct sock *sk, int __space, __u32 mss,
__u32 *rcv_wnd, __u32 *__window_clamp, int wscale_ok, __u8 *rcv_wscale,
__u32 init_rcv_wnd)
{ unsignedint space = (__space < 0 ? 0 : __space);
u32 window_clamp = READ_ONCE(*__window_clamp);
/* If no clamp set the clamp to the max possible scaled window */ if (window_clamp == 0)
window_clamp = (U16_MAX << TCP_MAX_WSCALE);
space = min(window_clamp, space);
/* Quantize space offering to a multiple of mss if possible. */ if (space > mss)
space = rounddown(space, mss);
/* NOTE: offering an initial window larger than 32767 *willbreaksomebuggyTCPstacks.Iftheadmintellsus *itislikelywecouldbespeakingwithsuchabuggystack *wewilltruncateourinitialwindowofferingto32K-1 *unlesstheremotehassentusawindowscalingoption, *whichweinterpretasasigntheremoteTCPisnot *misinterpretingthewindowfieldasasignedquantity.
*/ if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_workaround_signed_windows))
(*rcv_wnd) = min(space, MAX_TCP_WINDOW); else
(*rcv_wnd) = space;
if (init_rcv_wnd)
*rcv_wnd = min(*rcv_wnd, init_rcv_wnd * mss);
*rcv_wscale = 0; if (wscale_ok) { /* Set window scaling on max possible window */
space = max_t(u32, space, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]));
space = max_t(u32, space, READ_ONCE(sysctl_rmem_max));
space = min_t(u32, space, window_clamp);
*rcv_wscale = clamp_t(int, ilog2(space) - 15, 0, TCP_MAX_WSCALE);
} /* Set the clamp no higher than max representable value */
WRITE_ONCE(*__window_clamp,
min_t(__u32, U16_MAX << (*rcv_wscale), window_clamp));
}
EXPORT_IPV6_MOD(tcp_select_initial_window);
/* Chose a new window to advertise, update state in tcp_sock for the *socket,andreturnresultwithRFC1323scalingapplied.Thereturn *valuecanbestuffeddirectlyintoth->windowforanoutgoing *frame.
*/ static u16 tcp_select_window(struct sock *sk)
{ struct tcp_sock *tp = tcp_sk(sk); struct net *net = sock_net(sk);
u32 old_win = tp->rcv_wnd;
u32 cur_win, new_win;
/* Make the window 0 if we failed to queue the data because we *areoutofmemory.
*/ if (unlikely(inet_csk(sk)->icsk_ack.pending & ICSK_ACK_NOMEM)) {
tp->pred_flags = 0;
tp->rcv_wnd = 0;
tp->rcv_wup = tp->rcv_nxt; return0;
}
cur_win = tcp_receive_window(tp);
new_win = __tcp_select_window(sk); if (new_win < cur_win) { /* Danger Will Robinson! *Don'tupdatercv_wup/rcv_wndhereorelse *wewillnotbeabletoadvertiseazero *windowintime.--DaveM * *RelaxWillRobinson.
*/ if (!READ_ONCE(net->ipv4.sysctl_tcp_shrink_window) || !tp->rx_opt.rcv_wscale) { /* Never shrink the offered window */ if (new_win == 0)
NET_INC_STATS(net, LINUX_MIB_TCPWANTZEROWINDOWADV);
new_win = ALIGN(cur_win, 1 << tp->rx_opt.rcv_wscale);
}
}
tp->rcv_wnd = new_win;
tp->rcv_wup = tp->rcv_nxt;
/* Make sure we do not exceed the maximum possible *scaledwindow.
*/ if (!tp->rx_opt.rcv_wscale &&
READ_ONCE(net->ipv4.sysctl_tcp_workaround_signed_windows))
new_win = min(new_win, MAX_TCP_WINDOW); else
new_win = min(new_win, (65535U << tp->rx_opt.rcv_wscale));
if (!use_ecn) { conststruct dst_entry *dst = __sk_dst_get(sk);
if (dst && dst_feature(dst, RTAX_FEATURE_ECN))
use_ecn = true;
}
tp->ecn_flags = 0;
if (use_ecn) {
TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_ECE | TCPHDR_CWR;
tcp_ecn_mode_set(tp, TCP_ECN_MODE_RFC3168); if (tcp_ca_needs_ecn(sk) || bpf_needs_ecn)
INET_ECN_xmit(sk);
}
}
staticvoid tcp_ecn_clear_syn(struct sock *sk, struct sk_buff *skb)
{ if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_ecn_fallback)) /* tp->ecn_flags are cleared at a later point in time when *SYNACKisultimativelybeingreceived.
*/
TCP_SKB_CB(skb)->tcp_flags &= ~(TCPHDR_ECE | TCPHDR_CWR);
}
/* Set up ECN state for a packet on a ESTABLISHED socket that is about to *besent.
*/ staticvoid tcp_ecn_send(struct sock *sk, struct sk_buff *skb, struct tcphdr *th, int tcp_header_len)
{ struct tcp_sock *tp = tcp_sk(sk);
if (tcp_ecn_mode_rfc3168(tp)) { /* Not-retransmitted data segment: set ECT and inject CWR. */ if (skb->len != tcp_header_len &&
!before(TCP_SKB_CB(skb)->seq, tp->snd_nxt)) {
INET_ECN_xmit(sk); if (tp->ecn_flags & TCP_ECN_QUEUE_CWR) {
tp->ecn_flags &= ~TCP_ECN_QUEUE_CWR;
th->cwr = 1;
skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
}
} elseif (!tcp_ca_needs_ecn(sk)) { /* ACK or retransmitted segment: clear ECT|CE */
INET_ECN_dontxmit(sk);
} if (tp->ecn_flags & TCP_ECN_DEMAND_CWR)
th->ece = 1;
}
}
/* Constructs common control bits of non-data skb. If SYN/FIN is present, *autoincrementendseqno.
*/ staticvoid tcp_init_nondata_skb(struct sk_buff *skb, u32 seq, u16 flags)
{
skb->ip_summed = CHECKSUM_PARTIAL;
sock_ops.args[0] = bpf_skops_write_hdr_opt_arg0(skb, synack_type);
sock_ops.remaining_opt_len = *remaining; /* tcp_current_mss() does not pass a skb */ if (skb)
bpf_skops_init_skb(&sock_ops, skb, 0);
if (mptcp_synack_options(req, &size, &opts->mptcp)) { if (*remaining >= size) {
opts->options |= OPTION_MPTCP;
*remaining -= size;
}
}
}
}
/* Compute TCP options for SYN packets. This is not the final *networkwireformatyet.
*/ staticunsignedint tcp_syn_options(struct sock *sk, struct sk_buff *skb, struct tcp_out_options *opts, struct tcp_key *key)
{ struct tcp_sock *tp = tcp_sk(sk); unsignedint remaining = MAX_TCP_OPTION_SPACE; struct tcp_fastopen_request *fastopen = tp->fastopen_req; bool timestamps;
/* Better than switch (key.type) as it has static branches */ if (tcp_key_is_md5(key)) {
timestamps = false;
opts->options |= OPTION_MD5;
remaining -= TCPOLEN_MD5SIG_ALIGNED;
} else {
timestamps = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_timestamps); if (tcp_key_is_ao(key)) {
opts->options |= OPTION_AO;
remaining -= tcp_ao_len_aligned(key->ao_key);
}
}
/* We always get an MSS option. The option bytes which will be seen in *normaldatapacketsshouldtimestampsbeused,mustbeintheMSS *advertised.Butwesubtractthemfromtp->mss_cachesothat *calculationsintcp_sendmsgaresimpleretc.Soaccountforthis *facthereifnecessary.Ifwedon'tdothiscorrectly,asa *receiverwewon'trecognizedatapacketsasbeingfullsizedwhenwe *should,andthuswewon'tabidebythedelayedACKrulescorrectly. *SACKsdon'tmatter,weneverdelayanACKwhenwehaveanyofthose
* going out. */
opts->mss = tcp_advertise_mss(sk);
remaining -= TCPOLEN_MSS_ALIGNED;
/* perform an atomic operation only if at least one flag is set */ do { if (!(flags & TCP_DEFERRED_ALL)) return;
nflags = flags & ~TCP_DEFERRED_ALL;
} while (!try_cmpxchg(&sk->sk_tsq_flags, &flags, nflags));
if (flags & TCPF_TSQ_DEFERRED) {
tcp_tsq_write(sk);
__sock_put(sk);
}
if (flags & TCPF_WRITE_TIMER_DEFERRED) {
tcp_write_timer_handler(sk);
__sock_put(sk);
} if (flags & TCPF_DELACK_TIMER_DEFERRED) {
tcp_delack_timer_handler(sk);
__sock_put(sk);
} if (flags & TCPF_MTU_REDUCED_DEFERRED) {
inet_csk(sk)->icsk_af_ops->mtu_reduced(sk);
__sock_put(sk);
} if ((flags & TCPF_ACK_DEFERRED) && inet_csk_ack_scheduled(sk))
tcp_send_ack(sk);
}
EXPORT_IPV6_MOD(tcp_release_cb);
/* Keep one reference on sk_wmem_alloc. *Willbereleasedbysk_free()fromhereortcp_tsq_workfn()
*/
WARN_ON(refcount_sub_and_test(skb->truesize - 1, &sk->sk_wmem_alloc));
/* If this softirq is serviced by ksoftirqd, we are likely under stress. *Waituntilourqueues(qdisc+devices)aredrained. *Thisgives: *-lesscallbackstotcp_write_xmit(),reducingstress(batches) *-chanceforincomingACK(processedbyanothercpumaybe) *tomigratethisflow(skb->ooo_okaywillbeeventuallyset)
*/ if (refcount_read(&sk->sk_wmem_alloc) >= SKB_TRUESIZE(1) && this_cpu_ksoftirqd() == current) goto out;
oval = smp_load_acquire(&sk->sk_tsq_flags); do { if (!(oval & TSQF_THROTTLED) || (oval & TSQF_QUEUED)) goto out;
if (unlikely(!skb)) return -ENOBUFS; /* retransmit skbs might have a non zero value in skb->dev *becauseskb->devisaliasedwithskb->rbnode.rb_left
*/
skb->dev = NULL;
}
tcp_get_current_key(sk, &key); if (unlikely(tcb->tcp_flags & TCPHDR_SYN)) {
tcp_options_size = tcp_syn_options(sk, skb, &opts, &key);
} else {
tcp_options_size = tcp_established_options(sk, skb, &opts, &key); /* Force a PSH flag on all (GSO) packets to expedite GRO flush *atreceiver:ThisslightlyimproveGROperformance. *NotethatwedonotforcethePSHflagfornonGSOpackets, *becausetheymightbesentunderhighcongestionevents, *andinthiscaseitisbettertodelaythedeliveryof1-MSS *packetsandthusthecorrespondingACKpacketthatwould *releasethefollowingpacket.
*/ if (tcp_skb_pcount(skb) > 1)
tcb->tcp_flags |= TCPHDR_PSH;
}
tcp_header_size = tcp_options_size + sizeof(struct tcphdr);
/* We set skb->ooo_okay to one if this packet can select *adifferentTXqueuethanpriorpacketsofthisflow, *toavoidselfinflictedreorders. *The'other'queuedecisionisbasedoncurrentcpunumber *ifXPSisenabled,orsk->sk_txhashotherwise. *Wecanswitchtoanother(andbetter)queueif: *1)Nopacketwithpayloadisinqdisc/devicequeues. *DelaysinTXcompletioncandefeatthetest *evenifpacketswerealreadysent. *2)Orrtxqueueisempty. *ThismitigatesabovecaseifACKpacketsfor *allpriorpacketswerealreadyprocessed.
*/
skb->ooo_okay = sk_wmem_alloc_get(sk) < SKB_TRUESIZE(1) ||
tcp_rtx_queue_empty(sk);
/* If we had to use memory reserve to allocate this skb, *thismightcausedropsifpacketisloopedback: *OthersocketmightnothaveSOCK_MEMALLOC. *Packetsnotloopedbackdonotcareaboutpfmemalloc.
*/
skb->pfmemalloc = 0;
/* The urg_mode check is necessary during a below snd_una win probe */ if (unlikely(tcp_urg_mode(tp) && before(tcb->seq, tp->snd_up))) { if (before(tp->snd_up, tcb->seq + 0x10000)) {
th->urg_ptr = htons(tp->snd_up - tcb->seq);
th->urg = 1;
} elseif (after(tcb->seq + 0xFFFF, tp->snd_nxt)) {
th->urg_ptr = htons(0xFFFF);
th->urg = 1;
}
}
skb_shinfo(skb)->gso_type = sk->sk_gso_type; if (likely(!(tcb->tcp_flags & TCPHDR_SYN))) {
th->window = htons(tcp_select_window(sk));
tcp_ecn_send(sk, skb, th, tcp_header_size);
} else { /* RFC1323: The window in SYN & SYN/ACK segments *isneverscaled.
*/
th->window = htons(min(tp->rcv_wnd, 65535U));
}
tcp_options_write(th, tp, NULL, &opts, &key);
if (tcp_key_is_md5(&key)) { #ifdef CONFIG_TCP_MD5SIG /* Calculate the MD5 hash, as we have all we need now */
sk_gso_disable(sk);
tp->af_specific->calc_md5_hash(opts.hash_location,
key.md5_key, sk, skb); #endif
} elseif (tcp_key_is_ao(&key)) { int err;
if (after(tcb->end_seq, tp->snd_nxt) || tcb->seq == tcb->end_seq)
TCP_ADD_STATS(sock_net(sk), TCP_MIB_OUTSEGS,
tcp_skb_pcount(skb));
tp->segs_out += tcp_skb_pcount(skb);
skb_set_hash_from_sk(skb, sk); /* OK, its time to fill skb_shinfo(skb)->gso_{segs|size} */
skb_shinfo(skb)->gso_segs = tcp_skb_pcount(skb);
skb_shinfo(skb)->gso_size = tcp_skb_mss(skb);
/* Leave earliest departure time in skb->tstamp (skb->skb_mstamp_ns) */
/* Cleanup our debris for IP stacks */
memset(skb->cb, 0, max(sizeof(struct inet_skb_parm), sizeof(struct inet6_skb_parm)));
/* This routine just queues the buffer for sending. * *NOTE:probe0timerisnotchecked,donotforgettcp_push_pending_frames, *otherwisesocketcanstall.
*/ staticvoid tcp_queue_skb(struct sock *sk, struct sk_buff *skb)
{ struct tcp_sock *tp = tcp_sk(sk);
/* Advance write_seq and place onto the write_queue. */
WRITE_ONCE(tp->write_seq, TCP_SKB_CB(skb)->end_seq);
__skb_header_release(skb);
tcp_add_write_queue_tail(sk, skb);
sk_wmem_queued_add(sk, skb->truesize);
sk_mem_charge(sk, skb->truesize);
}
/* Initialize TSO segments for a packet. */ staticint tcp_set_skb_tso_segs(struct sk_buff *skb, unsignedint mss_now)
{ int tso_segs;
if (skb->len <= mss_now) { /* Avoid the costly divide in the normal *non-TSOcase.
*/
TCP_SKB_CB(skb)->tcp_gso_size = 0;
tcp_skb_pcount_set(skb, 1); return1;
}
TCP_SKB_CB(skb)->tcp_gso_size = mss_now;
tso_segs = DIV_ROUND_UP(skb->len, mss_now);
tcp_skb_pcount_set(skb, tso_segs); return tso_segs;
}
/* Pcount in the middle of the write queue got changed, we need to do various *tweakstofixcounters
*/ staticvoid tcp_adjust_pcount(struct sock *sk, conststruct sk_buff *skb, int decr)
{ struct tcp_sock *tp = tcp_sk(sk);
tp->packets_out -= decr;
if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
tp->sacked_out -= decr; if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS)
tp->retrans_out -= decr; if (TCP_SKB_CB(skb)->sacked & TCPCB_LOST)
tp->lost_out -= decr;
/* Reno case is special. Sigh... */ if (tcp_is_reno(tp) && decr > 0)
tp->sacked_out -= min_t(u32, tp->sacked_out, decr);
/* Insert buff after skb on the write or rtx queue of sk. */ staticvoid tcp_insert_write_queue_after(struct sk_buff *skb, struct sk_buff *buff, struct sock *sk, enum tcp_queue tcp_queue)
{ if (tcp_queue == TCP_FRAG_IN_WRITE_QUEUE)
__skb_queue_after(&sk->sk_write_queue, skb, buff); else
tcp_rbtree_insert(&sk->tcp_rtx_queue, buff);
}
/* Function to create two new TCP segments. Shrinks the given segment *tothespecifiedsizeandappendsanewsegmentwiththerestofthe *packettothelist.Thiswon'tbecalledfrequently,Ihope. *Remember,thesearestillheaderlessSKBsatthispoint.
*/ int tcp_fragment(struct sock *sk, enum tcp_queue tcp_queue, struct sk_buff *skb, u32 len, unsignedint mss_now, gfp_t gfp)
{ struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *buff; int old_factor; long limit;
u16 flags; int nlen;
if (WARN_ON(len > skb->len)) return -EINVAL;
DEBUG_NET_WARN_ON_ONCE(skb_headlen(skb));
/* tcp_sendmsg() can overshoot sk_wmem_queued by one full size skb. *Weneedsomeallowancetonotpenalizeapplicationssettingsmall *SO_SNDBUFvalues. *Alsoallowfirstandlastskbinretransmitqueuetobesplit.
*/
limit = sk->sk_sndbuf + 2 * SKB_TRUESIZE(GSO_LEGACY_MAX_SIZE); if (unlikely((sk->sk_wmem_queued >> 1) > limit &&
tcp_queue != TCP_FRAG_IN_WRITE_QUEUE &&
skb != tcp_rtx_queue_head(sk) &&
skb != tcp_rtx_queue_tail(sk))) {
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPWQUEUETOOBIG); return -ENOMEM;
}
if (skb_unclone_keeptruesize(skb, gfp)) return -ENOMEM;
/* Get a new skb... force flag on. */
buff = tcp_stream_alloc_skb(sk, gfp, true); if (!buff) return -ENOMEM; /* We'll just try again later. */
skb_copy_decrypted(buff, skb);
mptcp_skb_ext_copy(buff, skb);
/* PSH and FIN should only be set in the second packet. */
flags = TCP_SKB_CB(skb)->tcp_flags;
TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH);
TCP_SKB_CB(buff)->tcp_flags = flags;
TCP_SKB_CB(buff)->sacked = TCP_SKB_CB(skb)->sacked;
tcp_skb_fragment_eor(skb, buff);
/* Fix up tso_factor for both original and new SKB. */
tcp_set_skb_tso_segs(skb, mss_now);
tcp_set_skb_tso_segs(buff, mss_now);
/* Update delivered info for the new segment */
TCP_SKB_CB(buff)->tx = TCP_SKB_CB(skb)->tx;
/* If this packet has been sent out already, we must *adjustthevariouspacketcounters.
*/ if (!before(tp->snd_nxt, TCP_SKB_CB(buff)->end_seq)) { int diff = old_factor - tcp_skb_pcount(skb) -
tcp_skb_pcount(buff);
if (diff)
tcp_adjust_pcount(sk, skb, diff);
}
/* Link BUFF into the send queue. */
__skb_header_release(buff);
tcp_insert_write_queue_after(skb, buff, sk, tcp_queue); if (tcp_queue == TCP_FRAG_IN_RTX_QUEUE)
list_add(&buff->tcp_tsorted_anchor, &skb->tcp_tsorted_anchor);
return0;
}
/* This is similar to __pskb_pull_tail(). The difference is that pulled *dataisnotcopied,butimmediatelydiscarded.
*/ staticint __pskb_trim_head(struct sk_buff *skb, int len)
{ struct skb_shared_info *shinfo; int i, k, eat;
DEBUG_NET_WARN_ON_ONCE(skb_headlen(skb));
eat = len;
k = 0;
shinfo = skb_shinfo(skb); for (i = 0; i < shinfo->nr_frags; i++) { int size = skb_frag_size(&shinfo->frags[i]);
/* Remove acked data from a packet in the transmit queue. */ int tcp_trim_head(struct sock *sk, struct sk_buff *skb, u32 len)
{
u32 delta_truesize;
if (skb_unclone_keeptruesize(skb, GFP_ATOMIC)) return -ENOMEM;
delta_truesize = __pskb_trim_head(skb, len);
TCP_SKB_CB(skb)->seq += len;
skb->truesize -= delta_truesize;
sk_wmem_queued_add(sk, -delta_truesize); if (!skb_zcopy_pure(skb))
sk_mem_uncharge(sk, delta_truesize);
/* Any change of skb->len requires recalculation of tso factor. */ if (tcp_skb_pcount(skb) > 1)
tcp_set_skb_tso_segs(skb, tcp_skb_mss(skb));
return0;
}
/* Calculate MSS not accounting any TCP options. */ staticinlineint __tcp_mtu_to_mss(struct sock *sk, int pmtu)
{ conststruct tcp_sock *tp = tcp_sk(sk); conststruct inet_connection_sock *icsk = inet_csk(sk); int mss_now;
/* Calculate base mss without TCP options: ItisMMS_S-sizeof(tcphdr)ofrfc1122
*/
mss_now = pmtu - icsk->icsk_af_ops->net_header_len - sizeof(struct tcphdr);
/* Clamp it (mss_clamp does not include tcp options) */ if (mss_now > tp->rx_opt.mss_clamp)
mss_now = tp->rx_opt.mss_clamp;
/* Now subtract optional transport overhead */
mss_now -= icsk->icsk_ext_hdr_len;
/* Then reserve room for full set of TCP options and 8 bytes of data */
mss_now = max(mss_now,
READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_snd_mss)); return mss_now;
}
/* Calculate MSS. Not accounting for SACKs here. */ int tcp_mtu_to_mss(struct sock *sk, int pmtu)
{ /* Subtract TCP options size, not including SACKs */ return __tcp_mtu_to_mss(sk, pmtu) -
(tcp_sk(sk)->tcp_header_len - sizeof(struct tcphdr));
}
EXPORT_IPV6_MOD(tcp_mtu_to_mss);
/* Inverse of above */ int tcp_mss_to_mtu(struct sock *sk, int mss)
{ conststruct tcp_sock *tp = tcp_sk(sk); conststruct inet_connection_sock *icsk = inet_csk(sk);
/* And store cached results */
icsk->icsk_pmtu_cookie = pmtu; if (icsk->icsk_mtup.enabled)
mss_now = min(mss_now, tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_low));
tp->mss_cache = mss_now;
return mss_now;
}
EXPORT_IPV6_MOD(tcp_sync_mss);
/* Compute the current effective MSS, taking SACKs and IP options, *andevenPMTUdiscoveryeventsintoaccount.
*/ unsignedint tcp_current_mss(struct sock *sk)
{ conststruct tcp_sock *tp = tcp_sk(sk); conststruct dst_entry *dst = __sk_dst_get(sk);
u32 mss_now; unsignedint header_len; struct tcp_out_options opts; struct tcp_key key;
mss_now = tp->mss_cache;
if (dst) {
u32 mtu = dst_mtu(dst); if (mtu != inet_csk(sk)->icsk_pmtu_cookie)
mss_now = tcp_sync_mss(sk, mtu);
}
tcp_get_current_key(sk, &key);
header_len = tcp_established_options(sk, NULL, &opts, &key) + sizeof(struct tcphdr); /* The mss_cache is sized based on tp->tcp_header_len, which assumes *somecommonoptions.Ifthisisanoddpacket(becausewehaveSACK *blocksetc)thenourcalculatedheader_lenwillbedifferent,and
* we have to adjust mss_now correspondingly */ if (header_len != tp->tcp_header_len) { int delta = (int) header_len - tp->tcp_header_len;
mss_now -= delta;
}
return mss_now;
}
/* RFC2861, slow part. Adjust cwnd, after it was not full during one rto. *Asadditionalprotections,wedonottouchcwndinretransmissionphases, *andifapplicationhititssndbuflimitrecently.
*/ staticvoid tcp_cwnd_application_limited(struct sock *sk)
{ struct tcp_sock *tp = tcp_sk(sk);
/* Track the strongest available signal of the degree to which the cwnd *isfullyutilized.Ifcwnd-limitedthenrememberthatfactforthe *currentwindow.Ifnotcwnd-limitedthentrackthemaximumnumberof *outstandingpacketsinthecurrentwindow.(Ifcwnd-limitedthenwe *chosetonotupdatetp->max_packets_outtoavoidanextraelse *clausewithnofunctionalimpact.)
*/ if (!before(tp->snd_una, tp->cwnd_usage_seq) ||
is_cwnd_limited ||
(!tp->is_cwnd_limited &&
tp->packets_out > tp->max_packets_out)) {
tp->is_cwnd_limited = is_cwnd_limited;
tp->max_packets_out = tp->packets_out;
tp->cwnd_usage_seq = tp->snd_nxt;
}
if (tcp_is_cwnd_limited(sk)) { /* Network is feed fully. */
tp->snd_cwnd_used = 0;
tp->snd_cwnd_stamp = tcp_jiffies32;
} else { /* Network starves. */ if (tp->packets_out > tp->snd_cwnd_used)
tp->snd_cwnd_used = tp->packets_out;
/* Return the number of segments we want in the skb we are transmitting. *Seeifcongestioncontrolmodulewantstodecide;otherwise,autosize.
*/ static u32 tcp_tso_segs(struct sock *sk, unsignedint mss_now)
{ conststruct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
u32 min_tso, tso_segs;
/* Returns the portion of skb which can be sent right away */ staticunsignedint tcp_mss_split_point(conststruct sock *sk, conststruct sk_buff *skb, unsignedint mss_now, unsignedint max_segs, int nonagle)
{ conststruct tcp_sock *tp = tcp_sk(sk);
u32 partial, needed, window, max_len;
if (likely(max_len <= window && skb != tcp_write_queue_tail(sk))) return max_len;
needed = min(skb->len, window);
if (max_len <= needed) return max_len;
partial = needed % mss_now; /* If last segment is not a full MSS, check if Nagle rules allow us *toincludethislastsegmentinthisskb. *Otherwise,we'llsplittheskbatlastMSSboundary
*/ if (tcp_nagle_check(partial != 0, tp, nonagle)) return needed - partial;
return needed;
}
/* Can at least one segment of SKB be sent right now, according to the *congestionwindowrules?Ifso,returnhowmanysegmentsareallowed.
*/ static u32 tcp_cwnd_test(conststruct tcp_sock *tp)
{
u32 in_flight, cwnd, halfcwnd;
/* Return true if the Nagle test allows this packet to be *sentnow.
*/ staticinlinebool tcp_nagle_test(conststruct tcp_sock *tp, conststruct sk_buff *skb, unsignedint cur_mss, int nonagle)
{ /* Nagle rule does not apply to frames, which sit in the middle of the *write_queue(theyhavenochancestogetnewdata). * *Thisisimplementedinthecallers,wheretheymodifythe'nonagle' *argumentbaseduponthelocationofSKBinthesendqueue.
*/ if (nonagle & TCP_NAGLE_PUSH) returntrue;
/* Don't use the nagle rule for urgent data (or for the final FIN). */ if (tcp_urg_mode(tp) || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) returntrue;
if (!tcp_nagle_check(skb->len < cur_mss, tp, nonagle)) returntrue;
returnfalse;
}
/* Does at least the first segment of SKB fit into the send window? */ staticbool tcp_snd_wnd_test(conststruct tcp_sock *tp, conststruct sk_buff *skb, unsignedint cur_mss)
{
u32 end_seq = TCP_SKB_CB(skb)->end_seq;
if (skb->len > cur_mss)
end_seq = TCP_SKB_CB(skb)->seq + cur_mss;
return !after(end_seq, tcp_wnd_end(tp));
}
/* Trim TSO SKB to LEN bytes, put the remaining data into a new packet *whichisputafterSKBonthelist.Itisverymuchlike *tcp_fragment()exceptthatitmaymakeseveralkindsofassumptions *inordertospeedupthesplittingoperation.Inparticular,we *knowthatallthedataisinscatter-gatherpages,andthatthe *packethasneverbeensentoutbefore(andthusisnotcloned).
*/ staticint tso_fragment(struct sock *sk, struct sk_buff *skb, unsignedint len, unsignedint mss_now, gfp_t gfp)
{ int nlen = skb->len - len; struct sk_buff *buff;
u16 flags;
/* All of a TSO frame must be composed of paged data. */
DEBUG_NET_WARN_ON_ONCE(skb->len != skb->data_len);
/* PSH and FIN should only be set in the second packet. */
flags = TCP_SKB_CB(skb)->tcp_flags;
TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH);
TCP_SKB_CB(buff)->tcp_flags = flags;
/* If at least some fraction of a window is available, *justuseit.
*/
chunk /= win_divisor; if (limit >= chunk) goto send_now;
} else { /* Different approach, try not to defer past a single *ACK.ReceivershouldACKeveryotherfullsized *frame,soifwehavespaceformorethan3frames *thensendnow.
*/ if (limit > tcp_max_tso_deferred_mss(tp) * tp->mss_cache) goto send_now;
}
/* TODO : use tsorted_sent_queue ? */
head = tcp_rtx_queue_head(sk); if (!head) goto send_now;
srtt_in_ns = (u64)(NSEC_PER_USEC >> 3) * tp->srtt_us; /* When is the ACK expected ? */
expected_ack = head->tstamp + srtt_in_ns; /* How far from now is the ACK expected ? */
how_far_is_the_ack = expected_ack - tp->tcp_clock_cache;
/* If next ACK is likely to come too late, *ieinmorethanmin(1ms,halfsrtt),donotdefer.
*/
threshold = min(srtt_in_ns >> 1, NSEC_PER_MSEC);
if ((s64)(how_far_is_the_ack - threshold) > 0) goto send_now;
/* Ok, it looks like it is advisable to defer. *Threecasesaretracked: *1)Wearecwnd-limited *2)Wearerwnd-limited *3)Weareapplicationlimited.
*/ if (cong_win < send_win) { if (cong_win <= skb->len) {
*is_cwnd_limited = true; returntrue;
}
} else { if (send_win <= skb->len) {
*is_rwnd_limited = true; returntrue;
}
}
/* If this packet won't get more data, do not wait. */ if ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) ||
TCP_SKB_CB(skb)->eor) goto send_now;
/* tcp_mtu_probe() and tcp_grow_skb() can both eat an skb (src) if *allitspayloadwasmovedtoanotherone(dst). *Makesuretotransfertcp_flags,eor,andtstamp.
*/ staticvoid tcp_eat_one_skb(struct sock *sk, struct sk_buff *dst, struct sk_buff *src)
{
TCP_SKB_CB(dst)->tcp_flags |= TCP_SKB_CB(src)->tcp_flags;
TCP_SKB_CB(dst)->eor = TCP_SKB_CB(src)->eor;
tcp_skb_collapse_tstamp(dst, src);
tcp_unlink_write_queue(src, sk);
tcp_wmem_free_skb(sk, src);
}
/* Create a new MTU probe if we are ready. *MTUprobeisregularlyattemptingtoincreasethepathMTUby *deliberatelysendinglargerpackets.Thisdiscoversrouting *changesresultinginlargerpathMTUs. * *Returns0ifweshouldwaittoprobe(nocwndavailable), *1ifaprobewassent, *-1otherwise
*/ staticint tcp_mtu_probe(struct sock *sk)
{ struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb, *nskb, *next; struct net *net = sock_net(sk); int probe_size; int size_needed; int copy, len; int mss_now; int interval;
/* Not currently probing/verifying, *notinrecovery, *haveenoughcwnd,and *notSACKing(thevariableheadersthrowthingsoff)
*/ if (likely(!icsk->icsk_mtup.enabled ||
icsk->icsk_mtup.probe_size ||
inet_csk(sk)->icsk_ca_state != TCP_CA_Open ||
tcp_snd_cwnd(tp) < 11 ||
tp->rx_opt.num_sacks || tp->rx_opt.dsack)) return -1;
/* Use binary search for probe_size between tcp_mss_base, *andcurrentmss_clamp.if(search_high-search_low) *smallerthanathreshold,backofffromprobing.
*/
mss_now = tcp_current_mss(sk);
probe_size = tcp_mtu_to_mss(sk, (icsk->icsk_mtup.search_high +
icsk->icsk_mtup.search_low) >> 1);
size_needed = probe_size + (tp->reordering + 1) * tp->mss_cache;
interval = icsk->icsk_mtup.search_high - icsk->icsk_mtup.search_low; /* When misfortune happens, we are reprobing actively, *andthenreprobetimerhasexpired.Westickwithcurrent *probingprocessbynotresettingsearchrangetoitsorignal.
*/ if (probe_size > tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_high) ||
interval < READ_ONCE(net->ipv4.sysctl_tcp_probe_threshold)) { /* Check whether enough time has elaplased for *anotherroundofprobing.
*/
tcp_mtu_check_reprobe(sk); return -1;
}
/* Have enough data in the send queue to probe? */ if (tp->write_seq - tp->snd_nxt < size_needed) return -1;
if (tp->snd_wnd < size_needed) return -1; if (after(tp->snd_nxt + size_needed, tcp_wnd_end(tp))) return0;
/* Do we need to wait to drain cwnd? With none in flight, don't stall */ if (tcp_packets_in_flight(tp) + 2 > tcp_snd_cwnd(tp)) { if (!tcp_packets_in_flight(tp)) return -1; else return0;
}
if (!tcp_can_coalesce_send_queue_head(sk, probe_size)) return -1;
/* We're allowed to probe. Build it now. */
nskb = tcp_stream_alloc_skb(sk, GFP_ATOMIC, false); if (!nskb) return -1;
/* build the payload, and be prepared to abort if this fails. */ if (tcp_clone_payload(sk, nskb, probe_size)) {
tcp_skb_tsorted_anchor_cleanup(nskb);
consume_skb(nskb); return -1;
}
sk_wmem_queued_add(sk, nskb->truesize);
sk_mem_charge(sk, nskb->truesize);
if (len >= probe_size) break;
}
tcp_init_tso_segs(nskb, nskb->len);
/* We're ready to send. If this fails, the probe will *beresegmentedintomss-sizedpiecesbytcp_write_xmit().
*/ if (!tcp_transmit_skb(sk, nskb, 1, GFP_ATOMIC)) { /* Decrement cwnd here because we are sending
* effectively two packets. */
tcp_snd_cwnd_set(tp, tcp_snd_cwnd(tp) - 1);
tcp_event_new_data_sent(sk, nskb);
/* TSQ is based on skb truesize sum (sk_wmem_alloc), so we *approximateourneedsassumingan~100%skb->truesizeoverhead. *USEC_PER_SECisapproximatedby2^20. *do_div(extra_bytes,USEC_PER_SEC/2)isreplacedbyarightshift.
*/
extra_bytes >>= (20 - 1);
limit += extra_bytes;
} if (refcount_read(&sk->sk_wmem_alloc) > limit) { /* Always send skb if rtx queue is empty or has one skb. *NoneedtowaitforTXcompletiontocallusback, *aftersoftirqschedule. *ThishelpswhenTXcompletionsaredelayedtoomuch.
*/ if (tcp_rtx_queue_empty_or_single_skb(sk)) returnfalse;
set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags); /* It is possible TX completion already happened *beforewesetTSQ_THROTTLED,sowemust *testagainthecondition.
*/
smp_mb__after_atomic(); if (refcount_read(&sk->sk_wmem_alloc) > limit) returntrue;
} returnfalse;
}
staticvoid tcp_chrono_set(struct tcp_sock *tp, constenum tcp_chrono new)
{ const u32 now = tcp_jiffies32; enum tcp_chrono old = tp->chrono_type;
if (old > TCP_CHRONO_UNSPEC)
tp->chrono_stat[old - 1] += now - tp->chrono_start;
tp->chrono_start = now;
tp->chrono_type = new;
}
/* If there are multiple conditions worthy of tracking in a *chronographthenthehighestpriorityenumtakesprecedence *overtheotherconditions.Sothatifsomething"moreinteresting" *startshappening,stopthepreviouschronoandstartanewone.
*/ if (type > tp->chrono_type)
tcp_chrono_set(tp, type);
}
/* There are multiple conditions worthy of tracking in a *chronograph,sothatthehighestpriorityenumtakes *precedenceovertheotherconditions(seetcp_chrono_start). *Ifaconditionstops,weonlystopchronotrackingif *it'sthe"mostinteresting"orcurrentchronoweare *trackingandstartsbusychronoifwehavependingdata.
*/ if (tcp_rtx_and_write_queues_empty(sk))
tcp_chrono_set(tp, TCP_CHRONO_UNSPEC); elseif (type == tp->chrono_type)
tcp_chrono_set(tp, TCP_CHRONO_BUSY);
}
/* First skb in the write queue is smaller than ideal packet size. *Checkifwecanmovepayloadfromthesecondskbinthequeue.
*/ staticvoid tcp_grow_skb(struct sock *sk, struct sk_buff *skb, int amount)
{ struct sk_buff *next_skb = skb->next; unsignedint nlen;
if (!next_skb->len) { /* In case FIN is set, we need to update end_seq */
TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq;
tcp_eat_one_skb(sk, skb, next_skb);
}
}
/* This routine writes packets to the network. It advances the *send_head.Thishappensasincomingacksopenuptheremote *windowforus. * *LARGESENDnote:!tcp_urg_modeisoverkill,onlyframesbetween *snd_up-64k-mss..snd_upcannotbelarge.However,takinginto *accountrareuseofURG,thisisnotabigflaw. * *Sendatmostonepacketwhenpush_one>0.Temporarilyignore *cwndlimittoforceatmostonepacketoutwhenpush_one==2.
tcp_mstamp_refresh(tp); if (!push_one) { /* Do MTU probing. */
result = tcp_mtu_probe(sk); if (!result) { returnfalse;
} elseif (result > 0) {
sent_pkts = 1;
}
}
max_segs = tcp_tso_segs(sk, mss_now); while ((skb = tcp_send_head(sk))) { unsignedint limit; int missing_bytes;
if (unlikely(tp->repair) && tp->repair_queue == TCP_SEND_QUEUE) { /* "skb_mstamp_ns" is used as a start point for the retransmit timer */
tp->tcp_wstamp_ns = tp->tcp_clock_cache;
skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC);
list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue);
tcp_init_tso_segs(skb, mss_now); goto repair; /* Skip network transmission */
}
if (tcp_pacing_check(sk)) break;
cwnd_quota = tcp_cwnd_test(tp); if (!cwnd_quota) { if (push_one == 2) /* Force out a loss probe pkt. */
cwnd_quota = 1; else break;
}
cwnd_quota = min(cwnd_quota, max_segs);
missing_bytes = cwnd_quota * mss_now - skb->len; if (missing_bytes > 0)
tcp_grow_skb(sk, skb, missing_bytes);
tso_segs = tcp_set_skb_tso_segs(skb, mss_now);
if (unlikely(!tcp_snd_wnd_test(tp, skb, mss_now))) {
is_rwnd_limited = true; break;
}
if (tso_segs == 1) { if (unlikely(!tcp_nagle_test(tp, skb, mss_now,
(tcp_skb_is_last(sk, skb) ?
nonagle : TCP_NAGLE_PUSH)))) break;
} else { if (!push_one &&
tcp_tso_should_defer(sk, skb, &is_cwnd_limited,
&is_rwnd_limited, max_segs)) break;
}
/* Argh, we hit an empty skb(), presumably a thread *issleepinginsendmsg()/sk_stream_wait_memory(). *Wedonotwanttosendapure-ackpacketandhave *astrangelookingrtxqueuewithemptypacket(s).
*/ if (TCP_SKB_CB(skb)->end_seq == TCP_SKB_CB(skb)->seq) break;
if (unlikely(tcp_transmit_skb(sk, skb, 1, gfp))) break;
repair: /* Advance the send_head. This one is sent out. *Thiscallwillincrementpackets_out.
*/
tcp_event_new_data_sent(sk, skb);
if (likely(sent_pkts)) { if (tcp_in_cwnd_reduction(sk))
tp->prr_out += sent_pkts;
/* Send one loss probe per tail loss episode. */ if (push_one != 2)
tcp_schedule_loss_probe(sk, false); returnfalse;
} return !tp->packets_out && !tcp_write_queue_empty(sk);
}
/* If the RTO formula yields an earlier time, then use that time. */
rto_delta_us = advancing_rto ?
jiffies_to_usecs(inet_csk(sk)->icsk_rto) :
tcp_rto_delta_us(sk); /* How far in future is RTO? */ if (rto_delta_us > 0)
timeout = min_t(u32, timeout, usecs_to_jiffies(rto_delta_us));
/* Thanks to skb fast clones, we can detect if a prior transmit of *apacketisstillinaqdiscordriverqueue. *Inthiscase,thereisverylittlepointdoingaretransmit!
*/ staticbool skb_still_in_host_queue(struct sock *sk, conststruct sk_buff *skb)
{ if (unlikely(skb_fclone_busy(sk, skb))) {
set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
smp_mb__after_atomic(); if (skb_fclone_busy(sk, skb)) {
NET_INC_STATS(sock_net(sk),
LINUX_MIB_TCPSPURIOUS_RTX_HOSTQUEUES); returntrue;
}
} returnfalse;
}
/* When probe timeout (PTO) fires, try send a new segment if possible, else *retransmitthelastsegment.
*/ void tcp_send_loss_probe(struct sock *sk)
{ struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; int pcount; int mss = tcp_current_mss(sk);
/* At most one outstanding TLP */ if (tp->tlp_high_seq) goto rearm_timer;
if (WARN_ON(!skb || !tcp_skb_pcount(skb))) goto rearm_timer;
if (__tcp_retransmit_skb(sk, skb, 1)) goto rearm_timer;
tp->tlp_retrans = 1;
probe_sent: /* Record snd_nxt for loss detection. */
tp->tlp_high_seq = tp->snd_nxt;
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSPROBES); /* Reset s.t. tcp_rearm_rto will restart timer from now */
smp_store_release(&inet_csk(sk)->icsk_pending, 0);
rearm_timer:
tcp_rearm_rto(sk);
}
/* Push out any pending frames which were held back due to *TCP_CORKorattemptatcoalescingtinypackets. *Thesocketmustbelockedbythecaller.
*/ void __tcp_push_pending_frames(struct sock *sk, unsignedint cur_mss, int nonagle)
{ /* If we are closed, the bytes will have to remain here. *Intimeclosedownwillfinish,weemptythewritequeueand *allwillbehappy.
*/ if (unlikely(sk->sk_state == TCP_CLOSE)) return;
if (tcp_write_xmit(sk, cur_mss, nonagle, 0,
sk_gfp_mask(sk, GFP_ATOMIC)))
tcp_check_probe_timer(sk);
}
/* Send _single_ skb sitting at the send head. This function requires *truepushpendingframestosetupprobetimeretc.
*/ void tcp_push_one(struct sock *sk, unsignedint mss_now)
{ struct sk_buff *skb = tcp_send_head(sk);
if (unlikely(mss > full_space)) {
mss = full_space; if (mss <= 0) return0;
}
/* Only allow window shrink if the sysctl is enabled and we have *anon-zeroscalingfactorineffect.
*/ if (READ_ONCE(net->ipv4.sysctl_tcp_shrink_window) && tp->rx_opt.rcv_wscale) goto shrink_window_allowed;
/* do not allow window to shrink */
if (free_space < (full_space >> 1)) {
icsk->icsk_ack.quick = 0;
if (tcp_under_memory_pressure(sk))
tcp_adjust_rcv_ssthresh(sk);
/* free_space might become our new window, make sure we don't *increaseitduetowscale.
*/
free_space = round_down(free_space, 1 << tp->rx_opt.rcv_wscale);
/* if free space is less than mss estimate, or is below 1/16th *ofthemaximumallowed,trytomovetozero-window,else *tcp_clamp_window()willgrowrcvbufuptotcp_rmem[2],and *newincomingdataisdroppedduetomemorylimits. *Withlargewindow,msstesttriggerswaytoolateinorder *toannouncezerowindowintimebeforermemlimitkicksin.
*/ if (free_space < (allowed_space >> 4) || free_space < mss) return0;
}
if (free_space > tp->rcv_ssthresh)
free_space = tp->rcv_ssthresh;
/* Don't do rounding if we are using window scaling, since the *scaledwindowwillnotlineupwiththeMSSboundaryanyway.
*/ if (tp->rx_opt.rcv_wscale) {
window = free_space;
/* Advertise enough space so that it won't get scaled away. *Importcase:preventzerowindowannouncementif *1<<rcv_wscale>mss.
*/
window = ALIGN(window, (1 << tp->rx_opt.rcv_wscale));
} else {
window = tp->rcv_wnd; /* Get the largest window that is a nice multiple of mss. *Windowclampalreadyappliedabove. *Ifourcurrentwindowofferingiswithin1mssofthe *freespacewejustkeepit.Thispreventsthedivide *andmultiplyfromhappeningmostofthetime. *Wealsodon'tdoanywindowroundingwhenthefreespace *istoosmall.
*/ if (window <= free_space - mss || window > free_space)
window = rounddown(free_space, mss); elseif (mss == full_space &&
free_space > window + (full_space >> 1))
window = free_space;
}
return window;
shrink_window_allowed: /* new window should always be an exact multiple of scaling factor */
free_space = round_down(free_space, 1 << tp->rx_opt.rcv_wscale);
if (free_space < (full_space >> 1)) {
icsk->icsk_ack.quick = 0;
if (tcp_under_memory_pressure(sk))
tcp_adjust_rcv_ssthresh(sk);
/* if free space is too low, return a zero window */ if (free_space < (allowed_space >> 4) || free_space < mss ||
free_space < (1 << tp->rx_opt.rcv_wscale)) return0;
}
if (free_space > tp->rcv_ssthresh) {
free_space = tp->rcv_ssthresh; /* new window should always be an exact multiple of scaling factor * *Forthiscase,weALIGN"up"(increasefree_space)because *weknowfree_spaceisnotzerohere,ithasbeenreducedfrom *thememory-basedlimit,andrcv_ssthreshisnotahardlimit *(unlikesk_rcvbuf).
*/
free_space = ALIGN(free_space, (1 << tp->rx_opt.rcv_wscale));
}
if (next_skb_size && !tcp_skb_shift(skb, next_skb, 1, next_skb_size)) returnfalse;
tcp_highest_sack_replace(sk, next_skb, skb);
/* Update sequence range on original skb. */
TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq;
/* Merge over control information. This moves PSH/FIN etc. over */
TCP_SKB_CB(skb)->tcp_flags |= TCP_SKB_CB(next_skb)->tcp_flags;
/* All done, get rid of second SKB and account for it so *packetcountingdoesnotbreak.
*/
TCP_SKB_CB(skb)->sacked |= TCP_SKB_CB(next_skb)->sacked & TCPCB_EVER_RETRANS;
TCP_SKB_CB(skb)->eor = TCP_SKB_CB(next_skb)->eor;
/* changed transmit queue under us so clear hints */ if (next_skb == tp->retransmit_skb_hint)
tp->retransmit_skb_hint = skb;
/* Check if coalescing SKBs is legal. */ staticbool tcp_can_collapse(conststruct sock *sk, conststruct sk_buff *skb)
{ if (tcp_skb_pcount(skb) > 1) returnfalse; if (skb_cloned(skb)) returnfalse; if (!skb_frags_readable(skb)) returnfalse; /* Some heuristics for collapsing over SACK'd could be invented */ if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) returnfalse;
returntrue;
}
/* Collapse packets in the retransmit queue to make to create *lesspacketsonthewire.Thisisonlydoneonretransmission.
*/ staticvoid tcp_retrans_try_collapse(struct sock *sk, struct sk_buff *to, int space)
{ struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb = to, *tmp; bool first = true;
if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_retrans_collapse)) return; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN) return;
skb_rbtree_walk_from_safe(skb, tmp) { if (!tcp_can_collapse(sk, skb)) break;
if (!tcp_skb_can_collapse(to, skb)) break;
space -= skb->len;
if (first) {
first = false; continue;
}
if (space < 0) break;
if (after(TCP_SKB_CB(skb)->end_seq, tcp_wnd_end(tp))) break;
if (!tcp_collapse_retrans(sk, to)) break;
}
}
/* This retransmits one SKB. Policy decisions and retransmit queue *stateupdatesaredonebythecaller.Returnsnon-zeroifan *erroroccurredwhichpreventedthesend.
*/ int __tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb, int segs)
{ struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); unsignedint cur_mss; int diff, len, err; int avail_wnd;
/* Inconclusive MTU probe */ if (icsk->icsk_mtup.probe_size)
icsk->icsk_mtup.probe_size = 0;
if (skb_still_in_host_queue(sk, skb)) {
err = -EBUSY; goto out;
}
/* If receiver has shrunk his window, and skb is out of *newwindow,donotretransmitit.Theexceptionisthe *case,whenwindowisshrunktozero.Inthiscase *ourretransmitofonesegmentservesasazerowindowprobe.
*/ if (avail_wnd <= 0) { if (TCP_SKB_CB(skb)->seq != tp->snd_una) {
err = -EAGAIN; goto out;
}
avail_wnd = cur_mss;
}
len = cur_mss * segs; if (len > avail_wnd) {
len = rounddown(avail_wnd, cur_mss); if (!len)
len = avail_wnd;
} if (skb->len > len) { if (tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb, len,
cur_mss, GFP_ATOMIC)) {
err = -ENOMEM; /* We'll try again later. */ goto out;
}
} else { if (skb_unclone_keeptruesize(skb, GFP_ATOMIC)) {
err = -ENOMEM; goto out;
}
/* Update global and local TCP statistics. */
segs = tcp_skb_pcount(skb);
TCP_ADD_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS, segs); if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)
__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNRETRANS);
tp->total_retrans += segs;
tp->bytes_retrans += skb->len;
/* make sure skb->data is aligned on arches that require it *andcheckifack-trimming&collapsingextendedtheheadroom *beyondwhatcsum_startcancover.
*/ if (unlikely((NET_IP_ALIGN && ((unsignedlong)skb->data & 3)) ||
skb_headroom(skb) >= 0xFFFF)) { struct sk_buff *nskb;
if (BPF_SOCK_OPS_TEST_FLAG(tp, BPF_SOCK_OPS_RETRANS_CB_FLAG))
tcp_call_bpf_3arg(sk, BPF_SOCK_OPS_RETRANS_CB,
TCP_SKB_CB(skb)->seq, segs, err);
if (unlikely(err) && err != -EBUSY)
NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPRETRANSFAIL, segs);
/* To avoid taking spuriously low RTT samples based on a timestamp *foratransmitthatneverhappened,alwaysmarkEVER_RETRANS
*/
TCP_SKB_CB(skb)->sacked |= TCPCB_EVER_RETRANS;
} if (rearm_timer)
tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
inet_csk(sk)->icsk_rto, true);
}
/* We allow to exceed memory limits for FIN packets to expedite *connectionteardownand(memory)recovery. *Otherwisetcp_send_fin()couldbetemptedtoeitherdelayFIN *orevenbeforcedtocloseflowwithoutanyFIN. *Ingeneral,wewanttoallowoneskbpersockettoavoidhangs *withedgetriggerepoll()
*/ void sk_forced_mem_schedule(struct sock *sk, int size)
{ int delta, amt;
delta = size - sk->sk_forward_alloc; if (delta <= 0) return;
amt = sk_mem_pages(delta);
sk_forward_alloc_add(sk, amt << PAGE_SHIFT);
sk_memory_allocated_add(sk, amt);
if (mem_cgroup_sockets_enabled && sk->sk_memcg)
mem_cgroup_charge_skmem(sk->sk_memcg, amt,
gfp_memcg_charge() | __GFP_NOFAIL);
}
/* Send a FIN. The caller locks the socket for us. *WeshouldtrytosendaFINpacketreallyhard,buteventuallygiveup.
*/ void tcp_send_fin(struct sock *sk)
{ struct sk_buff *skb, *tskb, *tail = tcp_write_queue_tail(sk); struct tcp_sock *tp = tcp_sk(sk);
/* Optimization, tack on the FIN if we have one skb in write queue and *thisskbwasnotyetsent,orweareundermemorypressure. *Note:inthelattercase,FINpacketwillbesentafteratimeout, *asTCPstackthinksithasalreadybeentransmitted.
*/
tskb = tail; if (!tskb && tcp_under_memory_pressure(sk))
tskb = skb_rb_last(&sk->tcp_rtx_queue);
if (tskb) {
TCP_SKB_CB(tskb)->tcp_flags |= TCPHDR_FIN;
TCP_SKB_CB(tskb)->end_seq++;
tp->write_seq++; if (!tail) { /* This means tskb was already sent. *PretendweincludedtheFINonprevioustransmit. *Weneedtosettp->snd_nxttothevalueitwouldhave *ifFINhadbeensent.Thisisbecauseretransmitpath *doesnotchangetp->snd_nxt.
*/
WRITE_ONCE(tp->snd_nxt, tp->snd_nxt + 1); return;
}
} else {
skb = alloc_skb_fclone(MAX_TCP_HEADER,
sk_gfp_mask(sk, GFP_ATOMIC |
__GFP_NOWARN)); if (unlikely(!skb)) return;
INIT_LIST_HEAD(&skb->tcp_tsorted_anchor);
skb_reserve(skb, MAX_TCP_HEADER);
sk_forced_mem_schedule(sk, skb->truesize); /* FIN eats a sequence byte, write_seq advanced by tcp_queue_skb(). */
tcp_init_nondata_skb(skb, tp->write_seq,
TCPHDR_ACK | TCPHDR_FIN);
tcp_queue_skb(sk, skb);
}
__tcp_push_pending_frames(sk, tcp_current_mss(sk), TCP_NAGLE_OFF);
}
/* We get here when a process closes a file descriptor (either due to *anexplicitclose()orasabyproductofexit()'ing)andthere *wasunreaddatainthereceivequeue.Thisbehaviorisrecommended *byRFC2525,section2.17.-DaveM
*/ void tcp_send_active_reset(struct sock *sk, gfp_t priority, enum sk_rst_reason reason)
{ struct sk_buff *skb;
TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTRSTS);
/* NOTE: No TCP options attached and we never retransmit this. */
skb = alloc_skb(MAX_TCP_HEADER, priority); if (!skb) {
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED); return;
}
/* Reserve space for headers and prepare control bits. */
skb_reserve(skb, MAX_TCP_HEADER);
tcp_init_nondata_skb(skb, tcp_acceptable_seq(sk),
TCPHDR_ACK | TCPHDR_RST);
tcp_mstamp_refresh(tcp_sk(sk)); /* Send it off. */ if (tcp_transmit_skb(sk, skb, 0, priority))
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED);
/* skb of trace_tcp_send_reset() keeps the skb that caused RST, *skbhereisdifferenttothetroublesomeskb,souseNULL
*/
trace_tcp_send_reset(sk, NULL, reason);
}
/* Send a crossed SYN-ACK during socket establishment. *WARNING:Thisroutinemustonlybecalledwhenwehavealreadysent *aSYNpacketthatcrossedtheincomingSYNthatcausedthisroutine *togetcalled.Ifthisassumptionfailsthentheinitialrcv_wnd *andrcv_wscalevalueswillnotbecorrect.
*/ int tcp_send_synack(struct sock *sk)
{ struct sk_buff *skb;
skb = tcp_rtx_queue_head(sk); if (!skb || !(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
pr_err("%s: wrong queue state\n", __func__); return -EFAULT;
} if (!(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_ACK)) { if (skb_cloned(skb)) { struct sk_buff *nskb;
skb = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC); if (unlikely(!skb)) {
dst_release(dst); return NULL;
} /* Reserve space for headers. */
skb_reserve(skb, MAX_TCP_HEADER);
switch (synack_type) { case TCP_SYNACK_NORMAL:
skb_set_owner_edemux(skb, req_to_sk(req)); break; case TCP_SYNACK_COOKIE: /* Under synflood, we do not attach skb to a socket, *toavoidfalsesharing.
*/ break; case TCP_SYNACK_FASTOPEN: /* sk is a const pointer, because we want to express multiple *cpumightcallusconcurrently. *sk->sk_wmem_allocinanatomic,wecanpromotetorw.
*/
skb_set_owner_w(skb, (struct sock *)sk); break;
}
skb_dst_set(skb, dst);
mss = tcp_mss_clamp(tp, dst_metric_advmss(dst));
memset(&opts, 0, sizeof(opts));
now = tcp_clock_ns(); #ifdef CONFIG_SYN_COOKIES if (unlikely(synack_type == TCP_SYNACK_COOKIE && ireq->tstamp_ok))
skb_set_delivery_time(skb, cookie_init_timestamp(req, now),
SKB_CLOCK_MONOTONIC); else #endif
{
skb_set_delivery_time(skb, now, SKB_CLOCK_MONOTONIC); if (!tcp_rsk(req)->snt_synack) /* Timestamp first SYNACK */
tcp_rsk(req)->snt_synack = tcp_skb_timestamp_us(skb);
}
/* Do all connect socket setups that can be done AF independent. */ staticvoid tcp_connect_init(struct sock *sk)
{ conststruct dst_entry *dst = __sk_dst_get(sk); struct tcp_sock *tp = tcp_sk(sk);
__u8 rcv_wscale;
u32 rcv_wnd;
/* We'll fix this up when we get a response from the other end. *Seetcp_input.c:tcp_rcv_state_processcaseTCP_SYN_SENT.
*/
tp->tcp_header_len = sizeof(struct tcphdr); if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_timestamps))
tp->tcp_header_len += TCPOLEN_TSTAMP_ALIGNED;
tcp_ao_connect_init(sk);
/* If user gave his TCP_MAXSEG, record it to clamp */ if (tp->rx_opt.user_mss)
tp->rx_opt.mss_clamp = tp->rx_opt.user_mss;
tp->max_window = 0;
tcp_mtup_init(sk);
tcp_sync_mss(sk, dst_mtu(dst));
tcp_ca_dst_init(sk, dst);
if (!tp->window_clamp)
WRITE_ONCE(tp->window_clamp, dst_metric(dst, RTAX_WINDOW));
tp->advmss = tcp_mss_clamp(tp, dst_metric_advmss(dst));
tcp_initialize_rcv_mss(sk);
/* limit the window selection if the user enforce a smaller rx buffer */ if (sk->sk_userlocks & SOCK_RCVBUF_LOCK &&
(tp->window_clamp > tcp_full_space(sk) || tp->window_clamp == 0))
WRITE_ONCE(tp->window_clamp, tcp_full_space(sk));
/* Build and send a SYN with data and (cached) Fast Open cookie. However, *queueadata-onlypacketaftertheregularSYN,suchthatregularSYNs *areretransmittedontimeouts.AlsoiftheremoteSYN-ACKacknowledges *onlytheSYNsequence,thedataareretransmittedinthefirstACK. *Ifcookieisnotcachedorothererroroccurs,fallsbacktosenda *regularSYNwithFastOpencookierequestoption.
*/ staticint tcp_send_syn_data(struct sock *sk, struct sk_buff *syn)
{ struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct tcp_fastopen_request *fo = tp->fastopen_req; struct page_frag *pfrag = sk_page_frag(sk); struct sk_buff *syn_data; int space, err = 0;
tp->rx_opt.mss_clamp = tp->advmss; /* If MSS is not cached */ if (!tcp_fastopen_cookie_check(sk, &tp->rx_opt.mss_clamp, &fo->cookie)) goto fallback;
/* MSS for SYN-data is based on cached MSS and bounded by PMTU and *user-MSS.Reservemaximumoptionspaceformiddleboxesthatadd *privateTCPoptions.ThecostisreduceddataspaceinSYN:(
*/
tp->rx_opt.mss_clamp = tcp_mss_clamp(tp, tp->rx_opt.mss_clamp); /* Sync mss_cache after updating the mss_clamp */
tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
space = __tcp_mtu_to_mss(sk, icsk->icsk_pmtu_cookie) -
MAX_TCP_OPTION_SPACE;
space = min_t(size_t, space, fo->size);
if (space &&
!skb_page_frag_refill(min_t(size_t, space, PAGE_SIZE),
pfrag, sk->sk_allocation)) goto fallback;
syn_data = tcp_stream_alloc_skb(sk, sk->sk_allocation, false); if (!syn_data) goto fallback;
memcpy(syn_data->cb, syn->cb, sizeof(syn->cb)); if (space) {
space = min_t(size_t, space, pfrag->size - pfrag->offset);
space = tcp_wmem_schedule(sk, space);
} if (space) {
space = copy_page_from_iter(pfrag->page, pfrag->offset,
space, &fo->data->msg_iter); if (unlikely(!space)) {
tcp_skb_tsorted_anchor_cleanup(syn_data);
kfree_skb(syn_data); goto fallback;
}
skb_fill_page_desc(syn_data, 0, pfrag->page,
pfrag->offset, space);
page_ref_inc(pfrag->page);
pfrag->offset += space;
skb_len_add(syn_data, space);
skb_zcopy_set(syn_data, fo->uarg, NULL);
} /* No more data pending in inet_wait_for_connect() */ if (space == fo->size)
fo->data = NULL;
fo->copied = space;
tcp_connect_queue_skb(sk, syn_data); if (syn_data->len)
tcp_chrono_start(sk, TCP_CHRONO_BUSY);
/* Now full SYN+DATA was cloned and sent (or not), *removetheSYNfromtheoriginalskb(syn_data) *wekeepinwritequeueincaseofaretransmit,aswe *alsohavetheSYNpacket(withnodata)inthesamequeue.
*/
TCP_SKB_CB(syn_data)->seq++;
TCP_SKB_CB(syn_data)->tcp_flags = TCPHDR_ACK | TCPHDR_PSH; if (!err) {
tp->syn_data = (fo->copied > 0);
tcp_rbtree_insert(&sk->tcp_rtx_queue, syn_data);
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPORIGDATASENT); goto done;
}
/* data was not sent, put it in write_queue */
__skb_queue_tail(&sk->sk_write_queue, syn_data);
tp->packets_out -= tcp_skb_pcount(syn_data);
fallback: /* Send a regular SYN with Fast Open cookie request option */ if (fo->cookie.len > 0)
fo->cookie.len = 0;
err = tcp_transmit_skb(sk, syn, 1, sk->sk_allocation); if (err)
tp->syn_fastopen = 0;
done:
fo->cookie.len = -1; /* Exclude Fast Open option for SYN retries */ return err;
}
/* Build a SYN and send it off. */ int tcp_connect(struct sock *sk)
{ struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *buff; int err;
#ifdefined(CONFIG_TCP_MD5SIG) && defined(CONFIG_TCP_AO) /* Has to be checked late, after setting daddr/saddr/ops. *Returnerrorifthepeerhasbothamd5andatcp-aokey *configuredasthisisambiguous.
*/ if (unlikely(rcu_dereference_protected(tp->md5sig_info,
lockdep_sock_is_held(sk)))) { bool needs_ao = !!tp->af_specific->ao_lookup(sk, sk, -1, -1); bool needs_md5 = !!tp->af_specific->md5_lookup(sk, sk); struct tcp_ao_info *ao_info;
ao_info = rcu_dereference_check(tp->ao_info,
lockdep_sock_is_held(sk)); if (ao_info) { /* This is an extra check: tcp_ao_required() in *tcp_v{4,6}_parse_md5_keys()shouldpreventadding *md5keysonao_requiredsocket.
*/
needs_ao |= ao_info->ao_required;
WARN_ON_ONCE(ao_info->ao_required && needs_md5);
} if (needs_md5 && needs_ao) return -EKEYREJECTED;
/* If we have a matching md5 key and no matching tcp-ao key *thenfreeupao_infoifallocated.
*/ if (needs_md5) {
tcp_ao_destroy_sock(sk, false);
} elseif (needs_ao) {
tcp_clear_md5_list(sk);
kfree(rcu_replace_pointer(tp->md5sig_info, NULL,
lockdep_sock_is_held(sk)));
}
} #endif #ifdef CONFIG_TCP_AO if (unlikely(rcu_dereference_protected(tp->ao_info,
lockdep_sock_is_held(sk)))) { /* Don't allow connecting if ao is configured but no *matchingkeyisfound.
*/ if (!tp->af_specific->ao_lookup(sk, sk, -1, -1)) return -EKEYREJECTED;
} #endif
if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk)) return -EHOSTUNREACH; /* Routing failure or similar. */
tcp_connect_init(sk);
if (unlikely(tp->repair)) {
tcp_finish_connect(sk, NULL); return0;
}
buff = tcp_stream_alloc_skb(sk, sk->sk_allocation, true); if (unlikely(!buff)) return -ENOBUFS;
/* SYN eats a sequence byte, write_seq updated by *tcp_connect_queue_skb().
*/
tcp_init_nondata_skb(buff, tp->write_seq, TCPHDR_SYN);
tcp_mstamp_refresh(tp);
tp->retrans_stamp = tcp_time_stamp_ts(tp);
tcp_connect_queue_skb(sk, buff);
tcp_ecn_send_syn(sk, buff);
tcp_rbtree_insert(&sk->tcp_rtx_queue, buff);
/* Send off SYN; include data in Fast Open. */
err = tp->fastopen_req ? tcp_send_syn_data(sk, buff) :
tcp_transmit_skb(sk, buff, 1, sk->sk_allocation); if (err == -ECONNREFUSED) return err;
/* We change tp->snd_nxt after the tcp_transmit_skb() call *inordertomakethispacketgetcountedintcpOutSegs.
*/
WRITE_ONCE(tp->snd_nxt, tp->write_seq);
tp->pushed_seq = tp->write_seq;
buff = tcp_send_head(sk); if (unlikely(buff)) {
WRITE_ONCE(tp->snd_nxt, TCP_SKB_CB(buff)->seq);
tp->pushed_seq = TCP_SKB_CB(buff)->seq;
}
TCP_INC_STATS(sock_net(sk), TCP_MIB_ACTIVEOPENS);
/* Timer for repeating the SYN until an answer. */
tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
inet_csk(sk)->icsk_rto, false); return0;
}
EXPORT_SYMBOL(tcp_connect);
/* Send out a delayed ack, the caller does the policy checking *toseeifweshouldevenbehere.Seetcp_input.c:tcp_ack_snd_check() *fordetails.
*/ void tcp_send_delayed_ack(struct sock *sk)
{ struct inet_connection_sock *icsk = inet_csk(sk); int ato = icsk->icsk_ack.ato; unsignedlong timeout;
if (ato > TCP_DELACK_MIN) { conststruct tcp_sock *tp = tcp_sk(sk); int max_ato = HZ / 2;
if (inet_csk_in_pingpong_mode(sk) ||
(icsk->icsk_ack.pending & ICSK_ACK_PUSHED))
max_ato = TCP_DELACK_MAX;
/* Slow path, intersegment interval is "high". */
/* If some rtt estimate is known, use it to bound delayed ack. *Donotuseinet_csk(sk)->icsk_rtohere,useresultsofrttmeasurements *directly.
*/ if (tp->srtt_us) { int rtt = max_t(int, usecs_to_jiffies(tp->srtt_us >> 3),
TCP_DELACK_MIN);
if (rtt < max_ato)
max_ato = rtt;
}
ato = min(ato, max_ato);
}
ato = min_t(u32, ato, tcp_delack_max(sk));
/* Stay within the limit we were given */
timeout = jiffies + ato;
/* Use new timeout only if there wasn't a older one earlier. */ if (icsk->icsk_ack.pending & ICSK_ACK_TIMER) { /* If delack timer is about to expire, send ACK now. */ if (time_before_eq(icsk_delack_timeout(icsk), jiffies + (ato >> 2))) {
tcp_send_ack(sk); return;
}
/* This routine sends an ack and also updates the window. */ void __tcp_send_ack(struct sock *sk, u32 rcv_nxt, u16 flags)
{ struct sk_buff *buff;
/* If we have been reset, we may not send again. */ if (sk->sk_state == TCP_CLOSE) return;
/* We are not putting this on the write queue, so *tcp_transmit_skb()willsettheownershiptothis *sock.
*/
buff = alloc_skb(MAX_TCP_HEADER,
sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN)); if (unlikely(!buff)) { struct inet_connection_sock *icsk = inet_csk(sk); unsignedlong delay;
/* Reserve space for headers and prepare control bits. */
skb_reserve(buff, MAX_TCP_HEADER);
tcp_init_nondata_skb(buff, tcp_acceptable_seq(sk), TCPHDR_ACK | flags);
/* We do not want pure acks influencing TCP Small Queues or fq/pacing *toomuch. *SKB_TRUESIZE(max(1..66,MAX_TCP_HEADER))isunfortunately~784
*/
skb_set_tcp_pure_ack(buff);
/* Send it off, this clears delayed acks for us. */
__tcp_transmit_skb(sk, buff, 0, (__force gfp_t)0, rcv_nxt);
}
EXPORT_SYMBOL_GPL(__tcp_send_ack);
/* This routine sends a packet with an out of date sequence *number.Itassumestheotherendwilltrytoackit. * *Question:whatshouldwemakewhileurgentmode? *4.4BSDforcessendingsinglebyteofdata.Wecannotsend *outofwindowdata,becausewehaveSND.NXT==SND.MAX... * *Currentsolution:tosendTWOzero-lengthsegmentsinurgentmode: *oneiswithSEG.SEQ=SND.UNAtodeliverurgentpointer,anotheris *out-of-datewithSND.UNA-1toprobewindow.
*/ staticint tcp_xmit_probe_skb(struct sock *sk, int urgent, int mib)
{ struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb;
/* We don't queue it, tcp_transmit_skb() sets ownership. */
skb = alloc_skb(MAX_TCP_HEADER,
sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN)); if (!skb) return -1;
/* Reserve space for headers and set control bits. */
skb_reserve(skb, MAX_TCP_HEADER); /* Use a previous sequence. This should cause the other *endtosendanack.Don'tqueueorcloneSKB,just *sendit.
*/
tcp_init_nondata_skb(skb, tp->snd_una - !urgent, TCPHDR_ACK);
NET_INC_STATS(sock_net(sk), mib); return tcp_transmit_skb(sk, skb, 0, (__force gfp_t)0);
}
/* Called from setsockopt( ... TCP_REPAIR ) */ void tcp_send_window_probe(struct sock *sk)
{ if (sk->sk_state == TCP_ESTABLISHED) {
tcp_sk(sk)->snd_wl1 = tcp_sk(sk)->rcv_nxt - 1;
tcp_mstamp_refresh(tcp_sk(sk));
tcp_xmit_probe_skb(sk, 0, LINUX_MIB_TCPWINPROBE);
}
}
/* Initiate keepalive or window probe from timer. */ int tcp_write_wakeup(struct sock *sk, int mib)
{ struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb;
if (tp->packets_out || tcp_write_queue_empty(sk)) { /* Cancel probe timer, if it is not required. */
icsk->icsk_probes_out = 0;
icsk->icsk_backoff = 0;
icsk->icsk_probes_tstamp = 0; return;
}
icsk->icsk_probes_out++; if (err <= 0) { if (icsk->icsk_backoff < READ_ONCE(net->ipv4.sysctl_tcp_retries2))
icsk->icsk_backoff++;
timeout = tcp_probe0_when(sk, tcp_rto_max(sk));
} else { /* If packet was not sent due to local congestion, *Letsendersfightforlocalresourcesconservatively.
*/
timeout = TCP_RESOURCE_PROBE_INTERVAL;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.