1 /*
2 * INET An implementation of the TCP/IP protocol suite for the LINUX
3 * operating system. INET is implemented using the BSD Socket
4 * interface as the means of communication with the user level.
5 *
6 * Implementation of the Transmission Control Protocol(TCP).
7 *
8 * Version: $Id: tcp_input.c,v 1.243 2002/02/01 22:01:04 davem Exp $
9 *
10 * Authors: Ross Biro
11 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
12 * Mark Evans, <evansmp@uhura.aston.ac.uk>
13 * Corey Minyard <wf-rch!minyard@relay.EU.net>
14 * Florian La Roche, <flla@stud.uni-sb.de>
15 * Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
16 * Linus Torvalds, <torvalds@cs.helsinki.fi>
17 * Alan Cox, <gw4pts@gw4pts.ampr.org>
18 * Matthew Dillon, <dillon@apollo.west.oic.com>
19 * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
20 * Jorge Cwik, <jorge@laser.satlink.net>
21 */
22
23 /*
24 * Changes:
25 * Pedro Roque : Fast Retransmit/Recovery.
26 * Two receive queues.
27 * Retransmit queue handled by TCP.
28 * Better retransmit timer handling.
29 * New congestion avoidance.
30 * Header prediction.
31 * Variable renaming.
32 *
33 * Eric : Fast Retransmit.
34 * Randy Scott : MSS option defines.
35 * Eric Schenk : Fixes to slow start algorithm.
36 * Eric Schenk : Yet another double ACK bug.
37 * Eric Schenk : Delayed ACK bug fixes.
38 * Eric Schenk : Floyd style fast retrans war avoidance.
39 * David S. Miller : Don't allow zero congestion window.
40 * Eric Schenk : Fix retransmitter so that it sends
41 * next packet on ack of previous packet.
42 * Andi Kleen : Moved open_request checking here
43 * and process RSTs for open_requests.
44 * Andi Kleen : Better prune_queue, and other fixes.
45 * Andrey Savochkin: Fix RTT measurements in the presence of
46 * timestamps.
47 * Andrey Savochkin: Check sequence numbers correctly when
48 * removing SACKs due to in sequence incoming
49 * data segments.
50 * Andi Kleen: Make sure we never ack data there is not
51 * enough room for. Also make this condition
52 * a fatal error if it might still happen.
53 * Andi Kleen: Add tcp_measure_rcv_mss to make
54 * connections with MSS<min(MTU,ann. MSS)
55 * work without delayed acks.
56 * Andi Kleen: Process packets with PSH set in the
57 * fast path.
58 * J Hadi Salim: ECN support
59 * Andrei Gurtov,
60 * Pasi Sarolahti,
61 * Panu Kuhlberg: Experimental audit of TCP (re)transmission
62 * engine. Lots of bugs are found.
63 * Pasi Sarolahti: F-RTO for dealing with spurious RTOs
64 */
65
66 #include <linux/mm.h>
67 #include <linux/module.h>
68 #include <linux/sysctl.h>
69 #include <net/tcp.h>
70 #include <net/inet_common.h>
71 #include <linux/ipsec.h>
72 #include <asm/unaligned.h>
73 #include <net/netdma.h>
74
75 int sysctl_tcp_timestamps __read_mostly = 1;
76 int sysctl_tcp_window_scaling __read_mostly = 1;
77 int sysctl_tcp_sack __read_mostly = 1;
78 int sysctl_tcp_fack __read_mostly = 1;
79 int sysctl_tcp_reordering __read_mostly = TCP_FASTRETRANS_THRESH;
80 int sysctl_tcp_ecn __read_mostly;
81 int sysctl_tcp_dsack __read_mostly = 1;
82 int sysctl_tcp_app_win __read_mostly = 31;
83 int sysctl_tcp_adv_win_scale __read_mostly = 2;
84
85 int sysctl_tcp_stdurg __read_mostly;
86 int sysctl_tcp_rfc1337 __read_mostly;
87 int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
88 int sysctl_tcp_frto __read_mostly = 2;
89 int sysctl_tcp_frto_response __read_mostly;
90 int sysctl_tcp_nometrics_save __read_mostly;
91
92 int sysctl_tcp_moderate_rcvbuf __read_mostly = 1;
93 int sysctl_tcp_abc __read_mostly;
94
95 #define FLAG_DATA 0x01 /* Incoming frame contained data. */
96 #define FLAG_WIN_UPDATE 0x02 /* Incoming ACK was a window update. */
97 #define FLAG_DATA_ACKED 0x04 /* This ACK acknowledged new data. */
98 #define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted. */
99 #define FLAG_SYN_ACKED 0x10 /* This ACK acknowledged SYN. */
100 #define FLAG_DATA_SACKED 0x20 /* New SACK. */
101 #define FLAG_ECE 0x40 /* ECE in this ACK */
102 #define FLAG_DATA_LOST 0x80 /* SACK detected data lossage. */
103 #define FLAG_SLOWPATH 0x100 /* Do not skip RFC checks for window update.*/
104 #define FLAG_ONLY_ORIG_SACKED 0x200 /* SACKs only non-rexmit sent before RTO */
105 #define FLAG_SND_UNA_ADVANCED 0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
106 #define FLAG_DSACKING_ACK 0x800 /* SACK blocks contained D-SACK info */
107 #define FLAG_NONHEAD_RETRANS_ACKED 0x1000 /* Non-head rexmitted data was ACKed */
108 #define FLAG_SACK_RENEGING 0x2000 /* snd_una advanced to a sacked seq */
109
110 #define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED)
111 #define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
112 #define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE)
113 #define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED)
114 #define FLAG_ANY_PROGRESS (FLAG_FORWARD_PROGRESS|FLAG_SND_UNA_ADVANCED)
115
116 #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
117 #define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
118
119 /* Adapt the MSS value used to make delayed ack decision to the
120 * real world.
121 */
122 static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
123 {
124 struct inet_connection_sock *icsk = inet_csk(sk);
125 const unsigned int lss = icsk->icsk_ack.last_seg_size;
126 unsigned int len;
127
128 icsk->icsk_ack.last_seg_size = 0;
129
130 /* skb->len may jitter because of SACKs, even if peer
131 * sends good full-sized frames.
132 */
133 len = skb_shinfo(skb)->gso_size ? : skb->len;
134 if (len >= icsk->icsk_ack.rcv_mss) {
135 icsk->icsk_ack.rcv_mss = len;
136 } else {
137 /* Otherwise, we make more careful check taking into account,
138 * that SACKs block is variable.
139 *
140 * "len" is invariant segment length, including TCP header.
141 */
142 len += skb->data - skb_transport_header(skb);
143 if (len >= TCP_MIN_RCVMSS + sizeof(struct tcphdr) ||
144 /* If PSH is not set, packet should be
145 * full sized, provided peer TCP is not badly broken.
146 * This observation (if it is correct 8)) allows
147 * to handle super-low mtu links fairly.
148 */
149 (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
150 !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
151 /* Subtract also invariant (if peer is RFC compliant),
152 * tcp header plus fixed timestamp option length.
153 * Resulting "len" is MSS free of SACK jitter.
154 */
155 len -= tcp_sk(sk)->tcp_header_len;
156 icsk->icsk_ack.last_seg_size = len;
157 if (len == lss) {
158 icsk->icsk_ack.rcv_mss = len;
159 return;
160 }
161 }
162 if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
163 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
164 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
165 }
166 }
167
168 static void tcp_incr_quickack(struct sock *sk)
169 {
170 struct inet_connection_sock *icsk = inet_csk(sk);
171 unsigned quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
172
173 if (quickacks == 0)
174 quickacks = 2;
175 if (quickacks > icsk->icsk_ack.quick)
176 icsk->icsk_ack.quick = min(quickacks, TCP_MAX_QUICKACKS);
177 }
178
179 void tcp_enter_quickack_mode(struct sock *sk)
180 {
181 struct inet_connection_sock *icsk = inet_csk(sk);
182 tcp_incr_quickack(sk);
183 icsk->icsk_ack.pingpong = 0;
184 icsk->icsk_ack.ato = TCP_ATO_MIN;
185 }
186
187 /* Send ACKs quickly, if "quick" count is not exhausted
188 * and the session is not interactive.
189 */
190
191 static inline int tcp_in_quickack_mode(const struct sock *sk)
192 {
193 const struct inet_connection_sock *icsk = inet_csk(sk);
194 return icsk->icsk_ack.quick && !icsk->icsk_ack.pingpong;
195 }
196
197 static inline void TCP_ECN_queue_cwr(struct tcp_sock *tp)
198 {
199 if (tp->ecn_flags & TCP_ECN_OK)
200 tp->ecn_flags |= TCP_ECN_QUEUE_CWR;
201 }
202
203 static inline void TCP_ECN_accept_cwr(struct tcp_sock *tp, struct sk_buff *skb)
204 {
205 if (tcp_hdr(skb)->cwr)
206 tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
207 }
208
209 static inline void TCP_ECN_withdraw_cwr(struct tcp_sock *tp)
210 {
211 tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
212 }
213
214 static inline void TCP_ECN_check_ce(struct tcp_sock *tp, struct sk_buff *skb)
215 {
216 if (tp->ecn_flags & TCP_ECN_OK) {
217 if (INET_ECN_is_ce(TCP_SKB_CB(skb)->flags))
218 tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
219 /* Funny extension: if ECT is not set on a segment,
220 * it is surely retransmit. It is not in ECN RFC,
221 * but Linux follows this rule. */
222 else if (INET_ECN_is_not_ect((TCP_SKB_CB(skb)->flags)))
223 tcp_enter_quickack_mode((struct sock *)tp);
224 }
225 }
226
227 static inline void TCP_ECN_rcv_synack(struct tcp_sock *tp, struct tcphdr *th)
228 {
229 if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr))
230 tp->ecn_flags &= ~TCP_ECN_OK;
231 }
232
233 static inline void TCP_ECN_rcv_syn(struct tcp_sock *tp, struct tcphdr *th)
234 {
235 if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr))
236 tp->ecn_flags &= ~TCP_ECN_OK;
237 }
238
239 static inline int TCP_ECN_rcv_ecn_echo(struct tcp_sock *tp, struct tcphdr *th)
240 {
241 if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK))
242 return 1;
243 return 0;
244 }
245
246 /* Buffer size and advertised window tuning.
247 *
248 * 1. Tuning sk->sk_sndbuf, when connection enters established state.
249 */
250
251 static void tcp_fixup_sndbuf(struct sock *sk)
252 {
253 int sndmem = tcp_sk(sk)->rx_opt.mss_clamp + MAX_TCP_HEADER + 16 +
254 sizeof(struct sk_buff);
255
256 if (sk->sk_sndbuf < 3 * sndmem)
257 sk->sk_sndbuf = min(3 * sndmem, sysctl_tcp_wmem[2]);
258 }
259
260 /* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
261 *
262 * All tcp_full_space() is split to two parts: "network" buffer, allocated
263 * forward and advertised in receiver window (tp->rcv_wnd) and
264 * "application buffer", required to isolate scheduling/application
265 * latencies from network.
266 * window_clamp is maximal advertised window. It can be less than
267 * tcp_full_space(), in this case tcp_full_space() - window_clamp
268 * is reserved for "application" buffer. The less window_clamp is
269 * the smoother our behaviour from viewpoint of network, but the lower
270 * throughput and the higher sensitivity of the connection to losses. 8)
271 *
272 * rcv_ssthresh is more strict window_clamp used at "slow start"
273 * phase to predict further behaviour of this connection.
274 * It is used for two goals:
275 * - to enforce header prediction at sender, even when application
276 * requires some significant "application buffer". It is check #1.
277 * - to prevent pruning of receive queue because of misprediction
278 * of receiver window. Check #2.
279 *
280 * The scheme does not work when sender sends good segments opening
281 * window and then starts to feed us spaghetti. But it should work
282 * in common situations. Otherwise, we have to rely on queue collapsing.
283 */
284
285 /* Slow part of check#2. */
286 static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb)
287 {
288 struct tcp_sock *tp = tcp_sk(sk);
289 /* Optimize this! */
290 int truesize = tcp_win_from_space(skb->truesize) >> 1;
291 int window = tcp_win_from_space(sysctl_tcp_rmem[2]) >> 1;
292
293 while (tp->rcv_ssthresh <= window) {
294 if (truesize <= skb->len)
295 return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
296
297 truesize >>= 1;
298 window >>= 1;
299 }
300 return 0;
301 }
302
303 static void tcp_grow_window(struct sock *sk, struct sk_buff *skb)
304 {
305 struct tcp_sock *tp = tcp_sk(sk);
306
307 /* Check #1 */
308 if (tp->rcv_ssthresh < tp->window_clamp &&
309 (int)tp->rcv_ssthresh < tcp_space(sk) &&
310 !tcp_memory_pressure) {
311 int incr;
312
313 /* Check #2. Increase window, if skb with such overhead
314 * will fit to rcvbuf in future.
315 */
316 if (tcp_win_from_space(skb->truesize) <= skb->len)
317 incr = 2 * tp->advmss;
318 else
319 incr = __tcp_grow_window(sk, skb);
320
321 if (incr) {
322 tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr,
323 tp->window_clamp);
324 inet_csk(sk)->icsk_ack.quick |= 1;
325 }
326 }
327 }
328
329 /* 3. Tuning rcvbuf, when connection enters established state. */
330
331 static void tcp_fixup_rcvbuf(struct sock *sk)
332 {
333 struct tcp_sock *tp = tcp_sk(sk);
334 int rcvmem = tp->advmss + MAX_TCP_HEADER + 16 + sizeof(struct sk_buff);
335
336 /* Try to select rcvbuf so that 4 mss-sized segments
337 * will fit to window and corresponding skbs will fit to our rcvbuf.
338 * (was 3; 4 is minimum to allow fast retransmit to work.)
339 */
340 while (tcp_win_from_space(rcvmem) < tp->advmss)
341 rcvmem += 128;
342 if (sk->sk_rcvbuf < 4 * rcvmem)
343 sk->sk_rcvbuf = min(4 * rcvmem, sysctl_tcp_rmem[2]);
344 }
345
346 /* 4. Try to fixup all. It is made immediately after connection enters
347 * established state.
348 */
349 static void tcp_init_buffer_space(struct sock *sk)
350 {
351 struct tcp_sock *tp = tcp_sk(sk);
352 int maxwin;
353
354 if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK))
355 tcp_fixup_rcvbuf(sk);
356 if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
357 tcp_fixup_sndbuf(sk);
358
359 tp->rcvq_space.space = tp->rcv_wnd;
360
361 maxwin = tcp_full_space(sk);
362
363 if (tp->window_clamp >= maxwin) {
364 tp->window_clamp = maxwin;
365
366 if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss)
367 tp->window_clamp = max(maxwin -
368 (maxwin >> sysctl_tcp_app_win),
369 4 * tp->advmss);
370 }
371
372 /* Force reservation of one segment. */
373 if (sysctl_tcp_app_win &&
374 tp->window_clamp > 2 * tp->advmss &&
375 tp->window_clamp + tp->advmss > maxwin)
376 tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
377
378 tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
379 tp->snd_cwnd_stamp = tcp_time_stamp;
380 }
381
382 /* 5. Recalculate window clamp after socket hit its memory bounds. */
383 static void tcp_clamp_window(struct sock *sk)
384 {
385 struct tcp_sock *tp = tcp_sk(sk);
386 struct inet_connection_sock *icsk = inet_csk(sk);
387
388 icsk->icsk_ack.quick = 0;
389
390 if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] &&
391 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
392 !tcp_memory_pressure &&
393 atomic_read(&tcp_memory_allocated) < sysctl_tcp_mem[0]) {
394 sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc),
395 sysctl_tcp_rmem[2]);
396 }
397 if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
398 tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
399 }
400
401 /* Initialize RCV_MSS value.
402 * RCV_MSS is an our guess about MSS used by the peer.
403 * We haven't any direct information about the MSS.
404 * It's better to underestimate the RCV_MSS rather than overestimate.
405 * Overestimations make us ACKing less frequently than needed.
406 * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
407 */
408 void tcp_initialize_rcv_mss(struct sock *sk)
409 {
410 struct tcp_sock *tp = tcp_sk(sk);
411 unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
412
413 hint = min(hint, tp->rcv_wnd / 2);
414 hint = min(hint, TCP_MIN_RCVMSS);
415 hint = max(hint, TCP_MIN_MSS);
416
417 inet_csk(sk)->icsk_ack.rcv_mss = hint;
418 }
419
420 /* Receiver "autotuning" code.
421 *
422 * The algorithm for RTT estimation w/o timestamps is based on
423 * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
424 * <http://www.lanl.gov/radiant/website/pubs/drs/lacsi2001.ps>
425 *
426 * More detail on this code can be found at
427 * <http://www.psc.edu/~jheffner/senior_thesis.ps>,
428 * though this reference is out of date. A new paper
429 * is pending.
430 */
431 static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
432 {
433 u32 new_sample = tp->rcv_rtt_est.rtt;
434 long m = sample;
435
436 if (m == 0)
437 m = 1;
438
439 if (new_sample != 0) {
440 /* If we sample in larger samples in the non-timestamp
441 * case, we could grossly overestimate the RTT especially
442 * with chatty applications or bulk transfer apps which
443 * are stalled on filesystem I/O.
444 *
445 * Also, since we are only going for a minimum in the
446 * non-timestamp case, we do not smooth things out
447 * else with timestamps disabled convergence takes too
448 * long.
449 */
450 if (!win_dep) {
451 m -= (new_sample >> 3);
452 new_sample += m;
453 } else if (m < new_sample)
454 new_sample = m << 3;
455 } else {
456 /* No previous measure. */
457 new_sample = m << 3;
458 }
459
460 if (tp->rcv_rtt_est.rtt != new_sample)
461 tp->rcv_rtt_est.rtt = new_sample;
462 }
463
464 static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
465 {
466 if (tp->rcv_rtt_est.time == 0)
467 goto new_measure;
468 if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
469 return;
470 tcp_rcv_rtt_update(tp, jiffies - tp->rcv_rtt_est.time, 1);
471
472 new_measure:
473 tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
474 tp->rcv_rtt_est.time = tcp_time_stamp;
475 }
476
477 static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
478 const struct sk_buff *skb)
479 {
480 struct tcp_sock *tp = tcp_sk(sk);
481 if (tp->rx_opt.rcv_tsecr &&
482 (TCP_SKB_CB(skb)->end_seq -
483 TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss))
484 tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rx_opt.rcv_tsecr, 0);
485 }
486
487 /*
488 * This function should be called every time data is copied to user space.
489 * It calculates the appropriate TCP receive buffer space.
490 */
491 void tcp_rcv_space_adjust(struct sock *sk)
492 {
493 struct tcp_sock *tp = tcp_sk(sk);
494 int time;
495 int space;
496
497 if (tp->rcvq_space.time == 0)
498 goto new_measure;
499
500 time = tcp_time_stamp - tp->rcvq_space.time;
501 if (time < (tp->rcv_rtt_est.rtt >> 3) || tp->rcv_rtt_est.rtt == 0)
502 return;
503
504 space = 2 * (tp->copied_seq - tp->rcvq_space.seq);
505
506 space = max(tp->rcvq_space.space, space);
507
508 if (tp->rcvq_space.space != space) {
509 int rcvmem;
510
511 tp->rcvq_space.space = space;
512
513 if (sysctl_tcp_moderate_rcvbuf &&
514 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
515 int new_clamp = space;
516
517 /* Receive space grows, normalize in order to
518 * take into account packet headers and sk_buff
519 * structure overhead.
520 */
521 space /= tp->advmss;
522 if (!space)
523 space = 1;
524 rcvmem = (tp->advmss + MAX_TCP_HEADER +
525 16 + sizeof(struct sk_buff));
526 while (tcp_win_from_space(rcvmem) < tp->advmss)
527 rcvmem += 128;
528 space *= rcvmem;
529 space = min(space, sysctl_tcp_rmem[2]);
530 if (space > sk->sk_rcvbuf) {
531 sk->sk_rcvbuf = space;
532
533 /* Make the window clamp follow along. */
534 tp->window_clamp = new_clamp;
535 }
536 }
537 }
538
539 new_measure:
540 tp->rcvq_space.seq = tp->copied_seq;
541 tp->rcvq_space.time = tcp_time_stamp;
542 }
543
544 /* There is something which you must keep in mind when you analyze the
545 * behavior of the tp->ato delayed ack timeout interval. When a
546 * connection starts up, we want to ack as quickly as possible. The
547 * problem is that "good" TCP's do slow start at the beginning of data
548 * transmission. The means that until we send the first few ACK's the
549 * sender will sit on his end and only queue most of his data, because
550 * he can only send snd_cwnd unacked packets at any given time. For
551 * each ACK we send, he increments snd_cwnd and transmits more of his
552 * queue. -DaveM
553 */
554 static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
555 {
556 struct tcp_sock *tp = tcp_sk(sk);
557 struct inet_connection_sock *icsk = inet_csk(sk);
558 u32 now;
559
560 inet_csk_schedule_ack(sk);
561
562 tcp_measure_rcv_mss(sk, skb);
563
564 tcp_rcv_rtt_measure(tp);
565
566 now = tcp_time_stamp;
567
568 if (!icsk->icsk_ack.ato) {
569 /* The _first_ data packet received, initialize
570 * delayed ACK engine.
571 */
572 tcp_incr_quickack(sk);
573 icsk->icsk_ack.ato = TCP_ATO_MIN;
574 } else {
575 int m = now - icsk->icsk_ack.lrcvtime;
576
577 if (m <= TCP_ATO_MIN / 2) {
578 /* The fastest case is the first. */
579 icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
580 } else if (m < icsk->icsk_ack.ato) {
581 icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
582 if (icsk->icsk_ack.ato > icsk->icsk_rto)
583 icsk->icsk_ack.ato = icsk->icsk_rto;
584 } else if (m > icsk->icsk_rto) {
585 /* Too long gap. Apparently sender failed to
586 * restart window, so that we send ACKs quickly.
587 */
588 tcp_incr_quickack(sk);
589 sk_mem_reclaim(sk);
590 }
591 }
592 icsk->icsk_ack.lrcvtime = now;
593
594 TCP_ECN_check_ce(tp, skb);
595
596 if (skb->len >= 128)
597 tcp_grow_window(sk, skb);
598 }
599
600 static u32 tcp_rto_min(struct sock *sk)
601 {
602 struct dst_entry *dst = __sk_dst_get(sk);
603 u32 rto_min = TCP_RTO_MIN;
604
605 if (dst && dst_metric_locked(dst, RTAX_RTO_MIN))
606 rto_min = dst->metrics[RTAX_RTO_MIN - 1];
607 return rto_min;
608 }
609
610 /* Called to compute a smoothed rtt estimate. The data fed to this
611 * routine either comes from timestamps, or from segments that were
612 * known _not_ to have been retransmitted [see Karn/Partridge
613 * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
614 * piece by Van Jacobson.
615 * NOTE: the next three routines used to be one big routine.
616 * To save cycles in the RFC 1323 implementation it was better to break
617 * it up into three procedures. -- erics
618 */
619 static void tcp_rtt_estimator(struct sock *sk, const __u32 mrtt)
620 {
621 struct tcp_sock *tp = tcp_sk(sk);
622 long m = mrtt; /* RTT */
623
624 /* The following amusing code comes from Jacobson's
625 * article in SIGCOMM '88. Note that rtt and mdev
626 * are scaled versions of rtt and mean deviation.
627 * This is designed to be as fast as possible
628 * m stands for "measurement".
629 *
630 * On a 1990 paper the rto value is changed to:
631 * RTO = rtt + 4 * mdev
632 *
633 * Funny. This algorithm seems to be very broken.
634 * These formulae increase RTO, when it should be decreased, increase
635 * too slowly, when it should be increased quickly, decrease too quickly
636 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
637 * does not matter how to _calculate_ it. Seems, it was trap
638 * that VJ failed to avoid. 8)
639 */
640 if (m == 0)
641 m = 1;
642 if (tp->srtt != 0) {
643 m -= (tp->srtt >> 3); /* m is now error in rtt est */
644 tp->srtt += m; /* rtt = 7/8 rtt + 1/8 new */
645 if (m < 0) {
646 m = -m; /* m is now abs(error) */
647 m -= (tp->mdev >> 2); /* similar update on mdev */
648 /* This is similar to one of Eifel findings.
649 * Eifel blocks mdev updates when rtt decreases.
650 * This solution is a bit different: we use finer gain
651 * for mdev in this case (alpha*beta).
652 * Like Eifel it also prevents growth of rto,
653 * but also it limits too fast rto decreases,
654 * happening in pure Eifel.
655 */
656 if (m > 0)
657 m >>= 3;
658 } else {
659 m -= (tp->mdev >> 2); /* similar update on mdev */
660 }
661 tp->mdev += m; /* mdev = 3/4 mdev + 1/4 new */
662 if (tp->mdev > tp->mdev_max) {
663 tp->mdev_max = tp->mdev;
664 if (tp->mdev_max > tp->rttvar)
665 tp->rttvar = tp->mdev_max;
666 }
667 if (after(tp->snd_una, tp->rtt_seq)) {
668 if (tp->mdev_max < tp->rttvar)
669 tp->rttvar -= (tp->rttvar - tp->mdev_max) >> 2;
670 tp->rtt_seq = tp->snd_nxt;
671 tp->mdev_max = tcp_rto_min(sk);
672 }
673 } else {
674 /* no previous measure. */
675 tp->srtt = m << 3; /* take the measured time to be rtt */
676 tp->mdev = m << 1; /* make sure rto = 3*rtt */
677 tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk));
678 tp->rtt_seq = tp->snd_nxt;
679 }
680 }
681
682 /* Calculate rto without backoff. This is the second half of Van Jacobson's
683 * routine referred to above.
684 */
685 static inline void tcp_set_rto(struct sock *sk)
686 {
687 const struct tcp_sock *tp = tcp_sk(sk);
688 /* Old crap is replaced with new one. 8)
689 *
690 * More seriously:
691 * 1. If rtt variance happened to be less 50msec, it is hallucination.
692 * It cannot be less due to utterly erratic ACK generation made
693 * at least by solaris and freebsd. "Erratic ACKs" has _nothing_
694 * to do with delayed acks, because at cwnd>2 true delack timeout
695 * is invisible. Actually, Linux-2.4 also generates erratic
696 * ACKs in some circumstances.
697 */
698 inet_csk(sk)->icsk_rto = (tp->srtt >> 3) + tp->rttvar;
699
700 /* 2. Fixups made earlier cannot be right.
701 * If we do not estimate RTO correctly without them,
702 * all the algo is pure shit and should be replaced
703 * with correct one. It is exactly, which we pretend to do.
704 */
705 }
706
707 /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
708 * guarantees that rto is higher.
709 */
710 static inline void tcp_bound_rto(struct sock *sk)
711 {
712 if (inet_csk(sk)->icsk_rto > TCP_RTO_MAX)
713 inet_csk(sk)->icsk_rto = TCP_RTO_MAX;
714 }
715
716 /* Save metrics learned by this TCP session.
717 This function is called only, when TCP finishes successfully
718 i.e. when it enters TIME-WAIT or goes from LAST-ACK to CLOSE.
719 */
720 void tcp_update_metrics(struct sock *sk)
721 {
722 struct tcp_sock *tp = tcp_sk(sk);
723 struct dst_entry *dst = __sk_dst_get(sk);
724
725 if (sysctl_tcp_nometrics_save)
726 return;
727
728 dst_confirm(dst);
729
730 if (dst && (dst->flags & DST_HOST)) {
731 const struct inet_connection_sock *icsk = inet_csk(sk);
732 int m;
733
734 if (icsk->icsk_backoff || !tp->srtt) {
735 /* This session failed to estimate rtt. Why?
736 * Probably, no packets returned in time.
737 * Reset our results.
738 */
739 if (!(dst_metric_locked(dst, RTAX_RTT)))
740 dst->metrics[RTAX_RTT - 1] = 0;
741 return;
742 }
743
744 m = dst_metric(dst, RTAX_RTT) - tp->srtt;
745
746 /* If newly calculated rtt larger than stored one,
747 * store new one. Otherwise, use EWMA. Remember,
748 * rtt overestimation is always better than underestimation.
749 */
750 if (!(dst_metric_locked(dst, RTAX_RTT))) {
751 if (m <= 0)
752 dst->metrics[RTAX_RTT - 1] = tp->srtt;
753 else
754 dst->metrics[RTAX_RTT - 1] -= (m >> 3);
755 }
756
757 if (!(dst_metric_locked(dst, RTAX_RTTVAR))) {
758 if (m < 0)
759 m = -m;
760
761 /* Scale deviation to rttvar fixed point */
762 m >>= 1;
763 if (m < tp->mdev)
764 m = tp->mdev;
765
766 if (m >= dst_metric(dst, RTAX_RTTVAR))
767 dst->metrics[RTAX_RTTVAR - 1] = m;
768 else
769 dst->metrics[RTAX_RTTVAR-1] -=
770 (dst->metrics[RTAX_RTTVAR-1] - m)>>2;
771 }
772
773 if (tp->snd_ssthresh >= 0xFFFF) {
774 /* Slow start still did not finish. */
775 if (dst_metric(dst, RTAX_SSTHRESH) &&
776 !dst_metric_locked(dst, RTAX_SSTHRESH) &&
777 (tp->snd_cwnd >> 1) > dst_metric(dst, RTAX_SSTHRESH))
778 dst->metrics[RTAX_SSTHRESH-1] = tp->snd_cwnd >> 1;
779 if (!dst_metric_locked(dst, RTAX_CWND) &&
780 tp->snd_cwnd > dst_metric(dst, RTAX_CWND))
781 dst->metrics[RTAX_CWND - 1] = tp->snd_cwnd;
782 } else if (tp->snd_cwnd > tp->snd_ssthresh &&
783 icsk->icsk_ca_state == TCP_CA_Open) {
784 /* Cong. avoidance phase, cwnd is reliable. */
785 if (!dst_metric_locked(dst, RTAX_SSTHRESH))
786 dst->metrics[RTAX_SSTHRESH-1] =
787 max(tp->snd_cwnd >> 1, tp->snd_ssthresh);
788 if (!dst_metric_locked(dst, RTAX_CWND))
789 dst->metrics[RTAX_CWND-1] = (dst->metrics[RTAX_CWND-1] + tp->snd_cwnd) >> 1;
790 } else {
791 /* Else slow start did not finish, cwnd is non-sense,
792 ssthresh may be also invalid.
793 */
794 if (!dst_metric_locked(dst, RTAX_CWND))
795 dst->metrics[RTAX_CWND-1] = (dst->metrics[RTAX_CWND-1] + tp->snd_ssthresh) >> 1;
796 if (dst->metrics[RTAX_SSTHRESH-1] &&
797 !dst_metric_locked(dst, RTAX_SSTHRESH) &&
798 tp->snd_ssthresh > dst->metrics[RTAX_SSTHRESH-1])
799 dst->metrics[RTAX_SSTHRESH-1] = tp->snd_ssthresh;
800 }
801
802 if (!dst_metric_locked(dst, RTAX_REORDERING)) {
803 if (dst->metrics[RTAX_REORDERING-1] < tp->reordering &&
804 tp->reordering != sysctl_tcp_reordering)
805 dst->metrics[RTAX_REORDERING-1] = tp->reordering;
806 }
807 }
808 }
809
810 /* Numbers are taken from RFC3390.
811 *
812 * John Heffner states:
813 *
814 * The RFC specifies a window of no more than 4380 bytes
815 * unless 2*MSS > 4380. Reading the pseudocode in the RFC
816 * is a bit misleading because they use a clamp at 4380 bytes
817 * rather than use a multiplier in the relevant range.
818 */
819 __u32 tcp_init_cwnd(struct tcp_sock *tp, struct dst_entry *dst)
820 {
821 __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
822
823 if (!cwnd) {
824 if (tp->mss_cache > 1460)
825 cwnd = 2;
826 else
827 cwnd = (tp->mss_cache > 1095) ? 3 : 4;
828 }
829 return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
830 }
831
832 /* Set slow start threshold and cwnd not falling to slow start */
833 void tcp_enter_cwr(struct sock *sk, const int set_ssthresh)
834 {
835 struct tcp_sock *tp = tcp_sk(sk);
836 const struct inet_connection_sock *icsk = inet_csk(sk);
837
838 tp->prior_ssthresh = 0;
839 tp->bytes_acked = 0;
840 if (icsk->icsk_ca_state < TCP_CA_CWR) {
841 tp->undo_marker = 0;
842 if (set_ssthresh)
843 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
844 tp->snd_cwnd = min(tp->snd_cwnd,
845 tcp_packets_in_flight(tp) + 1U);
846 tp->snd_cwnd_cnt = 0;
847 tp->high_seq = tp->snd_nxt;
848 tp->snd_cwnd_stamp = tcp_time_stamp;
849 TCP_ECN_queue_cwr(tp);
850
851 tcp_set_ca_state(sk, TCP_CA_CWR);
852 }
853 }
854
855 /*
856 * Packet counting of FACK is based on in-order assumptions, therefore TCP
857 * disables it when reordering is detected
858 */
859 static void tcp_disable_fack(struct tcp_sock *tp)
860 {
861 /* RFC3517 uses different metric in lost marker => reset on change */
862 if (tcp_is_fack(tp))
863 tp->lost_skb_hint = NULL;
864 tp->rx_opt.sack_ok &= ~2;
865 }
866
867 /* Take a notice that peer is sending D-SACKs */
868 static void tcp_dsack_seen(struct tcp_sock *tp)
869 {
870 tp->rx_opt.sack_ok |= 4;
871 }
872
873 /* Initialize metrics on socket. */
874
875 static void tcp_init_metrics(struct sock *sk)
876 {
877 struct tcp_sock *tp = tcp_sk(sk);
878 struct dst_entry *dst = __sk_dst_get(sk);
879
880 if (dst == NULL)
881 goto reset;
882
883 dst_confirm(dst);
884
885 if (dst_metric_locked(dst, RTAX_CWND))
886 tp->snd_cwnd_clamp = dst_metric(dst, RTAX_CWND);
887 if (dst_metric(dst, RTAX_SSTHRESH)) {
888 tp->snd_ssthresh = dst_metric(dst, RTAX_SSTHRESH);
889 if (tp->snd_ssthresh > tp->snd_cwnd_clamp)
890 tp->snd_ssthresh = tp->snd_cwnd_clamp;
891 }
892 if (dst_metric(dst, RTAX_REORDERING) &&
893 tp->reordering != dst_metric(dst, RTAX_REORDERING)) {
894 tcp_disable_fack(tp);
895 tp->reordering = dst_metric(dst, RTAX_REORDERING);
896 }
897
898 if (dst_metric(dst, RTAX_RTT) == 0)
899 goto reset;
900
901 if (!tp->srtt && dst_metric(dst, RTAX_RTT) < (TCP_TIMEOUT_INIT << 3))
902 goto reset;
903
904 /* Initial rtt is determined from SYN,SYN-ACK.
905 * The segment is small and rtt may appear much
906 * less than real one. Use per-dst memory
907 * to make it more realistic.
908 *
909 * A bit of theory. RTT is time passed after "normal" sized packet
910 * is sent until it is ACKed. In normal circumstances sending small
911 * packets force peer to delay ACKs and calculation is correct too.
912 * The algorithm is adaptive and, provided we follow specs, it
913 * NEVER underestimate RTT. BUT! If peer tries to make some clever
914 * tricks sort of "quick acks" for time long enough to decrease RTT
915 * to low value, and then abruptly stops to do it and starts to delay
916 * ACKs, wait for troubles.
917 */
918 if (dst_metric(dst, RTAX_RTT) > tp->srtt) {
919 tp->srtt = dst_metric(dst, RTAX_RTT);
920 tp->rtt_seq = tp->snd_nxt;
921 }
922 if (dst_metric(dst, RTAX_RTTVAR) > tp->mdev) {
923 tp->mdev = dst_metric(dst, RTAX_RTTVAR);
924 tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk));
925 }
926 tcp_set_rto(sk);
927 tcp_bound_rto(sk);
928 if (inet_csk(sk)->icsk_rto < TCP_TIMEOUT_INIT && !tp->rx_opt.saw_tstamp)
929 goto reset;
930 tp->snd_cwnd = tcp_init_cwnd(tp, dst);
931 tp->snd_cwnd_stamp = tcp_time_stamp;
932 return;
933
934 reset:
935 /* Play conservative. If timestamps are not
936 * supported, TCP will fail to recalculate correct
937 * rtt, if initial rto is too small. FORGET ALL AND RESET!
938 */
939 if (!tp->rx_opt.saw_tstamp && tp->srtt) {
940 tp->srtt = 0;
941 tp->mdev = tp->mdev_max = tp->rttvar = TCP_TIMEOUT_INIT;
942 inet_csk(sk)->icsk_rto = TCP_TIMEOUT_INIT;
943 }
944 }
945
946 static void tcp_update_reordering(struct sock *sk, const int metric,
947 const int ts)
948 {
949 struct tcp_sock *tp = tcp_sk(sk);
950 if (metric > tp->reordering) {
951 tp->reordering = min(TCP_MAX_REORDERING, metric);
952
953 /* This exciting event is worth to be remembered. 8) */
954 if (ts)
955 NET_INC_STATS_BH(LINUX_MIB_TCPTSREORDER);
956 else if (tcp_is_reno(tp))
957 NET_INC_STATS_BH(LINUX_MIB_TCPRENOREORDER);
958 else if (tcp_is_fack(tp))
959 NET_INC_STATS_BH(LINUX_MIB_TCPFACKREORDER);
960 else
961 NET_INC_STATS_BH(LINUX_MIB_TCPSACKREORDER);
962 #if FASTRETRANS_DEBUG > 1
963 printk(KERN_DEBUG "Disorder%d %d %u f%u s%u rr%d\n",
964 tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
965 tp->reordering,
966 tp->fackets_out,
967 tp->sacked_out,
968 tp->undo_marker ? tp->undo_retrans : 0);
969 #endif
970 tcp_disable_fack(tp);
971 }
972 }
973
974 /* This procedure tags the retransmission queue when SACKs arrive.
975 *
976 * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
977 * Packets in queue with these bits set are counted in variables
978 * sacked_out, retrans_out and lost_out, correspondingly.
979 *
980 * Valid combinations are:
981 * Tag InFlight Description
982 * 0 1 - orig segment is in flight.
983 * S 0 - nothing flies, orig reached receiver.
984 * L 0 - nothing flies, orig lost by net.
985 * R 2 - both orig and retransmit are in flight.
986 * L|R 1 - orig is lost, retransmit is in flight.
987 * S|R 1 - orig reached receiver, retrans is still in flight.
988 * (L|S|R is logically valid, it could occur when L|R is sacked,
989 * but it is equivalent to plain S and code short-curcuits it to S.
990 * L|S is logically invalid, it would mean -1 packet in flight 8))
991 *
992 * These 6 states form finite state machine, controlled by the following events:
993 * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
994 * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
995 * 3. Loss detection event of one of three flavors:
996 * A. Scoreboard estimator decided the packet is lost.
997 * A'. Reno "three dupacks" marks head of queue lost.
998 * A''. Its FACK modfication, head until snd.fack is lost.
999 * B. SACK arrives sacking data transmitted after never retransmitted
1000 * hole was sent out.
1001 * C. SACK arrives sacking SND.NXT at the moment, when the
1002 * segment was retransmitted.
1003 * 4. D-SACK added new rule: D-SACK changes any tag to S.
1004 *
1005 * It is pleasant to note, that state diagram turns out to be commutative,
1006 * so that we are allowed not to be bothered by order of our actions,
1007 * when multiple events arrive simultaneously. (see the function below).
1008 *
1009 * Reordering detection.
1010 * --------------------
1011 * Reordering metric is maximal distance, which a packet can be displaced
1012 * in packet stream. With SACKs we can estimate it:
1013 *
1014 * 1. SACK fills old hole and the corresponding segment was not
1015 * ever retransmitted -> reordering. Alas, we cannot use it
1016 * when segment was retransmitted.
1017 * 2. The last flaw is solved with D-SACK. D-SACK arrives
1018 * for retransmitted and already SACKed segment -> reordering..
1019 * Both of these heuristics are not used in Loss state, when we cannot
1020 * account for retransmits accurately.
1021 *
1022 * SACK block validation.
1023 * ----------------------
1024 *
1025 * SACK block range validation checks that the received SACK block fits to
1026 * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
1027 * Note that SND.UNA is not included to the range though being valid because
1028 * it means that the receiver is rather inconsistent with itself reporting
1029 * SACK reneging when it should advance SND.UNA. Such SACK block this is
1030 * perfectly valid, however, in light of RFC2018 which explicitly states
1031 * that "SACK block MUST reflect the newest segment. Even if the newest
1032 * segment is going to be discarded ...", not that it looks very clever
1033 * in case of head skb. Due to potentional receiver driven attacks, we
1034 * choose to avoid immediate execution of a walk in write queue due to
1035 * reneging and defer head skb's loss recovery to standard loss recovery
1036 * procedure that will eventually trigger (nothing forbids us doing this).
1037 *
1038 * Implements also blockage to start_seq wrap-around. Problem lies in the
1039 * fact that though start_seq (s) is before end_seq (i.e., not reversed),
1040 * there's no guarantee that it will be before snd_nxt (n). The problem
1041 * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
1042 * wrap (s_w):
1043 *
1044 * <- outs wnd -> <- wrapzone ->
1045 * u e n u_w e_w s n_w
1046 * | | | | | | |
1047 * |<------------+------+----- TCP seqno space --------------+---------->|
1048 * ...-- <2^31 ->| |<--------...
1049 * ...---- >2^31 ------>| |<--------...
1050 *
1051 * Current code wouldn't be vulnerable but it's better still to discard such
1052 * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
1053 * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
1054 * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
1055 * equal to the ideal case (infinite seqno space without wrap caused issues).
1056 *
1057 * With D-SACK the lower bound is extended to cover sequence space below
1058 * SND.UNA down to undo_marker, which is the last point of interest. Yet
1059 * again, D-SACK block must not to go across snd_una (for the same reason as
1060 * for the normal SACK blocks, explained above). But there all simplicity
1061 * ends, TCP might receive valid D-SACKs below that. As long as they reside
1062 * fully below undo_marker they do not affect behavior in anyway and can
1063 * therefore be safely ignored. In rare cases (which are more or less
1064 * theoretical ones), the D-SACK will nicely cross that boundary due to skb
1065 * fragmentation and packet reordering past skb's retransmission. To consider
1066 * them correctly, the acceptable range must be extended even more though
1067 * the exact amount is rather hard to quantify. However, tp->max_window can
1068 * be used as an exaggerated estimate.
1069 */
1070 static int tcp_is_sackblock_valid(struct tcp_sock *tp, int is_dsack,
1071 u32 start_seq, u32 end_seq)
1072 {
1073 /* Too far in future, or reversed (interpretation is ambiguous) */
1074 if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
1075 return 0;
1076
1077 /* Nasty start_seq wrap-around check (see comments above) */
1078 if (!before(start_seq, tp->snd_nxt))
1079 return 0;
1080
1081 /* In outstanding window? ...This is valid exit for D-SACKs too.
1082 * start_seq == snd_una is non-sensical (see comments above)
1083 */
1084 if (after(start_seq, tp->snd_una))
1085 return 1;
1086
1087 if (!is_dsack || !tp->undo_marker)
1088 return 0;
1089
1090 /* ...Then it's D-SACK, and must reside below snd_una completely */
1091 if (!after(end_seq, tp->snd_una))
1092 return 0;
1093
1094 if (!before(start_seq, tp->undo_marker))
1095 return 1;
1096
1097 /* Too old */
1098 if (!after(end_seq, tp->undo_marker))
1099 return 0;
1100
1101 /* Undo_marker boundary crossing (overestimates a lot). Known already:
1102 * start_seq < undo_marker and end_seq >= undo_marker.
1103 */
1104 return !before(start_seq, end_seq - tp->max_window);
1105 }
1106
1107 /* Check for lost retransmit. This superb idea is borrowed from "ratehalving".
1108 * Event "C". Later note: FACK people cheated me again 8), we have to account
1109 * for reordering! Ugly, but should help.
1110 *
1111 * Search retransmitted skbs from write_queue that were sent when snd_nxt was
1112 * less than what is now known to be received by the other end (derived from
1113 * highest SACK block). Also calculate the lowest snd_nxt among the remaining
1114 * retransmitted skbs to avoid some costly processing per ACKs.
1115 */
1116 static void tcp_mark_lost_retrans(struct sock *sk)
1117 {
1118 const struct inet_connection_sock *icsk = inet_csk(sk);
1119 struct tcp_sock *tp = tcp_sk(sk);
1120 struct sk_buff *skb;
1121 int cnt = 0;
1122 u32 new_low_seq = tp->snd_nxt;
1123 u32 received_upto = tcp_highest_sack_seq(tp);
1124
1125 if (!tcp_is_fack(tp) || !tp->retrans_out ||
1126 !after(received_upto, tp->lost_retrans_low) ||
1127 icsk->icsk_ca_state != TCP_CA_Recovery)
1128 return;
1129
1130 tcp_for_write_queue(skb, sk) {
1131 u32 ack_seq = TCP_SKB_CB(skb)->ack_seq;
1132
1133 if (skb == tcp_send_head(sk))
1134 break;
1135 if (cnt == tp->retrans_out)
1136 break;
1137 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1138 continue;
1139
1140 if (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS))
1141 continue;
1142
1143 if (after(received_upto, ack_seq) &&
1144 (tcp_is_fack(tp) ||
1145 !before(received_upto,
1146 ack_seq + tp->reordering * tp->mss_cache))) {
1147 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1148 tp->retrans_out -= tcp_skb_pcount(skb);
1149
1150 /* clear lost hint */
1151 tp->retransmit_skb_hint = NULL;
1152
1153 if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
1154 tp->lost_out += tcp_skb_pcount(skb);
1155 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1156 }
1157 NET_INC_STATS_BH(LINUX_MIB_TCPLOSTRETRANSMIT);
1158 } else {
1159 if (before(ack_seq, new_low_seq))
1160 new_low_seq = ack_seq;
1161 cnt += tcp_skb_pcount(skb);
1162 }
1163 }
1164
1165 if (tp->retrans_out)
1166 tp->lost_retrans_low = new_low_seq;
1167 }
1168
1169 static int tcp_check_dsack(struct tcp_sock *tp, struct sk_buff *ack_skb,
1170 struct tcp_sack_block_wire *sp, int num_sacks,
1171 u32 prior_snd_una)
1172 {
1173 u32 start_seq_0 = ntohl(get_unaligned(&sp[0].start_seq));
1174 u32 end_seq_0 = ntohl(get_unaligned(&sp[0].end_seq));
1175 int dup_sack = 0;
1176
1177 if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
1178 dup_sack = 1;
1179 tcp_dsack_seen(tp);
1180 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKRECV);
1181 } else if (num_sacks > 1) {
1182 u32 end_seq_1 = ntohl(get_unaligned(&sp[1].end_seq));
1183 u32 start_seq_1 = ntohl(get_unaligned(&sp[1].start_seq));
1184
1185 if (!after(end_seq_0, end_seq_1) &&
1186 !before(start_seq_0, start_seq_1)) {
1187 dup_sack = 1;
1188 tcp_dsack_seen(tp);
1189 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKOFORECV);
1190 }
1191 }
1192
1193 /* D-SACK for already forgotten data... Do dumb counting. */
1194 if (dup_sack &&
1195 !after(end_seq_0, prior_snd_una) &&
1196 after(end_seq_0, tp->undo_marker))
1197 tp->undo_retrans--;
1198
1199 return dup_sack;
1200 }
1201
1202 /* Check if skb is fully within the SACK block. In presence of GSO skbs,
1203 * the incoming SACK may not exactly match but we can find smaller MSS
1204 * aligned portion of it that matches. Therefore we might need to fragment
1205 * which may fail and creates some hassle (caller must handle error case
1206 * returns).
1207 */
1208 static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
1209 u32 start_seq, u32 end_seq)
1210 {
1211 int in_sack, err;
1212 unsigned int pkt_len;
1213
1214 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1215 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1216
1217 if (tcp_skb_pcount(skb) > 1 && !in_sack &&
1218 after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
1219
1220 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1221
1222 if (!in_sack)
1223 pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
1224 else
1225 pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
1226 err = tcp_fragment(sk, skb, pkt_len, skb_shinfo(skb)->gso_size);
1227 if (err < 0)
1228 return err;
1229 }
1230
1231 return in_sack;
1232 }
1233
1234 static int tcp_sacktag_one(struct sk_buff *skb, struct sock *sk,
1235 int *reord, int dup_sack, int fack_count)
1236 {
1237 struct tcp_sock *tp = tcp_sk(sk);
1238 u8 sacked = TCP_SKB_CB(skb)->sacked;
1239 int flag = 0;
1240
1241 /* Account D-SACK for retransmitted packet. */
1242 if (dup_sack && (sacked & TCPCB_RETRANS)) {
1243 if (after(TCP_SKB_CB(skb)->end_seq, tp->undo_marker))
1244 tp->undo_retrans--;
1245 if (sacked & TCPCB_SACKED_ACKED)
1246 *reord = min(fack_count, *reord);
1247 }
1248
1249 /* Nothing to do; acked frame is about to be dropped (was ACKed). */
1250 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1251 return flag;
1252
1253 if (!(sacked & TCPCB_SACKED_ACKED)) {
1254 if (sacked & TCPCB_SACKED_RETRANS) {
1255 /* If the segment is not tagged as lost,
1256 * we do not clear RETRANS, believing
1257 * that retransmission is still in flight.
1258 */
1259 if (sacked & TCPCB_LOST) {
1260 TCP_SKB_CB(skb)->sacked &=
1261 ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
1262 tp->lost_out -= tcp_skb_pcount(skb);
1263 tp->retrans_out -= tcp_skb_pcount(skb);
1264
1265 /* clear lost hint */
1266 tp->retransmit_skb_hint = NULL;
1267 }
1268 } else {
1269 if (!(sacked & TCPCB_RETRANS)) {
1270 /* New sack for not retransmitted frame,
1271 * which was in hole. It is reordering.
1272 */
1273 if (before(TCP_SKB_CB(skb)->seq,
1274 tcp_highest_sack_seq(tp)))
1275 *reord = min(fack_count, *reord);
1276
1277 /* SACK enhanced F-RTO (RFC4138; Appendix B) */
1278 if (!after(TCP_SKB_CB(skb)->end_seq, tp->frto_highmark))
1279 flag |= FLAG_ONLY_ORIG_SACKED;
1280 }
1281
1282 if (sacked & TCPCB_LOST) {
1283 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1284 tp->lost_out -= tcp_skb_pcount(skb);
1285
1286 /* clear lost hint */
1287 tp->retransmit_skb_hint = NULL;
1288 }
1289 }
1290
1291 TCP_SKB_CB(skb)->sacked |= TCPCB_SACKED_ACKED;
1292 flag |= FLAG_DATA_SACKED;
1293 tp->sacked_out += tcp_skb_pcount(skb);
1294
1295 fack_count += tcp_skb_pcount(skb);
1296
1297 /* Lost marker hint past SACKed? Tweak RFC3517 cnt */
1298 if (!tcp_is_fack(tp) && (tp->lost_skb_hint != NULL) &&
1299 before(TCP_SKB_CB(skb)->seq,
1300 TCP_SKB_CB(tp->lost_skb_hint)->seq))
1301 tp->lost_cnt_hint += tcp_skb_pcount(skb);
1302
1303 if (fack_count > tp->fackets_out)
1304 tp->fackets_out = fack_count;
1305
1306 if (!before(TCP_SKB_CB(skb)->seq, tcp_highest_sack_seq(tp)))
1307 tcp_advance_highest_sack(sk, skb);
1308 }
1309
1310 /* D-SACK. We can detect redundant retransmission in S|R and plain R
1311 * frames and clear it. undo_retrans is decreased above, L|R frames
1312 * are accounted above as well.
1313 */
1314 if (dup_sack && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS)) {
1315 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1316 tp->retrans_out -= tcp_skb_pcount(skb);
1317 tp->retransmit_skb_hint = NULL;
1318 }
1319
1320 return flag;
1321 }
1322
1323 static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
1324 struct tcp_sack_block *next_dup,
1325 u32 start_seq, u32 end_seq,
1326 int dup_sack_in, int *fack_count,
1327 int *reord, int *flag)
1328 {
1329 tcp_for_write_queue_from(skb, sk) {
1330 int in_sack = 0;
1331 int dup_sack = dup_sack_in;
1332
1333 if (skb == tcp_send_head(sk))
1334 break;
1335
1336 /* queue is in-order => we can short-circuit the walk early */
1337 if (!before(TCP_SKB_CB(skb)->seq, end_seq))
1338 break;
1339
1340 if ((next_dup != NULL) &&
1341 before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
1342 in_sack = tcp_match_skb_to_sack(sk, skb,
1343 next_dup->start_seq,
1344 next_dup->end_seq);
1345 if (in_sack > 0)
1346 dup_sack = 1;
1347 }
1348
1349 if (in_sack <= 0)
1350 in_sack = tcp_match_skb_to_sack(sk, skb, start_seq,
1351 end_seq);
1352 if (unlikely(in_sack < 0))
1353 break;
1354
1355 if (in_sack)
1356 *flag |= tcp_sacktag_one(skb, sk, reord, dup_sack,
1357 *fack_count);
1358
1359 *fack_count += tcp_skb_pcount(skb);
1360 }
1361 return skb;
1362 }
1363
1364 /* Avoid all extra work that is being done by sacktag while walking in
1365 * a normal way
1366 */
1367 static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
1368 u32 skip_to_seq, int *fack_count)
1369 {
1370 tcp_for_write_queue_from(skb, sk) {
1371 if (skb == tcp_send_head(sk))
1372 break;
1373
1374 if (!before(TCP_SKB_CB(skb)->end_seq, skip_to_seq))
1375 break;
1376
1377 *fack_count += tcp_skb_pcount(skb);
1378 }
1379 return skb;
1380 }
1381
1382 static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
1383 struct sock *sk,
1384 struct tcp_sack_block *next_dup,
1385 u32 skip_to_seq,
1386 int *fack_count, int *reord,
1387 int *flag)
1388 {
1389 if (next_dup == NULL)
1390 return skb;
1391
1392 if (before(next_dup->start_seq, skip_to_seq)) {
1393 skb = tcp_sacktag_skip(skb, sk, next_dup->start_seq, fack_count);
1394 skb = tcp_sacktag_walk(skb, sk, NULL,
1395 next_dup->start_seq, next_dup->end_seq,
1396 1, fack_count, reord, flag);
1397 }
1398
1399 return skb;
1400 }
1401
1402 static int tcp_sack_cache_ok(struct tcp_sock *tp, struct tcp_sack_block *cache)
1403 {
1404 return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1405 }
1406
1407 static int
1408 tcp_sacktag_write_queue(struct sock *sk, struct sk_buff *ack_skb,
1409 u32 prior_snd_una)
1410 {
1411 const struct inet_connection_sock *icsk = inet_csk(sk);
1412 struct tcp_sock *tp = tcp_sk(sk);
1413 unsigned char *ptr = (skb_transport_header(ack_skb) +
1414 TCP_SKB_CB(ack_skb)->sacked);
1415 struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
1416 struct tcp_sack_block sp[4];
1417 struct tcp_sack_block *cache;
1418 struct sk_buff *skb;
1419 int num_sacks = (ptr[1] - TCPOLEN_SACK_BASE) >> 3;
1420 int used_sacks;
1421 int reord = tp->packets_out;
1422 int flag = 0;
1423 int found_dup_sack = 0;
1424 int fack_count;
1425 int i, j;
1426 int first_sack_index;
1427
1428 if (!tp->sacked_out) {
1429 if (WARN_ON(tp->fackets_out))
1430 tp->fackets_out = 0;
1431 tcp_highest_sack_reset(sk);
1432 }
1433
1434 found_dup_sack = tcp_check_dsack(tp, ack_skb, sp_wire,
1435 num_sacks, prior_snd_una);
1436 if (found_dup_sack)
1437 flag |= FLAG_DSACKING_ACK;
1438
1439 /* Eliminate too old ACKs, but take into
1440 * account more or less fresh ones, they can
1441 * contain valid SACK info.
1442 */
1443 if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
1444 return 0;
1445
1446 if (!tp->packets_out)
1447 goto out;
1448
1449 used_sacks = 0;
1450 first_sack_index = 0;
1451 for (i = 0; i < num_sacks; i++) {
1452 int dup_sack = !i && found_dup_sack;
1453
1454 sp[used_sacks].start_seq = ntohl(get_unaligned(&sp_wire[i].start_seq));
1455 sp[used_sacks].end_seq = ntohl(get_unaligned(&sp_wire[i].end_seq));
1456
1457 if (!tcp_is_sackblock_valid(tp, dup_sack,
1458 sp[used_sacks].start_seq,
1459 sp[used_sacks].end_seq)) {
1460 if (dup_sack) {
1461 if (!tp->undo_marker)
1462 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKIGNOREDNOUNDO);
1463 else
1464 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKIGNOREDOLD);
1465 } else {
1466 /* Don't count olds caused by ACK reordering */
1467 if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) &&
1468 !after(sp[used_sacks].end_seq, tp->snd_una))
1469 continue;
1470 NET_INC_STATS_BH(LINUX_MIB_TCPSACKDISCARD);
1471 }
1472 if (i == 0)
1473 first_sack_index = -1;
1474 continue;
1475 }
1476
1477 /* Ignore very old stuff early */
1478 if (!after(sp[used_sacks].end_seq, prior_snd_una))
1479 continue;
1480
1481 used_sacks++;
1482 }
1483
1484 /* order SACK blocks to allow in order walk of the retrans queue */
1485 for (i = used_sacks - 1; i > 0; i--) {
1486 for (j = 0; j < i; j++) {
1487 if (after(sp[j].start_seq, sp[j + 1].start_seq)) {
1488 struct tcp_sack_block tmp;
1489
1490 tmp = sp[j];
1491 sp[j] = sp[j + 1];
1492 sp[j + 1] = tmp;
1493
1494 /* Track where the first SACK block goes to */
1495 if (j == first_sack_index)
1496 first_sack_index = j + 1;
1497 }
1498 }
1499 }
1500
1501 skb = tcp_write_queue_head(sk);
1502 fack_count = 0;
1503 i = 0;
1504
1505 if (!tp->sacked_out) {
1506 /* It's already past, so skip checking against it */
1507 cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1508 } else {
1509 cache = tp->recv_sack_cache;
1510 /* Skip empty blocks in at head of the cache */
1511 while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq &&
1512 !cache->end_seq)
1513 cache++;
1514 }
1515
1516 while (i < used_sacks) {
1517 u32 start_seq = sp[i].start_seq;
1518 u32 end_seq = sp[i].end_seq;
1519 int dup_sack = (found_dup_sack && (i == first_sack_index));
1520 struct tcp_sack_block *next_dup = NULL;
1521
1522 if (found_dup_sack && ((i + 1) == first_sack_index))
1523 next_dup = &sp[i + 1];
1524
1525 /* Event "B" in the comment above. */
1526 if (after(end_seq, tp->high_seq))
1527 flag |= FLAG_DATA_LOST;
1528
1529 /* Skip too early cached blocks */
1530 while (tcp_sack_cache_ok(tp, cache) &&
1531 !before(start_seq, cache->end_seq))
1532 cache++;
1533
1534 /* Can skip some work by looking recv_sack_cache? */
1535 if (tcp_sack_cache_ok(tp, cache) && !dup_sack &&
1536 after(end_seq, cache->start_seq)) {
1537
1538 /* Head todo? */
1539 if (before(start_seq, cache->start_seq)) {
1540 skb = tcp_sacktag_skip(skb, sk, start_seq,
1541 &fack_count);
1542 skb = tcp_sacktag_walk(skb, sk, next_dup,
1543 start_seq,
1544 cache->start_seq,
1545 dup_sack, &fack_count,
1546 &reord, &flag);
1547 }
1548
1549 /* Rest of the block already fully processed? */
1550 if (!after(end_seq, cache->end_seq))
1551 goto advance_sp;
1552
1553 skb = tcp_maybe_skipping_dsack(skb, sk, next_dup,
1554 cache->end_seq,
1555 &fack_count, &reord,
1556 &flag);
1557
1558 /* ...tail remains todo... */
1559 if (tcp_highest_sack_seq(tp) == cache->end_seq) {
1560 /* ...but better entrypoint exists! */
1561 skb = tcp_highest_sack(sk);
1562 if (skb == NULL)
1563 break;
1564 fack_count = tp->fackets_out;
1565 cache++;
1566 goto walk;
1567 }
1568
1569 skb = tcp_sacktag_skip(skb, sk, cache->end_seq,
1570 &fack_count);
1571 /* Check overlap against next cached too (past this one already) */
1572 cache++;
1573 continue;
1574 }
1575
1576 if (!before(start_seq, tcp_highest_sack_seq(tp))) {
1577 skb = tcp_highest_sack(sk);
1578 if (skb == NULL)
1579 break;
1580 fack_count = tp->fackets_out;
1581 }
1582 skb = tcp_sacktag_skip(skb, sk, start_seq, &fack_count);
1583
1584 walk:
1585 skb = tcp_sacktag_walk(skb, sk, next_dup, start_seq, end_seq,
1586 dup_sack, &fack_count, &reord, &flag);
1587
1588 advance_sp:
1589 /* SACK enhanced FRTO (RFC4138, Appendix B): Clearing correct
1590 * due to in-order walk
1591 */
1592 if (after(end_seq, tp->frto_highmark))
1593 flag &= ~FLAG_ONLY_ORIG_SACKED;
1594
1595 i++;
1596 }
1597
1598 /* Clear the head of the cache sack blocks so we can skip it next time */
1599 for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) {
1600 tp->recv_sack_cache[i].start_seq = 0;
1601 tp->recv_sack_cache[i].end_seq = 0;
1602 }
1603 for (j = 0; j < used_sacks; j++)
1604 tp->recv_sack_cache[i++] = sp[j];
1605
1606 tcp_mark_lost_retrans(sk);
1607
1608 tcp_verify_left_out(tp);
1609
1610 if ((reord < tp->fackets_out) &&
1611 ((icsk->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker) &&
1612 (!tp->frto_highmark || after(tp->snd_una, tp->frto_highmark)))
1613 tcp_update_reordering(sk, tp->fackets_out - reord, 0);
1614
1615 out:
1616
1617 #if FASTRETRANS_DEBUG > 0
1618 BUG_TRAP((int)tp->sacked_out >= 0);
1619 BUG_TRAP((int)tp->lost_out >= 0);
1620 BUG_TRAP((int)tp->retrans_out >= 0);
1621 BUG_TRAP((int)tcp_packets_in_flight(tp) >= 0);
1622 #endif
1623 return flag;
1624 }
1625
1626 /* Limits sacked_out so that sum with lost_out isn't ever larger than
1627 * packets_out. Returns zero if sacked_out adjustement wasn't necessary.
1628 */
1629 int tcp_limit_reno_sacked(struct tcp_sock *tp)
1630 {
1631 u32 holes;
1632
1633 holes = max(tp->lost_out, 1U);
1634 holes = min(holes, tp->packets_out);
1635
1636 if ((tp->sacked_out + holes) > tp->packets_out) {
1637 tp->sacked_out = tp->packets_out - holes;
1638 return 1;
1639 }
1640 return 0;
1641 }
1642
1643 /* If we receive more dupacks than we expected counting segments
1644 * in assumption of absent reordering, interpret this as reordering.
1645 * The only another reason could be bug in receiver TCP.
1646 */
1647 static void tcp_check_reno_reordering(struct sock *sk, const int addend)
1648 {
1649 struct tcp_sock *tp = tcp_sk(sk);
1650 if (tcp_limit_reno_sacked(tp))
1651 tcp_update_reordering(sk, tp->packets_out + addend, 0);
1652 }
1653
1654 /* Emulate SACKs for SACKless connection: account for a new dupack. */
1655
1656 static void tcp_add_reno_sack(struct sock *sk)
1657 {
1658 struct tcp_sock *tp = tcp_sk(sk);
1659 tp->sacked_out++;
1660 tcp_check_reno_reordering(sk, 0);
1661 tcp_verify_left_out(tp);
1662 }
1663
1664 /* Account for ACK, ACKing some data in Reno Recovery phase. */
1665
1666 static void tcp_remove_reno_sacks(struct sock *sk, int acked)
1667 {
1668 struct tcp_sock *tp = tcp_sk(sk);
1669
1670 if (acked > 0) {
1671 /* One ACK acked hole. The rest eat duplicate ACKs. */
1672 if (acked - 1 >= tp->sacked_out)
1673 tp->sacked_out = 0;
1674 else
1675 tp->sacked_out -= acked - 1;
1676 }
1677 tcp_check_reno_reordering(sk, acked);
1678 tcp_verify_left_out(tp);
1679 }
1680
1681 static inline void tcp_reset_reno_sack(struct tcp_sock *tp)
1682 {
1683 tp->sacked_out = 0;
1684 }
1685
1686 static int tcp_is_sackfrto(const struct tcp_sock *tp)
1687 {
1688 return (sysctl_tcp_frto == 0x2) && !tcp_is_reno(tp);
1689 }
1690
1691 /* F-RTO can only be used if TCP has never retransmitted anything other than
1692 * head (SACK enhanced variant from Appendix B of RFC4138 is more robust here)
1693 */
1694 int tcp_use_frto(struct sock *sk)
1695 {
1696 const struct tcp_sock *tp = tcp_sk(sk);
1697 const struct inet_connection_sock *icsk = inet_csk(sk);
1698 struct sk_buff *skb;
1699
1700 if (!sysctl_tcp_frto)
1701 return 0;
1702
1703 /* MTU probe and F-RTO won't really play nicely along currently */
1704 if (icsk->icsk_mtup.probe_size)
1705 return 0;
1706
1707 if (tcp_is_sackfrto(tp))
1708 return 1;
1709
1710 /* Avoid expensive walking of rexmit queue if possible */
1711 if (tp->retrans_out > 1)
1712 return 0;
1713
1714 skb = tcp_write_queue_head(sk);
1715 skb = tcp_write_queue_next(sk, skb); /* Skips head */
1716 tcp_for_write_queue_from(skb, sk) {
1717 if (skb == tcp_send_head(sk))
1718 break;
1719 if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS)
1720 return 0;
1721 /* Short-circuit when first non-SACKed skb has been checked */
1722 if (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
1723 break;
1724 }
1725 return 1;
1726 }
1727
1728 /* RTO occurred, but do not yet enter Loss state. Instead, defer RTO
1729 * recovery a bit and use heuristics in tcp_process_frto() to detect if
1730 * the RTO was spurious. Only clear SACKED_RETRANS of the head here to
1731 * keep retrans_out counting accurate (with SACK F-RTO, other than head
1732 * may still have that bit set); TCPCB_LOST and remaining SACKED_RETRANS
1733 * bits are handled if the Loss state is really to be entered (in
1734 * tcp_enter_frto_loss).
1735 *
1736 * Do like tcp_enter_loss() would; when RTO expires the second time it
1737 * does:
1738 * "Reduce ssthresh if it has not yet been made inside this window."
1739 */
1740 void tcp_enter_frto(struct sock *sk)
1741 {
1742 const struct inet_connection_sock *icsk = inet_csk(sk);
1743 struct tcp_sock *tp = tcp_sk(sk);
1744 struct sk_buff *skb;
1745
1746 if ((!tp->frto_counter && icsk->icsk_ca_state <= TCP_CA_Disorder) ||
1747 tp->snd_una == tp->high_seq ||
1748 ((icsk->icsk_ca_state == TCP_CA_Loss || tp->frto_counter) &&
1749 !icsk->icsk_retransmits)) {
1750 tp->prior_ssthresh = tcp_current_ssthresh(sk);
1751 /* Our state is too optimistic in ssthresh() call because cwnd
1752 * is not reduced until tcp_enter_frto_loss() when previous F-RTO
1753 * recovery has not yet completed. Pattern would be this: RTO,
1754 * Cumulative ACK, RTO (2xRTO for the same segment does not end
1755 * up here twice).
1756 * RFC4138 should be more specific on what to do, even though
1757 * RTO is quite unlikely to occur after the first Cumulative ACK
1758 * due to back-off and complexity of triggering events ...
1759 */
1760 if (tp->frto_counter) {
1761 u32 stored_cwnd;
1762 stored_cwnd = tp->snd_cwnd;
1763 tp->snd_cwnd = 2;
1764 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
1765 tp->snd_cwnd = stored_cwnd;
1766 } else {
1767 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
1768 }
1769 /* ... in theory, cong.control module could do "any tricks" in
1770 * ssthresh(), which means that ca_state, lost bits and lost_out
1771 * counter would have to be faked before the call occurs. We
1772 * consider that too expensive, unlikely and hacky, so modules
1773 * using these in ssthresh() must deal these incompatibility
1774 * issues if they receives CA_EVENT_FRTO and frto_counter != 0
1775 */
1776 tcp_ca_event(sk, CA_EVENT_FRTO);
1777 }
1778
1779 tp->undo_marker = tp->snd_una;
1780 tp->undo_retrans = 0;
1781
1782 skb = tcp_write_queue_head(sk);
1783 if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS)
1784 tp->undo_marker = 0;
1785 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) {
1786 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1787 tp->retrans_out -= tcp_skb_pcount(skb);
1788 }
1789 tcp_verify_left_out(tp);
1790
1791 /* Too bad if TCP was application limited */
1792 tp->snd_cwnd = min(tp->snd_cwnd, tcp_packets_in_flight(tp) + 1);
1793
1794 /* Earlier loss recovery underway (see RFC4138; Appendix B).
1795 * The last condition is necessary at least in tp->frto_counter case.
1796 */
1797 if (tcp_is_sackfrto(tp) && (tp->frto_counter ||
1798 ((1 << icsk->icsk_ca_state) & (TCPF_CA_Recovery|TCPF_CA_Loss))) &&
1799 after(tp->high_seq, tp->snd_una)) {
1800 tp->frto_highmark = tp->high_seq;
1801 } else {
1802 tp->frto_highmark = tp->snd_nxt;
1803 }
1804 tcp_set_ca_state(sk, TCP_CA_Disorder);
1805 tp->high_seq = tp->snd_nxt;
1806 tp->frto_counter = 1;
1807 }
1808
1809 /* Enter Loss state after F-RTO was applied. Dupack arrived after RTO,
1810 * which indicates that we should follow the traditional RTO recovery,
1811 * i.e. mark everything lost and do go-back-N retransmission.
1812 */
1813 static void tcp_enter_frto_loss(struct sock *sk, int allowed_segments, int flag)
1814 {
1815 struct tcp_sock *tp = tcp_sk(sk);
1816 struct sk_buff *skb;
1817
1818 tp->lost_out = 0;
1819 tp->retrans_out = 0;
1820 if (tcp_is_reno(tp))
1821 tcp_reset_reno_sack(tp);
1822
1823 tcp_for_write_queue(skb, sk) {
1824 if (skb == tcp_send_head(sk))
1825 break;
1826
1827 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1828 /*
1829 * Count the retransmission made on RTO correctly (only when
1830 * waiting for the first ACK and did not get it)...
1831 */
1832 if ((tp->frto_counter == 1) && !(flag & FLAG_DATA_ACKED)) {
1833 /* For some reason this R-bit might get cleared? */
1834 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS)
1835 tp->retrans_out += tcp_skb_pcount(skb);
1836 /* ...enter this if branch just for the first segment */
1837 flag |= FLAG_DATA_ACKED;
1838 } else {
1839 if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS)
1840 tp->undo_marker = 0;
1841 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1842 }
1843
1844 /* Marking forward transmissions that were made after RTO lost
1845 * can cause unnecessary retransmissions in some scenarios,
1846 * SACK blocks will mitigate that in some but not in all cases.
1847 * We used to not mark them but it was causing break-ups with
1848 * receivers that do only in-order receival.
1849 *
1850 * TODO: we could detect presence of such receiver and select
1851 * different behavior per flow.
1852 */
1853 if (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) {
1854 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1855 tp->lost_out += tcp_skb_pcount(skb);
1856 }
1857 }
1858 tcp_verify_left_out(tp);
1859
1860 tp->snd_cwnd = tcp_packets_in_flight(tp) + allowed_segments;
1861 tp->snd_cwnd_cnt = 0;
1862 tp->snd_cwnd_stamp = tcp_time_stamp;
1863 tp->frto_counter = 0;
1864 tp->bytes_acked = 0;
1865
1866 tp->reordering = min_t(unsigned int, tp->reordering,
1867 sysctl_tcp_reordering);
1868 tcp_set_ca_state(sk, TCP_CA_Loss);
1869 tp->high_seq = tp->snd_nxt;
1870 TCP_ECN_queue_cwr(tp);
1871
1872 tcp_clear_retrans_hints_partial(tp);
1873 }
1874
1875 static void tcp_clear_retrans_partial(struct tcp_sock *tp)
1876 {
1877 tp->retrans_out = 0;
1878 tp->lost_out = 0;
1879
1880 tp->undo_marker = 0;
1881 tp->undo_retrans = 0;
1882 }
1883
1884 void tcp_clear_retrans(struct tcp_sock *tp)
1885 {
1886 tcp_clear_retrans_partial(tp);
1887
1888 tp->fackets_out = 0;
1889 tp->sacked_out = 0;
1890 }
1891
1892 /* Enter Loss state. If "how" is not zero, forget all SACK information
1893 * and reset tags completely, otherwise preserve SACKs. If receiver
1894 * dropped its ofo queue, we will know this due to reneging detection.
1895 */
1896 void tcp_enter_loss(struct sock *sk, int how)
1897 {
1898 const struct inet_connection_sock *icsk = inet_csk(sk);
1899 struct tcp_sock *tp = tcp_sk(sk);
1900 struct sk_buff *skb;
1901
1902 /* Reduce ssthresh if it has not yet been made inside this window. */
1903 if (icsk->icsk_ca_state <= TCP_CA_Disorder || tp->snd_una == tp->high_seq ||
1904 (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) {
1905 tp->prior_ssthresh = tcp_current_ssthresh(sk);
1906 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
1907 tcp_ca_event(sk, CA_EVENT_LOSS);
1908 }
1909 tp->snd_cwnd = 1;
1910 tp->snd_cwnd_cnt = 0;
1911 tp->snd_cwnd_stamp = tcp_time_stamp;
1912
1913 tp->bytes_acked = 0;
1914 tcp_clear_retrans_partial(tp);
1915
1916 if (tcp_is_reno(tp))
1917 tcp_reset_reno_sack(tp);
1918
1919 if (!how) {
1920 /* Push undo marker, if it was plain RTO and nothing
1921 * was retransmitted. */
1922 tp->undo_marker = tp->snd_una;
1923 tcp_clear_retrans_hints_partial(tp);
1924 } else {
1925 tp->sacked_out = 0;
1926 tp->fackets_out = 0;
1927 tcp_clear_all_retrans_hints(tp);
1928 }
1929
1930 tcp_for_write_queue(skb, sk) {
1931 if (skb == tcp_send_head(sk))
1932 break;
1933
1934 if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS)
1935 tp->undo_marker = 0;
1936 TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
1937 if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || how) {
1938 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
1939 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1940 tp->lost_out += tcp_skb_pcount(skb);
1941 }
1942 }
1943 tcp_verify_left_out(tp);
1944
1945 tp->reordering = min_t(unsigned int, tp->reordering,
1946 sysctl_tcp_reordering);
1947 tcp_set_ca_state(sk, TCP_CA_Loss);
1948 tp->high_seq = tp->snd_nxt;
1949 TCP_ECN_queue_cwr(tp);
1950 /* Abort F-RTO algorithm if one is in progress */
1951 tp->frto_counter = 0;
1952 }
1953
1954 /* If ACK arrived pointing to a remembered SACK, it means that our
1955 * remembered SACKs do not reflect real state of receiver i.e.
1956 * receiver _host_ is heavily congested (or buggy).
1957 *
1958 * Do processing similar to RTO timeout.
1959 */
1960 static int tcp_check_sack_reneging(struct sock *sk, int flag)
1961 {
1962 if (flag & FLAG_SACK_RENEGING) {
1963 struct inet_connection_sock *icsk = inet_csk(sk);
1964 NET_INC_STATS_BH(LINUX_MIB_TCPSACKRENEGING);
1965
1966 tcp_enter_loss(sk, 1);
1967 icsk->icsk_retransmits++;
1968 tcp_retransmit_skb(sk, tcp_write_queue_head(sk));
1969 inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
1970 icsk->icsk_rto, TCP_RTO_MAX);
1971 return 1;
1972 }
1973 return 0;
1974 }
1975
1976 static inline int tcp_fackets_out(struct tcp_sock *tp)
1977 {
1978 return tcp_is_reno(tp) ? tp->sacked_out + 1 : tp->fackets_out;
1979 }
1980
1981 /* Heurestics to calculate number of duplicate ACKs. There's no dupACKs
1982 * counter when SACK is enabled (without SACK, sacked_out is used for
1983 * that purpose).
1984 *
1985 * Instead, with FACK TCP uses fackets_out that includes both SACKed
1986 * segments up to the highest received SACK block so far and holes in
1987 * between them.
1988 *
1989 * With reordering, holes may still be in flight, so RFC3517 recovery
1990 * uses pure sacked_out (total number of SACKed segments) even though
1991 * it violates the RFC that uses duplicate ACKs, often these are equal
1992 * but when e.g. out-of-window ACKs or packet duplication occurs,
1993 * they differ. Since neither occurs due to loss, TCP should really
1994 * ignore them.
1995 */
1996 static inline int tcp_dupack_heurestics(struct tcp_sock *tp)
1997 {
1998 return tcp_is_fack(tp) ? tp->fackets_out : tp->sacked_out + 1;
1999 }
2000
2001 static inline int tcp_skb_timedout(struct sock *sk, struct sk_buff *skb)
2002 {
2003 return (tcp_time_stamp - TCP_SKB_CB(skb)->when > inet_csk(sk)->icsk_rto);
2004 }
2005
2006 static inline int tcp_head_timedout(struct sock *sk)
2007 {
2008 struct tcp_sock *tp = tcp_sk(sk);
2009
2010 return tp->packets_out &&
2011 tcp_skb_timedout(sk, tcp_write_queue_head(sk));
2012 }
2013
2014 /* Linux NewReno/SACK/FACK/ECN state machine.
2015 * --------------------------------------
2016 *
2017 * "Open" Normal state, no dubious events, fast path.
2018 * "Disorder" In all the respects it is "Open",
2019 * but requires a bit more attention. It is entered when
2020 * we see some SACKs or dupacks. It is split of "Open"
2021 * mainly to move some processing from fast path to slow one.
2022 * "CWR" CWND was reduced due to some Congestion Notification event.
2023 * It can be ECN, ICMP source quench, local device congestion.
2024 * "Recovery" CWND was reduced, we are fast-retransmitting.
2025 * "Loss" CWND was reduced due to RTO timeout or SACK reneging.
2026 *
2027 * tcp_fastretrans_alert() is entered:
2028 * - each incoming ACK, if state is not "Open"
2029 * - when arrived ACK is unusual, namely:
2030 * * SACK
2031 * * Duplicate ACK.
2032 * * ECN ECE.
2033 *
2034 * Counting packets in flight is pretty simple.
2035 *
2036 * in_flight = packets_out - left_out + retrans_out
2037 *
2038 * packets_out is SND.NXT-SND.UNA counted in packets.
2039 *
2040 * retrans_out is number of retransmitted segments.
2041 *
2042 * left_out is number of segments left network, but not ACKed yet.
2043 *
2044 * left_out = sacked_out + lost_out
2045 *
2046 * sacked_out: Packets, which arrived to receiver out of order
2047 * and hence not ACKed. With SACKs this number is simply
2048 * amount of SACKed data. Even without SACKs
2049 * it is easy to give pretty reliable estimate of this number,
2050 * counting duplicate ACKs.
2051 *
2052 * lost_out: Packets lost by network. TCP has no explicit
2053 * "loss notification" feedback from network (for now).
2054 * It means that this number can be only _guessed_.
2055 * Actually, it is the heuristics to predict lossage that
2056 * distinguishes different algorithms.
2057 *
2058 * F.e. after RTO, when all the queue is considered as lost,
2059 * lost_out = packets_out and in_flight = retrans_out.
2060 *
2061 * Essentially, we have now two algorithms counting
2062 * lost packets.
2063 *
2064 * FACK: It is the simplest heuristics. As soon as we decided
2065 * that something is lost, we decide that _all_ not SACKed
2066 * packets until the most forward SACK are lost. I.e.
2067 * lost_out = fackets_out - sacked_out and left_out = fackets_out.
2068 * It is absolutely correct estimate, if network does not reorder
2069 * packets. And it loses any connection to reality when reordering
2070 * takes place. We use FACK by default until reordering
2071 * is suspected on the path to this destination.
2072 *
2073 * NewReno: when Recovery is entered, we assume that one segment
2074 * is lost (classic Reno). While we are in Recovery and
2075 * a partial ACK arrives, we assume that one more packet
2076 * is lost (NewReno). This heuristics are the same in NewReno
2077 * and SACK.
2078 *
2079 * Imagine, that's all! Forget about all this shamanism about CWND inflation
2080 * deflation etc. CWND is real congestion window, never inflated, changes
2081 * only according to classic VJ rules.
2082 *
2083 * Really tricky (and requiring careful tuning) part of algorithm
2084 * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
2085 * The first determines the moment _when_ we should reduce CWND and,
2086 * hence, slow down forward transmission. In fact, it determines the moment
2087 * when we decide that hole is caused by loss, rather than by a reorder.
2088 *
2089 * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
2090 * holes, caused by lost packets.
2091 *
2092 * And the most logically complicated part of algorithm is undo
2093 * heuristics. We detect false retransmits due to both too early
2094 * fast retransmit (reordering) and underestimated RTO, analyzing
2095 * timestamps and D-SACKs. When we detect that some segments were
2096 * retransmitted by mistake and CWND reduction was wrong, we undo
2097 * window reduction and abort recovery phase. This logic is hidden
2098 * inside several functions named tcp_try_undo_<something>.
2099 */
2100
2101 /* This function decides, when we should leave Disordered state
2102 * and enter Recovery phase, reducing congestion window.
2103 *
2104 * Main question: may we further continue forward transmission
2105 * with the same cwnd?
2106 */
2107 static int tcp_time_to_recover(struct sock *sk)
2108 {
2109 struct tcp_sock *tp = tcp_sk(sk);
2110 __u32 packets_out;
2111
2112 /* Do not perform any recovery during F-RTO algorithm */
2113 if (tp->frto_counter)
2114 return 0;
2115
2116 /* Trick#1: The loss is proven. */
2117 if (tp->lost_out)
2118 return 1;
2119
2120 /* Not-A-Trick#2 : Classic rule... */
2121 if (tcp_dupack_heurestics(tp) > tp->reordering)
2122 return 1;
2123
2124 /* Trick#3 : when we use RFC2988 timer restart, fast
2125 * retransmit can be triggered by timeout of queue head.
2126 */
2127 if (tcp_is_fack(tp) && tcp_head_timedout(sk))
2128 return 1;
2129
2130 /* Trick#4: It is still not OK... But will it be useful to delay
2131 * recovery more?
2132 */
2133 packets_out = tp->packets_out;
2134 if (packets_out <= tp->reordering &&
2135 tp->sacked_out >= max_t(__u32, packets_out/2, sysctl_tcp_reordering) &&
2136 !tcp_may_send_now(sk)) {
2137 /* We have nothing to send. This connection is limited
2138 * either by receiver window or by application.
2139 */
2140 return 1;
2141 }
2142
2143 return 0;
2144 }
2145
2146 /* RFC: This is from the original, I doubt that this is necessary at all:
2147 * clear xmit_retrans hint if seq of this skb is beyond hint. How could we
2148 * retransmitted past LOST markings in the first place? I'm not fully sure
2149 * about undo and end of connection cases, which can cause R without L?
2150 */
2151 static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
2152 {
2153 if ((tp->retransmit_skb_hint != NULL) &&
2154 before(TCP_SKB_CB(skb)->seq,
2155 TCP_SKB_CB(tp->retransmit_skb_hint)->seq))
2156 tp->retransmit_skb_hint = NULL;
2157 }
2158
2159 /* Mark head of queue up as lost. With RFC3517 SACK, the packets is
2160 * is against sacked "cnt", otherwise it's against facked "cnt"
2161 */
2162 static void tcp_mark_head_lost(struct sock *sk, int packets)
2163 {
2164 struct tcp_sock *tp = tcp_sk(sk);
2165 struct sk_buff *skb;
2166 int cnt, oldcnt;
2167 int err;
2168 unsigned int mss;
2169
2170 BUG_TRAP(packets <= tp->packets_out);
2171 if (tp->lost_skb_hint) {
2172 skb = tp->lost_skb_hint;
2173 cnt = tp->lost_cnt_hint;
2174 } else {
2175 skb = tcp_write_queue_head(sk);
2176 cnt = 0;
2177 }
2178
2179 tcp_for_write_queue_from(skb, sk) {
2180 if (skb == tcp_send_head(sk))
2181 break;
2182 /* TODO: do this better */
2183 /* this is not the most efficient way to do this... */
2184 tp->lost_skb_hint = skb;
2185 tp->lost_cnt_hint = cnt;
2186
2187 if (after(TCP_SKB_CB(skb)->end_seq, tp->high_seq))
2188 break;
2189
2190 oldcnt = cnt;
2191 if (tcp_is_fack(tp) || tcp_is_reno(tp) ||
2192 (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
2193 cnt += tcp_skb_pcount(skb);
2194
2195 if (cnt > packets) {
2196 if (tcp_is_sack(tp) || (oldcnt >= packets))
2197 break;
2198
2199 mss = skb_shinfo(skb)->gso_size;
2200 err = tcp_fragment(sk, skb, (packets - oldcnt) * mss, mss);
2201 if (err < 0)
2202 break;
2203 cnt = packets;
2204 }
2205
2206 if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_SACKED_ACKED|TCPCB_LOST))) {
2207 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
2208 tp->lost_out += tcp_skb_pcount(skb);
2209 tcp_verify_retransmit_hint(tp, skb);
2210 }
2211 }
2212 tcp_verify_left_out(tp);
2213 }
2214
2215 /* Account newly detected lost packet(s) */
2216
2217 static void tcp_update_scoreboard(struct sock *sk, int fast_rexmit)
2218 {
2219 struct tcp_sock *tp = tcp_sk(sk);
2220
2221 if (tcp_is_reno(tp)) {
2222 tcp_mark_head_lost(sk, 1);
2223 } else if (tcp_is_fack(tp)) {
2224 int lost = tp->fackets_out - tp->reordering;
2225 if (lost <= 0)
2226 lost = 1;
2227 tcp_mark_head_lost(sk, lost);
2228 } else {
2229 int sacked_upto = tp->sacked_out - tp->reordering;
2230 if (sacked_upto < fast_rexmit)
2231 sacked_upto = fast_rexmit;
2232 tcp_mark_head_lost(sk, sacked_upto);
2233 }
2234
2235 /* New heuristics: it is possible only after we switched
2236 * to restart timer each time when something is ACKed.
2237 * Hence, we can detect timed out packets during fast
2238 * retransmit without falling to slow start.
2239 */
2240 if (tcp_is_fack(tp) && tcp_head_timedout(sk)) {
2241 struct sk_buff *skb;
2242
2243 skb = tp->scoreboard_skb_hint ? tp->scoreboard_skb_hint
2244 : tcp_write_queue_head(sk);
2245
2246 tcp_for_write_queue_from(skb, sk) {
2247 if (skb == tcp_send_head(sk))
2248 break;
2249 if (!tcp_skb_timedout(sk, skb))
2250 break;
2251
2252 if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_SACKED_ACKED|TCPCB_LOST))) {
2253 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
2254 tp->lost_out += tcp_skb_pcount(skb);
2255 tcp_verify_retransmit_hint(tp, skb);
2256 }
2257 }
2258
2259 tp->scoreboard_skb_hint = skb;
2260
2261 tcp_verify_left_out(tp);
2262 }
2263 }
2264
2265 /* CWND moderation, preventing bursts due to too big ACKs
2266 * in dubious situations.
2267 */
2268 static inline void tcp_moderate_cwnd(struct tcp_sock *tp)
2269 {
2270 tp->snd_cwnd = min(tp->snd_cwnd,
2271 tcp_packets_in_flight(tp) + tcp_max_burst(tp));
2272 tp->snd_cwnd_stamp = tcp_time_stamp;
2273 }
2274
2275 /* Lower bound on congestion window is slow start threshold
2276 * unless congestion avoidance choice decides to overide it.
2277 */
2278 static inline u32 tcp_cwnd_min(const struct sock *sk)
2279 {
2280 const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
2281
2282 return ca_ops->min_cwnd ? ca_ops->min_cwnd(sk) : tcp_sk(sk)->snd_ssthresh;
2283 }
2284
2285 /* Decrease cwnd each second ack. */
2286 static void tcp_cwnd_down(struct sock *sk, int flag)
2287 {
2288 struct tcp_sock *tp = tcp_sk(sk);
2289 int decr = tp->snd_cwnd_cnt + 1;
2290
2291 if ((flag & (FLAG_ANY_PROGRESS | FLAG_DSACKING_ACK)) ||
2292 (tcp_is_reno(tp) && !(flag & FLAG_NOT_DUP))) {
2293 tp->snd_cwnd_cnt = decr & 1;
2294 decr >>= 1;
2295
2296 if (decr && tp->snd_cwnd > tcp_cwnd_min(sk))
2297 tp->snd_cwnd -= decr;
2298
2299 tp->snd_cwnd = min(tp->snd_cwnd, tcp_packets_in_flight(tp) + 1);
2300 tp->snd_cwnd_stamp = tcp_time_stamp;
2301 }
2302 }
2303
2304 /* Nothing was retransmitted or returned timestamp is less
2305 * than timestamp of the first retransmission.
2306 */
2307 static inline int tcp_packet_delayed(struct tcp_sock *tp)
2308 {
2309 return !tp->retrans_stamp ||
2310 (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
2311 (__s32)(tp->rx_opt.rcv_tsecr - tp->retrans_stamp) < 0);
2312 }
2313
2314 /* Undo procedures. */
2315
2316 #if FASTRETRANS_DEBUG > 1
2317 static void DBGUNDO(struct sock *sk, const char *msg)
2318 {
2319 struct tcp_sock *tp = tcp_sk(sk);
2320 struct inet_sock *inet = inet_sk(sk);
2321
2322 printk(KERN_DEBUG "Undo %s %u.%u.%u.%u/%u c%u l%u ss%u/%u p%u\n",
2323 msg,
2324 NIPQUAD(inet->daddr), ntohs(inet->dport),
2325 tp->snd_cwnd, tcp_left_out(tp),
2326 tp->snd_ssthresh, tp->prior_ssthresh,
2327 tp->packets_out);
2328 }
2329 #else
2330 #define DBGUNDO(x...) do { } while (0)
2331 #endif
2332
2333 static void tcp_undo_cwr(struct sock *sk, const int undo)
2334 {
2335 struct tcp_sock *tp = tcp_sk(sk);
2336
2337 if (tp->prior_ssthresh) {
2338 const struct inet_connection_sock *icsk = inet_csk(sk);
2339
2340 if (icsk->icsk_ca_ops->undo_cwnd)
2341 tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk);
2342 else
2343 tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh << 1);
2344
2345 if (undo && tp->prior_ssthresh > tp->snd_ssthresh) {
2346 tp->snd_ssthresh = tp->prior_ssthresh;
2347 TCP_ECN_withdraw_cwr(tp);
2348 }
2349 } else {
2350 tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh);
2351 }
2352 tcp_moderate_cwnd(tp);
2353 tp->snd_cwnd_stamp = tcp_time_stamp;
2354
2355 /* There is something screwy going on with the retrans hints after
2356 an undo */
2357 tcp_clear_all_retrans_hints(tp);
2358 }
2359
2360 static inline int tcp_may_undo(struct tcp_sock *tp)
2361 {
2362 return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp));
2363 }
2364
2365 /* People celebrate: "We love our President!" */
2366 static int tcp_try_undo_recovery(struct sock *sk)
2367 {
2368 struct tcp_sock *tp = tcp_sk(sk);
2369
2370 if (tcp_may_undo(tp)) {
2371 /* Happy end! We did not retransmit anything
2372 * or our original transmission succeeded.
2373 */
2374 DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans");
2375 tcp_undo_cwr(sk, 1);
2376 if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss)
2377 NET_INC_STATS_BH(LINUX_MIB_TCPLOSSUNDO);
2378 else
2379 NET_INC_STATS_BH(LINUX_MIB_TCPFULLUNDO);
2380 tp->undo_marker = 0;
2381 }
2382 if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) {
2383 /* Hold old state until something *above* high_seq
2384 * is ACKed. For Reno it is MUST to prevent false
2385 * fast retransmits (RFC2582). SACK TCP is safe. */
2386 tcp_moderate_cwnd(tp);
2387 return 1;
2388 }
2389 tcp_set_ca_state(sk, TCP_CA_Open);
2390 return 0;
2391 }
2392
2393 /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
2394 static void tcp_try_undo_dsack(struct sock *sk)
2395 {
2396 struct tcp_sock *tp = tcp_sk(sk);
2397
2398 if (tp->undo_marker && !tp->undo_retrans) {
2399 DBGUNDO(sk, "D-SACK");
2400 tcp_undo_cwr(sk, 1);
2401 tp->undo_marker = 0;
2402 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKUNDO);
2403 }
2404 }
2405
2406 /* Undo during fast recovery after partial ACK. */
2407
2408 static int tcp_try_undo_partial(struct sock *sk, int acked)
2409 {
2410 struct tcp_sock *tp = tcp_sk(sk);
2411 /* Partial ACK arrived. Force Hoe's retransmit. */
2412 int failed = tcp_is_reno(tp) || (tcp_fackets_out(tp) > tp->reordering);
2413
2414 if (tcp_may_undo(tp)) {
2415 /* Plain luck! Hole if filled with delayed
2416 * packet, rather than with a retransmit.
2417 */
2418 if (tp->retrans_out == 0)
2419 tp->retrans_stamp = 0;
2420
2421 tcp_update_reordering(sk, tcp_fackets_out(tp) + acked, 1);
2422
2423 DBGUNDO(sk, "Hoe");
2424 tcp_undo_cwr(sk, 0);
2425 NET_INC_STATS_BH(LINUX_MIB_TCPPARTIALUNDO);
2426
2427 /* So... Do not make Hoe's retransmit yet.
2428 * If the first packet was delayed, the rest
2429 * ones are most probably delayed as well.
2430 */
2431 failed = 0;
2432 }
2433 return failed;
2434 }
2435
2436 /* Undo during loss recovery after partial ACK. */
2437 static int tcp_try_undo_loss(struct sock *sk)
2438 {
2439 struct tcp_sock *tp = tcp_sk(sk);
2440
2441 if (tcp_may_undo(tp)) {
2442 struct sk_buff *skb;
2443 tcp_for_write_queue(skb, sk) {
2444 if (skb == tcp_send_head(sk))
2445 break;
2446 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
2447 }
2448
2449 tcp_clear_all_retrans_hints(tp);
2450
2451 DBGUNDO(sk, "partial loss");
2452 tp->lost_out = 0;
2453 tcp_undo_cwr(sk, 1);
2454 NET_INC_STATS_BH(LINUX_MIB_TCPLOSSUNDO);
2455 inet_csk(sk)->icsk_retransmits = 0;
2456 tp->undo_marker = 0;
2457 if (tcp_is_sack(tp))
2458 tcp_set_ca_state(sk, TCP_CA_Open);
2459 return 1;
2460 }
2461 return 0;
2462 }
2463
2464 static inline void tcp_complete_cwr(struct sock *sk)
2465 {
2466 struct tcp_sock *tp = tcp_sk(sk);
2467 tp->snd_cwnd = min(tp->snd_cwnd, tp->snd_ssthresh);
2468 tp->snd_cwnd_stamp = tcp_time_stamp;
2469 tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
2470 }
2471
2472 static void tcp_try_keep_open(struct sock *sk)
2473 {
2474 struct tcp_sock *tp = tcp_sk(sk);
2475 int state = TCP_CA_Open;
2476
2477 if (tcp_left_out(tp) || tp->retrans_out || tp->undo_marker)
2478 state = TCP_CA_Disorder;
2479
2480 if (inet_csk(sk)->icsk_ca_state != state) {
2481 tcp_set_ca_state(sk, state);
2482 tp->high_seq = tp->snd_nxt;
2483 }
2484 }
2485
2486 static void tcp_try_to_open(struct sock *sk, int flag)
2487 {
2488 struct tcp_sock *tp = tcp_sk(sk);
2489
2490 tcp_verify_left_out(tp);
2491
2492 if (!tp->frto_counter && tp->retrans_out == 0)
2493 tp->retrans_stamp = 0;
2494
2495 if (flag & FLAG_ECE)
2496 tcp_enter_cwr(sk, 1);
2497
2498 if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) {
2499 tcp_try_keep_open(sk);
2500 tcp_moderate_cwnd(tp);
2501 } else {
2502 tcp_cwnd_down(sk, flag);
2503 }
2504 }
2505
2506 static void tcp_mtup_probe_failed(struct sock *sk)
2507 {
2508 struct inet_connection_sock *icsk = inet_csk(sk);
2509
2510 icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
2511 icsk->icsk_mtup.probe_size = 0;
2512 }
2513
2514 static void tcp_mtup_probe_success(struct sock *sk, struct sk_buff *skb)
2515 {
2516 struct tcp_sock *tp = tcp_sk(sk);
2517 struct inet_connection_sock *icsk = inet_csk(sk);
2518
2519 /* FIXME: breaks with very large cwnd */
2520 tp->prior_ssthresh = tcp_current_ssthresh(sk);
2521 tp->snd_cwnd = tp->snd_cwnd *
2522 tcp_mss_to_mtu(sk, tp->mss_cache) /
2523 icsk->icsk_mtup.probe_size;
2524 tp->snd_cwnd_cnt = 0;
2525 tp->snd_cwnd_stamp = tcp_time_stamp;
2526 tp->rcv_ssthresh = tcp_current_ssthresh(sk);
2527
2528 icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
2529 icsk->icsk_mtup.probe_size = 0;
2530 tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
2531 }
2532
2533 /* Process an event, which can update packets-in-flight not trivially.
2534 * Main goal of this function is to calculate new estimate for left_out,
2535 * taking into account both packets sitting in receiver's buffer and
2536 * packets lost by network.
2537 *
2538 * Besides that it does CWND reduction, when packet loss is detected
2539 * and changes state of machine.
2540 *
2541 * It does _not_ decide what to send, it is made in function
2542 * tcp_xmit_retransmit_queue().
2543 */
2544 static void tcp_fastretrans_alert(struct sock *sk, int pkts_acked, int flag)
2545 {
2546 struct inet_connection_sock *icsk = inet_csk(sk);
2547 struct tcp_sock *tp = tcp_sk(sk);
2548 int is_dupack = !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP));
2549 int do_lost = is_dupack || ((flag & FLAG_DATA_SACKED) &&
2550 (tcp_fackets_out(tp) > tp->reordering));
2551 int fast_rexmit = 0;
2552
2553 if (WARN_ON(!tp->packets_out && tp->sacked_out))
2554 tp->sacked_out = 0;
2555 if (WARN_ON(!tp->sacked_out && tp->fackets_out))
2556 tp->fackets_out = 0;
2557
2558 /* Now state machine starts.
2559 * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
2560 if (flag & FLAG_ECE)
2561 tp->prior_ssthresh = 0;
2562
2563 /* B. In all the states check for reneging SACKs. */
2564 if (tcp_check_sack_reneging(sk, flag))
2565 return;
2566
2567 /* C. Process data loss notification, provided it is valid. */
2568 if (tcp_is_fack(tp) && (flag & FLAG_DATA_LOST) &&
2569 before(tp->snd_una, tp->high_seq) &&
2570 icsk->icsk_ca_state != TCP_CA_Open &&
2571 tp->fackets_out > tp->reordering) {
2572 tcp_mark_head_lost(sk, tp->fackets_out - tp->reordering);
2573 NET_INC_STATS_BH(LINUX_MIB_TCPLOSS);
2574 }
2575
2576 /* D. Check consistency of the current state. */
2577 tcp_verify_left_out(tp);
2578
2579 /* E. Check state exit conditions. State can be terminated
2580 * when high_seq is ACKed. */
2581 if (icsk->icsk_ca_state == TCP_CA_Open) {
2582 BUG_TRAP(tp->retrans_out == 0);
2583 tp->retrans_stamp = 0;
2584 } else if (!before(tp->snd_una, tp->high_seq)) {
2585 switch (icsk->icsk_ca_state) {
2586 case TCP_CA_Loss:
2587 icsk->icsk_retransmits = 0;
2588 if (tcp_try_undo_recovery(sk))
2589 return;
2590 break;
2591
2592 case TCP_CA_CWR:
2593 /* CWR is to be held something *above* high_seq
2594 * is ACKed for CWR bit to reach receiver. */
2595 if (tp->snd_una != tp->high_seq) {
2596 tcp_complete_cwr(sk);
2597 tcp_set_ca_state(sk, TCP_CA_Open);
2598 }
2599 break;
2600
2601 case TCP_CA_Disorder:
2602 tcp_try_undo_dsack(sk);
2603 if (!tp->undo_marker ||
2604 /* For SACK case do not Open to allow to undo
2605 * catching for all duplicate ACKs. */
2606 tcp_is_reno(tp) || tp->snd_una != tp->high_seq) {
2607 tp->undo_marker = 0;
2608 tcp_set_ca_state(sk, TCP_CA_Open);
2609 }
2610 break;
2611
2612 case TCP_CA_Recovery:
2613 if (tcp_is_reno(tp))
2614 tcp_reset_reno_sack(tp);
2615 if (tcp_try_undo_recovery(sk))
2616 return;
2617 tcp_complete_cwr(sk);
2618 break;
2619 }
2620 }
2621
2622 /* F. Process state. */
2623 switch (icsk->icsk_ca_state) {
2624 case TCP_CA_Recovery:
2625 if (!(flag & FLAG_SND_UNA_ADVANCED)) {
2626 if (tcp_is_reno(tp) && is_dupack)
2627 tcp_add_reno_sack(sk);
2628 } else
2629 do_lost = tcp_try_undo_partial(sk, pkts_acked);
2630 break;
2631 case TCP_CA_Loss:
2632 if (flag & FLAG_DATA_ACKED)
2633 icsk->icsk_retransmits = 0;
2634 if (tcp_is_reno(tp) && flag & FLAG_SND_UNA_ADVANCED)
2635 tcp_reset_reno_sack(tp);
2636 if (!tcp_try_undo_loss(sk)) {
2637 tcp_moderate_cwnd(tp);
2638 tcp_xmit_retransmit_queue(sk);
2639 return;
2640 }
2641 if (icsk->icsk_ca_state != TCP_CA_Open)
2642 return;
2643 /* Loss is undone; fall through to processing in Open state. */
2644 default:
2645 if (tcp_is_reno(tp)) {
2646 if (flag & FLAG_SND_UNA_ADVANCED)
2647 tcp_reset_reno_sack(tp);
2648 if (is_dupack)
2649 tcp_add_reno_sack(sk);
2650 }
2651
2652 if (icsk->icsk_ca_state == TCP_CA_Disorder)
2653 tcp_try_undo_dsack(sk);
2654
2655 if (!tcp_time_to_recover(sk)) {
2656 tcp_try_to_open(sk, flag);
2657 return;
2658 }
2659
2660 /* MTU probe failure: don't reduce cwnd */
2661 if (icsk->icsk_ca_state < TCP_CA_CWR &&
2662 icsk->icsk_mtup.probe_size &&
2663 tp->snd_una == tp->mtu_probe.probe_seq_start) {
2664 tcp_mtup_probe_failed(sk);
2665 /* Restores the reduction we did in tcp_mtup_probe() */
2666 tp->snd_cwnd++;
2667 tcp_simple_retransmit(sk);
2668 return;
2669 }
2670
2671 /* Otherwise enter Recovery state */
2672
2673 if (tcp_is_reno(tp))
2674 NET_INC_STATS_BH(LINUX_MIB_TCPRENORECOVERY);
2675 else
2676 NET_INC_STATS_BH(LINUX_MIB_TCPSACKRECOVERY);
2677
2678 tp->high_seq = tp->snd_nxt;
2679 tp->prior_ssthresh = 0;
2680 tp->undo_marker = tp->snd_una;
2681 tp->undo_retrans = tp->retrans_out;
2682
2683 if (icsk->icsk_ca_state < TCP_CA_CWR) {
2684 if (!(flag & FLAG_ECE))
2685 tp->prior_ssthresh = tcp_current_ssthresh(sk);
2686 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
2687 TCP_ECN_queue_cwr(tp);
2688 }
2689
2690 tp->bytes_acked = 0;
2691 tp->snd_cwnd_cnt = 0;
2692 tcp_set_ca_state(sk, TCP_CA_Recovery);
2693 fast_rexmit = 1;
2694 }
2695
2696 if (do_lost || (tcp_is_fack(tp) && tcp_head_timedout(sk)))
2697 tcp_update_scoreboard(sk, fast_rexmit);
2698 tcp_cwnd_down(sk, flag);
2699 tcp_xmit_retransmit_queue(sk);
2700 }
2701
2702 /* Read draft-ietf-tcplw-high-performance before mucking
2703 * with this code. (Supersedes RFC1323)
2704 */
2705 static void tcp_ack_saw_tstamp(struct sock *sk, int flag)
2706 {
2707 /* RTTM Rule: A TSecr value received in a segment is used to
2708 * update the averaged RTT measurement only if the segment
2709 * acknowledges some new data, i.e., only if it advances the
2710 * left edge of the send window.
2711 *
2712 * See draft-ietf-tcplw-high-performance-00, section 3.3.
2713 * 1998/04/10 Andrey V. Savochkin <saw@msu.ru>
2714 *
2715 * Changed: reset backoff as soon as we see the first valid sample.
2716 * If we do not, we get strongly overestimated rto. With timestamps
2717 * samples are accepted even from very old segments: f.e., when rtt=1
2718 * increases to 8, we retransmit 5 times and after 8 seconds delayed
2719 * answer arrives rto becomes 120 seconds! If at least one of segments
2720 * in window is lost... Voila. --ANK (010210)
2721 */
2722 struct tcp_sock *tp = tcp_sk(sk);
2723 const __u32 seq_rtt = tcp_time_stamp - tp->rx_opt.rcv_tsecr;
2724 tcp_rtt_estimator(sk, seq_rtt);
2725 tcp_set_rto(sk);
2726 inet_csk(sk)->icsk_backoff = 0;
2727 tcp_bound_rto(sk);
2728 }
2729
2730 static void tcp_ack_no_tstamp(struct sock *sk, u32 seq_rtt, int flag)
2731 {
2732 /* We don't have a timestamp. Can only use
2733 * packets that are not retransmitted to determine
2734 * rtt estimates. Also, we must not reset the
2735 * backoff for rto until we get a non-retransmitted
2736 * packet. This allows us to deal with a situation
2737 * where the network delay has increased suddenly.
2738 * I.e. Karn's algorithm. (SIGCOMM '87, p5.)
2739 */
2740
2741 if (flag & FLAG_RETRANS_DATA_ACKED)
2742 return;
2743
2744 tcp_rtt_estimator(sk, seq_rtt);
2745 tcp_set_rto(sk);
2746 inet_csk(sk)->icsk_backoff = 0;
2747 tcp_bound_rto(sk);
2748 }
2749
2750 static inline void tcp_ack_update_rtt(struct sock *sk, const int flag,
2751 const s32 seq_rtt)
2752 {
2753 const struct tcp_sock *tp = tcp_sk(sk);
2754 /* Note that peer MAY send zero echo. In this case it is ignored. (rfc1323) */
2755 if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
2756 tcp_ack_saw_tstamp(sk, flag);
2757 else if (seq_rtt >= 0)
2758 tcp_ack_no_tstamp(sk, seq_rtt, flag);
2759 }
2760
2761 static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 in_flight)
2762 {
2763 const struct inet_connection_sock *icsk = inet_csk(sk);
2764 icsk->icsk_ca_ops->cong_avoid(sk, ack, in_flight);
2765 tcp_sk(sk)->snd_cwnd_stamp = tcp_time_stamp;
2766 }
2767
2768 /* Restart timer after forward progress on connection.
2769 * RFC2988 recommends to restart timer to now+rto.
2770 */
2771 static void tcp_rearm_rto(struct sock *sk)
2772 {
2773 struct tcp_sock *tp = tcp_sk(sk);
2774
2775 if (!tp->packets_out) {
2776 inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
2777 } else {
2778 inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
2779 inet_csk(sk)->icsk_rto, TCP_RTO_MAX);
2780 }
2781 }
2782
2783 /* If we get here, the whole TSO packet has not been acked. */
2784 static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb)
2785 {
2786 struct tcp_sock *tp = tcp_sk(sk);
2787 u32 packets_acked;
2788
2789 BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una));
2790
2791 packets_acked = tcp_skb_pcount(skb);
2792 if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
2793 return 0;
2794 packets_acked -= tcp_skb_pcount(skb);
2795
2796 if (packets_acked) {
2797 BUG_ON(tcp_skb_pcount(skb) == 0);
2798 BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq));
2799 }
2800
2801 return packets_acked;
2802 }
2803
2804 /* Remove acknowledged frames from the retransmission queue. If our packet
2805 * is before the ack sequence we can discard it as it's confirmed to have
2806 * arrived at the other end.
2807 */
2808 static int tcp_clean_rtx_queue(struct sock *sk, int prior_fackets)
2809 {
2810 struct tcp_sock *tp = tcp_sk(sk);
2811 const struct inet_connection_sock *icsk = inet_csk(sk);
2812 struct sk_buff *skb;
2813 u32 now = tcp_time_stamp;
2814 int fully_acked = 1;
2815 int flag = 0;
2816 u32 pkts_acked = 0;
2817 u32 reord = tp->packets_out;
2818 s32 seq_rtt = -1;
2819 s32 ca_seq_rtt = -1;
2820 ktime_t last_ackt = net_invalid_timestamp();
2821
2822 while ((skb = tcp_write_queue_head(sk)) && skb != tcp_send_head(sk)) {
2823 struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
2824 u32 end_seq;
2825 u32 acked_pcount;
2826 u8 sacked = scb->sacked;
2827
2828 /* Determine how many packets and what bytes were acked, tso and else */
2829 if (after(scb->end_seq, tp->snd_una)) {
2830 if (tcp_skb_pcount(skb) == 1 ||
2831 !after(tp->snd_una, scb->seq))
2832 break;
2833
2834 acked_pcount = tcp_tso_acked(sk, skb);
2835 if (!acked_pcount)
2836 break;
2837
2838 fully_acked = 0;
2839 end_seq = tp->snd_una;
2840 } else {
2841 acked_pcount = tcp_skb_pcount(skb);
2842 end_seq = scb->end_seq;
2843 }
2844
2845 /* MTU probing checks */
2846 if (fully_acked && icsk->icsk_mtup.probe_size &&
2847 !after(tp->mtu_probe.probe_seq_end, scb->end_seq)) {
2848 tcp_mtup_probe_success(sk, skb);
2849 }
2850
2851 if (sacked & TCPCB_RETRANS) {
2852 if (sacked & TCPCB_SACKED_RETRANS)
2853 tp->retrans_out -= acked_pcount;
2854 flag |= FLAG_RETRANS_DATA_ACKED;
2855 ca_seq_rtt = -1;
2856 seq_rtt = -1;
2857 if ((flag & FLAG_DATA_ACKED) || (acked_pcount > 1))
2858 flag |= FLAG_NONHEAD_RETRANS_ACKED;
2859 } else {
2860 ca_seq_rtt = now - scb->when;
2861 last_ackt = skb->tstamp;
2862 if (seq_rtt < 0) {
2863 seq_rtt = ca_seq_rtt;
2864 }
2865 if (!(sacked & TCPCB_SACKED_ACKED))
2866 reord = min(pkts_acked, reord);
2867 }
2868
2869 if (sacked & TCPCB_SACKED_ACKED)
2870 tp->sacked_out -= acked_pcount;
2871 if (sacked & TCPCB_LOST)
2872 tp->lost_out -= acked_pcount;
2873
2874 if (unlikely(tp->urg_mode && !before(end_seq, tp->snd_up)))
2875 tp->urg_mode = 0;
2876
2877 tp->packets_out -= acked_pcount;
2878 pkts_acked += acked_pcount;
2879
2880 /* Initial outgoing SYN's get put onto the write_queue
2881 * just like anything else we transmit. It is not
2882 * true data, and if we misinform our callers that
2883 * this ACK acks real data, we will erroneously exit
2884 * connection startup slow start one packet too
2885 * quickly. This is severely frowned upon behavior.
2886 */
2887 if (!(scb->flags & TCPCB_FLAG_SYN)) {
2888 flag |= FLAG_DATA_ACKED;
2889 } else {
2890 flag |= FLAG_SYN_ACKED;
2891 tp->retrans_stamp = 0;
2892 }
2893
2894 if (!fully_acked)
2895 break;
2896
2897 tcp_unlink_write_queue(skb, sk);
2898 sk_wmem_free_skb(sk, skb);
2899 tcp_clear_all_retrans_hints(tp);
2900 }
2901
2902 if (skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
2903 flag |= FLAG_SACK_RENEGING;
2904
2905 if (flag & FLAG_ACKED) {
2906 const struct tcp_congestion_ops *ca_ops
2907 = inet_csk(sk)->icsk_ca_ops;
2908
2909 tcp_ack_update_rtt(sk, flag, seq_rtt);
2910 tcp_rearm_rto(sk);
2911
2912 if (tcp_is_reno(tp)) {
2913 tcp_remove_reno_sacks(sk, pkts_acked);
2914 } else {
2915 /* Non-retransmitted hole got filled? That's reordering */
2916 if (reord < prior_fackets)
2917 tcp_update_reordering(sk, tp->fackets_out - reord, 0);
2918 }
2919
2920 tp->fackets_out -= min(pkts_acked, tp->fackets_out);
2921
2922 if (ca_ops->pkts_acked) {
2923 s32 rtt_us = -1;
2924
2925 /* Is the ACK triggering packet unambiguous? */
2926 if (!(flag & FLAG_RETRANS_DATA_ACKED)) {
2927 /* High resolution needed and available? */
2928 if (ca_ops->flags & TCP_CONG_RTT_STAMP &&
2929 !ktime_equal(last_ackt,
2930 net_invalid_timestamp()))
2931 rtt_us = ktime_us_delta(ktime_get_real(),
2932 last_ackt);
2933 else if (ca_seq_rtt > 0)
2934 rtt_us = jiffies_to_usecs(ca_seq_rtt);
2935 }
2936
2937 ca_ops->pkts_acked(sk, pkts_acked, rtt_us);
2938 }
2939 }
2940
2941 #if FASTRETRANS_DEBUG > 0
2942 BUG_TRAP((int)tp->sacked_out >= 0);
2943 BUG_TRAP((int)tp->lost_out >= 0);
2944 BUG_TRAP((int)tp->retrans_out >= 0);
2945 if (!tp->packets_out && tcp_is_sack(tp)) {
2946 icsk = inet_csk(sk);
2947 if (tp->lost_out) {
2948 printk(KERN_DEBUG "Leak l=%u %d\n",
2949 tp->lost_out, icsk->icsk_ca_state);
2950 tp->lost_out = 0;
2951 }
2952 if (tp->sacked_out) {
2953 printk(KERN_DEBUG "Leak s=%u %d\n",
2954 tp->sacked_out, icsk->icsk_ca_state);
2955 tp->sacked_out = 0;
2956 }
2957 if (tp->retrans_out) {
2958 printk(KERN_DEBUG "Leak r=%u %d\n",
2959 tp->retrans_out, icsk->icsk_ca_state);
2960 tp->retrans_out = 0;
2961 }
2962 }
2963 #endif
2964 return flag;
2965 }
2966
2967 static void tcp_ack_probe(struct sock *sk)
2968 {
2969 const struct tcp_sock *tp = tcp_sk(sk);
2970 struct inet_connection_sock *icsk = inet_csk(sk);
2971
2972 /* Was it a usable window open? */
2973
2974 if (!after(TCP_SKB_CB(tcp_send_head(sk))->end_seq, tcp_wnd_end(tp))) {
2975 icsk->icsk_backoff = 0;
2976 inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0);
2977 /* Socket must be waked up by subsequent tcp_data_snd_check().
2978 * This function is not for random using!
2979 */
2980 } else {
2981 inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0,
2982 min(icsk->icsk_rto << icsk->icsk_backoff, TCP_RTO_MAX),
2983 TCP_RTO_MAX);
2984 }
2985 }
2986
2987 static inline int tcp_ack_is_dubious(const struct sock *sk, const int flag)
2988 {
2989 return (!(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
2990 inet_csk(sk)->icsk_ca_state != TCP_CA_Open);
2991 }
2992
2993 static inline int tcp_may_raise_cwnd(const struct sock *sk, const int flag)
2994 {
2995 const struct tcp_sock *tp = tcp_sk(sk);
2996 return (!(flag & FLAG_ECE) || tp->snd_cwnd < tp->snd_ssthresh) &&
2997 !((1 << inet_csk(sk)->icsk_ca_state) & (TCPF_CA_Recovery | TCPF_CA_CWR));
2998 }
2999
3000 /* Check that window update is acceptable.
3001 * The function assumes that snd_una<=ack<=snd_next.
3002 */
3003 static inline int tcp_may_update_window(const struct tcp_sock *tp,
3004 const u32 ack, const u32 ack_seq,
3005 const u32 nwin)
3006 {
3007 return (after(ack, tp->snd_una) ||
3008 after(ack_seq, tp->snd_wl1) ||
3009 (ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd));
3010 }
3011
3012 /* Update our send window.
3013 *
3014 * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
3015 * and in FreeBSD. NetBSD's one is even worse.) is wrong.
3016 */
3017 static int tcp_ack_update_window(struct sock *sk, struct sk_buff *skb, u32 ack,
3018 u32 ack_seq)
3019 {
3020 struct tcp_sock *tp = tcp_sk(sk);
3021 int flag = 0;
3022 u32 nwin = ntohs(tcp_hdr(skb)->window);
3023
3024 if (likely(!tcp_hdr(skb)->syn))
3025 nwin <<= tp->rx_opt.snd_wscale;
3026
3027 if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
3028 flag |= FLAG_WIN_UPDATE;
3029 tcp_update_wl(tp, ack, ack_seq);
3030
3031 if (tp->snd_wnd != nwin) {
3032 tp->snd_wnd = nwin;
3033
3034 /* Note, it is the only place, where
3035 * fast path is recovered for sending TCP.
3036 */
3037 tp->pred_flags = 0;
3038 tcp_fast_path_check(sk);
3039
3040 if (nwin > tp->max_window) {
3041 tp->max_window = nwin;
3042 tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie);
3043 }
3044 }
3045 }
3046
3047 tp->snd_una = ack;
3048
3049 return flag;
3050 }
3051
3052 /* A very conservative spurious RTO response algorithm: reduce cwnd and
3053 * continue in congestion avoidance.
3054 */
3055 static void tcp_conservative_spur_to_response(struct tcp_sock *tp)
3056 {
3057 tp->snd_cwnd = min(tp->snd_cwnd, tp->snd_ssthresh);
3058 tp->snd_cwnd_cnt = 0;
3059 tp->bytes_acked = 0;
3060 TCP_ECN_queue_cwr(tp);
3061 tcp_moderate_cwnd(tp);
3062 }
3063
3064 /* A conservative spurious RTO response algorithm: reduce cwnd using
3065 * rate halving and continue in congestion avoidance.
3066 */
3067 static void tcp_ratehalving_spur_to_response(struct sock *sk)
3068 {
3069 tcp_enter_cwr(sk, 0);
3070 }
3071
3072 static void tcp_undo_spur_to_response(struct sock *sk, int flag)
3073 {
3074 if (flag & FLAG_ECE)
3075 tcp_ratehalving_spur_to_response(sk);
3076 else
3077 tcp_undo_cwr(sk, 1);
3078 }
3079
3080 /* F-RTO spurious RTO detection algorithm (RFC4138)
3081 *
3082 * F-RTO affects during two new ACKs following RTO (well, almost, see inline
3083 * comments). State (ACK number) is kept in frto_counter. When ACK advances
3084 * window (but not to or beyond highest sequence sent before RTO):
3085 * On First ACK, send two new segments out.
3086 * On Second ACK, RTO was likely spurious. Do spurious response (response
3087 * algorithm is not part of the F-RTO detection algorithm
3088 * given in RFC4138 but can be selected separately).
3089 * Otherwise (basically on duplicate ACK), RTO was (likely) caused by a loss
3090 * and TCP falls back to conventional RTO recovery. F-RTO allows overriding
3091 * of Nagle, this is done using frto_counter states 2 and 3, when a new data
3092 * segment of any size sent during F-RTO, state 2 is upgraded to 3.
3093 *
3094 * Rationale: if the RTO was spurious, new ACKs should arrive from the
3095 * original window even after we transmit two new data segments.
3096 *
3097 * SACK version:
3098 * on first step, wait until first cumulative ACK arrives, then move to
3099 * the second step. In second step, the next ACK decides.
3100 *
3101 * F-RTO is implemented (mainly) in four functions:
3102 * - tcp_use_frto() is used to determine if TCP is can use F-RTO
3103 * - tcp_enter_frto() prepares TCP state on RTO if F-RTO is used, it is
3104 * called when tcp_use_frto() showed green light
3105 * - tcp_process_frto() handles incoming ACKs during F-RTO algorithm
3106 * - tcp_enter_frto_loss() is called if there is not enough evidence
3107 * to prove that the RTO is indeed spurious. It transfers the control
3108 * from F-RTO to the conventional RTO recovery
3109 */
3110 static int tcp_process_frto(struct sock *sk, int flag)
3111 {
3112 struct tcp_sock *tp = tcp_sk(sk);
3113
3114 tcp_verify_left_out(tp);
3115
3116 /* Duplicate the behavior from Loss state (fastretrans_alert) */
3117 if (flag & FLAG_DATA_ACKED)
3118 inet_csk(sk)->icsk_retransmits = 0;
3119
3120 if ((flag & FLAG_NONHEAD_RETRANS_ACKED) ||
3121 ((tp->frto_counter >= 2) && (flag & FLAG_RETRANS_DATA_ACKED)))
3122 tp->undo_marker = 0;
3123
3124 if (!before(tp->snd_una, tp->frto_highmark)) {
3125 tcp_enter_frto_loss(sk, (tp->frto_counter == 1 ? 2 : 3), flag);
3126 return 1;
3127 }
3128
3129 if (!tcp_is_sackfrto(tp)) {
3130 /* RFC4138 shortcoming in step 2; should also have case c):
3131 * ACK isn't duplicate nor advances window, e.g., opposite dir
3132 * data, winupdate
3133 */
3134 if (!(flag & FLAG_ANY_PROGRESS) && (flag & FLAG_NOT_DUP))
3135 return 1;
3136
3137 if (!(flag & FLAG_DATA_ACKED)) {
3138 tcp_enter_frto_loss(sk, (tp->frto_counter == 1 ? 0 : 3),
3139 flag);
3140 return 1;
3141 }
3142 } else {
3143 if (!(flag & FLAG_DATA_ACKED) && (tp->frto_counter == 1)) {
3144 /* Prevent sending of new data. */
3145 tp->snd_cwnd = min(tp->snd_cwnd,
3146 tcp_packets_in_flight(tp));
3147 return 1;
3148 }
3149
3150 if ((tp->frto_counter >= 2) &&
3151 (!(flag & FLAG_FORWARD_PROGRESS) ||
3152 ((flag & FLAG_DATA_SACKED) &&
3153 !(flag & FLAG_ONLY_ORIG_SACKED)))) {
3154 /* RFC4138 shortcoming (see comment above) */
3155 if (!(flag & FLAG_FORWARD_PROGRESS) &&
3156 (flag & FLAG_NOT_DUP))
3157 return 1;
3158
3159 tcp_enter_frto_loss(sk, 3, flag);
3160 return 1;
3161 }
3162 }
3163
3164 if (tp->frto_counter == 1) {
3165 /* tcp_may_send_now needs to see updated state */
3166 tp->snd_cwnd = tcp_packets_in_flight(tp) + 2;
3167 tp->frto_counter = 2;
3168
3169 if (!tcp_may_send_now(sk))
3170 tcp_enter_frto_loss(sk, 2, flag);
3171
3172 return 1;
3173 } else {
3174 switch (sysctl_tcp_frto_response) {
3175 case 2:
3176 tcp_undo_spur_to_response(sk, flag);
3177 break;
3178 case 1:
3179 tcp_conservative_spur_to_response(tp);
3180 break;
3181 default:
3182 tcp_ratehalving_spur_to_response(sk);
3183 break;
3184 }
3185 tp->frto_counter = 0;
3186 tp->undo_marker = 0;
3187 NET_INC_STATS_BH(LINUX_MIB_TCPSPURIOUSRTOS);
3188 }
3189 return 0;
3190 }
3191
3192 /* This routine deals with incoming acks, but not outgoing ones. */
3193 static int tcp_ack(struct sock *sk, struct sk_buff *skb, int flag)
3194 {
3195 struct inet_connection_sock *icsk = inet_csk(sk);
3196 struct tcp_sock *tp = tcp_sk(sk);
3197 u32 prior_snd_una = tp->snd_una;
3198 u32 ack_seq = TCP_SKB_CB(skb)->seq;
3199 u32 ack = TCP_SKB_CB(skb)->ack_seq;
3200 u32 prior_in_flight;
3201 u32 prior_fackets;
3202 int prior_packets;
3203 int frto_cwnd = 0;
3204
3205 /* If the ack is newer than sent or older than previous acks
3206 * then we can probably ignore it.
3207 */
3208 if (after(ack, tp->snd_nxt))
3209 goto uninteresting_ack;
3210
3211 if (before(ack, prior_snd_una))
3212 goto old_ack;
3213
3214 if (after(ack, prior_snd_una))
3215 flag |= FLAG_SND_UNA_ADVANCED;
3216
3217 if (sysctl_tcp_abc) {
3218 if (icsk->icsk_ca_state < TCP_CA_CWR)
3219 tp->bytes_acked += ack - prior_snd_una;
3220 else if (icsk->icsk_ca_state == TCP_CA_Loss)
3221 /* we assume just one segment left network */
3222 tp->bytes_acked += min(ack - prior_snd_una,
3223 tp->mss_cache);
3224 }
3225
3226 prior_fackets = tp->fackets_out;
3227 prior_in_flight = tcp_packets_in_flight(tp);
3228
3229 if (!(flag & FLAG_SLOWPATH) && after(ack, prior_snd_una)) {
3230 /* Window is constant, pure forward advance.
3231 * No more checks are required.
3232 * Note, we use the fact that SND.UNA>=SND.WL2.
3233 */
3234 tcp_update_wl(tp, ack, ack_seq);
3235 tp->snd_una = ack;
3236 flag |= FLAG_WIN_UPDATE;
3237
3238 tcp_ca_event(sk, CA_EVENT_FAST_ACK);
3239
3240 NET_INC_STATS_BH(LINUX_MIB_TCPHPACKS);
3241 } else {
3242 if (ack_seq != TCP_SKB_CB(skb)->end_seq)
3243 flag |= FLAG_DATA;
3244 else
3245 NET_INC_STATS_BH(LINUX_MIB_TCPPUREACKS);
3246
3247 flag |= tcp_ack_update_window(sk, skb, ack, ack_seq);
3248
3249 if (TCP_SKB_CB(skb)->sacked)
3250 flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una);
3251
3252 if (TCP_ECN_rcv_ecn_echo(tp, tcp_hdr(skb)))
3253 flag |= FLAG_ECE;
3254
3255 tcp_ca_event(sk, CA_EVENT_SLOW_ACK);
3256 }
3257
3258 /* We passed data and got it acked, remove any soft error
3259 * log. Something worked...
3260 */
3261 sk->sk_err_soft = 0;
3262 tp->rcv_tstamp = tcp_time_stamp;
3263 prior_packets = tp->packets_out;
3264 if (!prior_packets)
3265 goto no_queue;
3266
3267 /* See if we can take anything off of the retransmit queue. */
3268 flag |= tcp_clean_rtx_queue(sk, prior_fackets);
3269
3270 if (tp->frto_counter)
3271 frto_cwnd = tcp_process_frto(sk, flag);
3272 /* Guarantee sacktag reordering detection against wrap-arounds */
3273 if (before(tp->frto_highmark, tp->snd_una))
3274 tp->frto_highmark = 0;
3275
3276 if (tcp_ack_is_dubious(sk, flag)) {
3277 /* Advance CWND, if state allows this. */
3278 if ((flag & FLAG_DATA_ACKED) && !frto_cwnd &&
3279 tcp_may_raise_cwnd(sk, flag))
3280 tcp_cong_avoid(sk, ack, prior_in_flight);
3281 tcp_fastretrans_alert(sk, prior_packets - tp->packets_out,
3282 flag);
3283 } else {
3284 if ((flag & FLAG_DATA_ACKED) && !frto_cwnd)
3285 tcp_cong_avoid(sk, ack, prior_in_flight);
3286 }
3287
3288 if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP))
3289 dst_confirm(sk->sk_dst_cache);
3290
3291 return 1;
3292
3293 no_queue:
3294 icsk->icsk_probes_out = 0;
3295
3296 /* If this ack opens up a zero window, clear backoff. It was
3297 * being used to time the probes, and is probably far higher than
3298 * it needs to be for normal retransmission.
3299 */
3300 if (tcp_send_head(sk))
3301 tcp_ack_probe(sk);
3302 return 1;
3303
3304 old_ack:
3305 if (TCP_SKB_CB(skb)->sacked) {
3306 tcp_sacktag_write_queue(sk, skb, prior_snd_una);
3307 if (icsk->icsk_ca_state == TCP_CA_Open)
3308 tcp_try_keep_open(sk);
3309 }
3310
3311 uninteresting_ack:
3312 SOCK_DEBUG(sk, "Ack %u out of %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
3313 return 0;
3314 }
3315
3316 /* Look for tcp options. Normally only called on SYN and SYNACK packets.
3317 * But, this can also be called on packets in the established flow when
3318 * the fast version below fails.
3319 */
3320 void tcp_parse_options(struct sk_buff *skb, struct tcp_options_received *opt_rx,
3321 int estab)
3322 {
3323 unsigned char *ptr;
3324 struct tcphdr *th = tcp_hdr(skb);
3325 int length = (th->doff * 4) - sizeof(struct tcphdr);
3326
3327 ptr = (unsigned char *)(th + 1);
3328 opt_rx->saw_tstamp = 0;
3329
3330 while (length > 0) {
3331 int opcode = *ptr++;
3332 int opsize;
3333
3334 switch (opcode) {
3335 case TCPOPT_EOL:
3336 return;
3337 case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */
3338 length--;
3339 continue;
3340 default:
3341 opsize = *ptr++;
3342 if (opsize < 2) /* "silly options" */
3343 return;
3344 if (opsize > length)
3345 return; /* don't parse partial options */
3346 switch (opcode) {
3347 case TCPOPT_MSS:
3348 if (opsize == TCPOLEN_MSS && th->syn && !estab) {
3349 u16 in_mss = ntohs(get_unaligned((__be16 *)ptr));
3350 if (in_mss) {
3351 if (opt_rx->user_mss &&
3352 opt_rx->user_mss < in_mss)
3353 in_mss = opt_rx->user_mss;
3354 opt_rx->mss_clamp = in_mss;
3355 }
3356 }
3357 break;
3358 case TCPOPT_WINDOW:
3359 if (opsize == TCPOLEN_WINDOW && th->syn &&
3360 !estab && sysctl_tcp_window_scaling) {
3361 __u8 snd_wscale = *(__u8 *)ptr;
3362 opt_rx->wscale_ok = 1;
3363 if (snd_wscale > 14) {
3364 if (net_ratelimit())
3365 printk(KERN_INFO "tcp_parse_options: Illegal window "
3366 "scaling value %d >14 received.\n",
3367 snd_wscale);
3368 snd_wscale = 14;
3369 }
3370 opt_rx->snd_wscale = snd_wscale;
3371 }
3372 break;
3373 case TCPOPT_TIMESTAMP:
3374 if ((opsize == TCPOLEN_TIMESTAMP) &&
3375 ((estab && opt_rx->tstamp_ok) ||
3376 (!estab && sysctl_tcp_timestamps))) {
3377 opt_rx->saw_tstamp = 1;
3378 opt_rx->rcv_tsval = ntohl(get_unaligned((__be32 *)ptr));
3379 opt_rx->rcv_tsecr = ntohl(get_unaligned((__be32 *)(ptr+4)));
3380 }
3381 break;
3382 case TCPOPT_SACK_PERM:
3383 if (opsize == TCPOLEN_SACK_PERM && th->syn &&
3384 !estab && sysctl_tcp_sack) {
3385 opt_rx->sack_ok = 1;
3386 tcp_sack_reset(opt_rx);
3387 }
3388 break;
3389
3390 case TCPOPT_SACK:
3391 if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
3392 !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
3393 opt_rx->sack_ok) {
3394 TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
3395 }
3396 break;
3397 #ifdef CONFIG_TCP_MD5SIG
3398 case TCPOPT_MD5SIG:
3399 /*
3400 * The MD5 Hash has already been
3401 * checked (see tcp_v{4,6}_do_rcv()).
3402 */
3403 break;
3404 #endif
3405 }
3406
3407 ptr += opsize-2;
3408 length -= opsize;
3409 }
3410 }
3411 }
3412
3413 /* Fast parse options. This hopes to only see timestamps.
3414 * If it is wrong it falls back on tcp_parse_options().
3415 */
3416 static int tcp_fast_parse_options(struct sk_buff *skb, struct tcphdr *th,
3417 struct tcp_sock *tp)
3418 {
3419 if (th->doff == sizeof(struct tcphdr) >> 2) {
3420 tp->rx_opt.saw_tstamp = 0;
3421 return 0;
3422 } else if (tp->rx_opt.tstamp_ok &&
3423 th->doff == (sizeof(struct tcphdr)>>2)+(TCPOLEN_TSTAMP_ALIGNED>>2)) {
3424 __be32 *ptr = (__be32 *)(th + 1);
3425 if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
3426 | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
3427 tp->rx_opt.saw_tstamp = 1;
3428 ++ptr;
3429 tp->rx_opt.rcv_tsval = ntohl(*ptr);
3430 ++ptr;
3431 tp->rx_opt.rcv_tsecr = ntohl(*ptr);
3432 return 1;
3433 }
3434 }
3435 tcp_parse_options(skb, &tp->rx_opt, 1);
3436 return 1;
3437 }
3438
3439 static inline void tcp_store_ts_recent(struct tcp_sock *tp)
3440 {
3441 tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval;
3442 tp->rx_opt.ts_recent_stamp = get_seconds();
3443 }
3444
3445 static inline void tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq)
3446 {
3447 if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) {
3448 /* PAWS bug workaround wrt. ACK frames, the PAWS discard
3449 * extra check below makes sure this can only happen
3450 * for pure ACK frames. -DaveM
3451 *
3452 * Not only, also it occurs for expired timestamps.
3453 */
3454
3455 if ((s32)(tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent) >= 0 ||
3456 get_seconds() >= tp->rx_opt.ts_recent_stamp + TCP_PAWS_24DAYS)
3457 tcp_store_ts_recent(tp);
3458 }
3459 }
3460
3461 /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
3462 *
3463 * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
3464 * it can pass through stack. So, the following predicate verifies that
3465 * this segment is not used for anything but congestion avoidance or
3466 * fast retransmit. Moreover, we even are able to eliminate most of such
3467 * second order effects, if we apply some small "replay" window (~RTO)
3468 * to timestamp space.
3469 *
3470 * All these measures still do not guarantee that we reject wrapped ACKs
3471 * on networks with high bandwidth, when sequence space is recycled fastly,
3472 * but it guarantees that such events will be very rare and do not affect
3473 * connection seriously. This doesn't look nice, but alas, PAWS is really
3474 * buggy extension.
3475 *
3476 * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
3477 * states that events when retransmit arrives after original data are rare.
3478 * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
3479 * the biggest problem on large power networks even with minor reordering.
3480 * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
3481 * up to bandwidth of 18Gigabit/sec. 8) ]
3482 */
3483
3484 static int tcp_disordered_ack(const struct sock *sk, const struct sk_buff *skb)
3485 {
3486 struct tcp_sock *tp = tcp_sk(sk);
3487 struct tcphdr *th = tcp_hdr(skb);
3488 u32 seq = TCP_SKB_CB(skb)->seq;
3489 u32 ack = TCP_SKB_CB(skb)->ack_seq;
3490
3491 return (/* 1. Pure ACK with correct sequence number. */
3492 (th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
3493
3494 /* 2. ... and duplicate ACK. */
3495 ack == tp->snd_una &&
3496
3497 /* 3. ... and does not update window. */
3498 !tcp_may_update_window(tp, ack, seq, ntohs(th->window) << tp->rx_opt.snd_wscale) &&
3499
3500 /* 4. ... and sits in replay window. */
3501 (s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) <= (inet_csk(sk)->icsk_rto * 1024) / HZ);
3502 }
3503
3504 static inline int tcp_paws_discard(const struct sock *sk,
3505 const struct sk_buff *skb)
3506 {
3507 const struct tcp_sock *tp = tcp_sk(sk);
3508 return ((s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) > TCP_PAWS_WINDOW &&
3509 get_seconds() < tp->rx_opt.ts_recent_stamp + TCP_PAWS_24DAYS &&
3510 !tcp_disordered_ack(sk, skb));
3511 }
3512
3513 /* Check segment sequence number for validity.
3514 *
3515 * Segment controls are considered valid, if the segment
3516 * fits to the window after truncation to the window. Acceptability
3517 * of data (and SYN, FIN, of course) is checked separately.
3518 * See tcp_data_queue(), for example.
3519 *
3520 * Also, controls (RST is main one) are accepted using RCV.WUP instead
3521 * of RCV.NXT. Peer still did not advance his SND.UNA when we
3522 * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
3523 * (borrowed from freebsd)
3524 */
3525
3526 static inline int tcp_sequence(struct tcp_sock *tp, u32 seq, u32 end_seq)
3527 {
3528 return !before(end_seq, tp->rcv_wup) &&
3529 !after(seq, tp->rcv_nxt + tcp_receive_window(tp));
3530 }
3531
3532 /* When we get a reset we do this. */
3533 static void tcp_reset(struct sock *sk)
3534 {
3535 /* We want the right error as BSD sees it (and indeed as we do). */
3536 switch (sk->sk_state) {
3537 case TCP_SYN_SENT:
3538 sk->sk_err = ECONNREFUSED;
3539 break;
3540 case TCP_CLOSE_WAIT:
3541 sk->sk_err = EPIPE;
3542 break;
3543 case TCP_CLOSE:
3544 return;
3545 default:
3546 sk->sk_err = ECONNRESET;
3547 }
3548
3549 if (!sock_flag(sk, SOCK_DEAD))
3550 sk->sk_error_report(sk);
3551
3552 tcp_done(sk);
3553 }
3554
3555 /*
3556 * Process the FIN bit. This now behaves as it is supposed to work
3557 * and the FIN takes effect when it is validly part of sequence
3558 * space. Not before when we get holes.
3559 *
3560 * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
3561 * (and thence onto LAST-ACK and finally, CLOSE, we never enter
3562 * TIME-WAIT)
3563 *
3564 * If we are in FINWAIT-1, a received FIN indicates simultaneous
3565 * close and we go into CLOSING (and later onto TIME-WAIT)
3566 *
3567 * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
3568 */
3569 static void tcp_fin(struct sk_buff *skb, struct sock *sk, struct tcphdr *th)
3570 {
3571 struct tcp_sock *tp = tcp_sk(sk);
3572
3573 inet_csk_schedule_ack(sk);
3574
3575 sk->sk_shutdown |= RCV_SHUTDOWN;
3576 sock_set_flag(sk, SOCK_DONE);
3577
3578 switch (sk->sk_state) {
3579 case TCP_SYN_RECV:
3580 case TCP_ESTABLISHED:
3581 /* Move to CLOSE_WAIT */
3582 tcp_set_state(sk, TCP_CLOSE_WAIT);
3583 inet_csk(sk)->icsk_ack.pingpong = 1;
3584 break;
3585
3586 case TCP_CLOSE_WAIT:
3587 case TCP_CLOSING:
3588 /* Received a retransmission of the FIN, do
3589 * nothing.
3590 */
3591 break;
3592 case TCP_LAST_ACK:
3593 /* RFC793: Remain in the LAST-ACK state. */
3594 break;
3595
3596 case TCP_FIN_WAIT1:
3597 /* This case occurs when a simultaneous close
3598 * happens, we must ack the received FIN and
3599 * enter the CLOSING state.
3600 */
3601 tcp_send_ack(sk);
3602 tcp_set_state(sk, TCP_CLOSING);
3603 break;
3604 case TCP_FIN_WAIT2:
3605 /* Received a FIN -- send ACK and enter TIME_WAIT. */
3606 tcp_send_ack(sk);
3607 tcp_time_wait(sk, TCP_TIME_WAIT, 0);
3608 break;
3609 default:
3610 /* Only TCP_LISTEN and TCP_CLOSE are left, in these
3611 * cases we should never reach this piece of code.
3612 */
3613 printk(KERN_ERR "%s: Impossible, sk->sk_state=%d\n",
3614 __FUNCTION__, sk->sk_state);
3615 break;
3616 }
3617
3618 /* It _is_ possible, that we have something out-of-order _after_ FIN.
3619 * Probably, we should reset in this case. For now drop them.
3620 */
3621 __skb_queue_purge(&tp->out_of_order_queue);
3622 if (tcp_is_sack(tp))
3623 tcp_sack_reset(&tp->rx_opt);
3624 sk_mem_reclaim(sk);
3625
3626 if (!sock_flag(sk, SOCK_DEAD)) {
3627 sk->sk_state_change(sk);
3628
3629 /* Do not send POLL_HUP for half duplex close. */
3630 if (sk->sk_shutdown == SHUTDOWN_MASK ||
3631 sk->sk_state == TCP_CLOSE)
3632 sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
3633 else
3634 sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
3635 }
3636 }
3637
3638 static inline int tcp_sack_extend(struct tcp_sack_block *sp, u32 seq,
3639 u32 end_seq)
3640 {
3641 if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
3642 if (before(seq, sp->start_seq))
3643 sp->start_seq = seq;
3644 if (after(end_seq, sp->end_seq))
3645 sp->end_seq = end_seq;
3646 return 1;
3647 }
3648 return 0;
3649 }
3650
3651 static void tcp_dsack_set(struct tcp_sock *tp, u32 seq, u32 end_seq)
3652 {
3653 if (tcp_is_sack(tp) && sysctl_tcp_dsack) {
3654 if (before(seq, tp->rcv_nxt))
3655 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKOLDSENT);
3656 else
3657 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKOFOSENT);
3658
3659 tp->rx_opt.dsack = 1;
3660 tp->duplicate_sack[0].start_seq = seq;
3661 tp->duplicate_sack[0].end_seq = end_seq;
3662 tp->rx_opt.eff_sacks = min(tp->rx_opt.num_sacks + 1,
3663 4 - tp->rx_opt.tstamp_ok);
3664 }
3665 }
3666
3667 static void tcp_dsack_extend(struct tcp_sock *tp, u32 seq, u32 end_seq)
3668 {
3669 if (!tp->rx_opt.dsack)
3670 tcp_dsack_set(tp, seq, end_seq);
3671 else
3672 tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
3673 }
3674
3675 static void tcp_send_dupack(struct sock *sk, struct sk_buff *skb)
3676 {
3677 struct tcp_sock *tp = tcp_sk(sk);
3678
3679 if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
3680 before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
3681 NET_INC_STATS_BH(LINUX_MIB_DELAYEDACKLOST);
3682 tcp_enter_quickack_mode(sk);
3683
3684 if (tcp_is_sack(tp) && sysctl_tcp_dsack) {
3685 u32 end_seq = TCP_SKB_CB(skb)->end_seq;
3686
3687 if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
3688 end_seq = tp->rcv_nxt;
3689 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, end_seq);
3690 }
3691 }
3692
3693 tcp_send_ack(sk);
3694 }
3695
3696 /* These routines update the SACK block as out-of-order packets arrive or
3697 * in-order packets close up the sequence space.
3698 */
3699 static void tcp_sack_maybe_coalesce(struct tcp_sock *tp)
3700 {
3701 int this_sack;
3702 struct tcp_sack_block *sp = &tp->selective_acks[0];
3703 struct tcp_sack_block *swalk = sp + 1;
3704
3705 /* See if the recent change to the first SACK eats into
3706 * or hits the sequence space of other SACK blocks, if so coalesce.
3707 */
3708 for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) {
3709 if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
3710 int i;
3711
3712 /* Zap SWALK, by moving every further SACK up by one slot.
3713 * Decrease num_sacks.
3714 */
3715 tp->rx_opt.num_sacks--;
3716 tp->rx_opt.eff_sacks = min(tp->rx_opt.num_sacks +
3717 tp->rx_opt.dsack,
3718 4 - tp->rx_opt.tstamp_ok);
3719 for (i = this_sack; i < tp->rx_opt.num_sacks; i++)
3720 sp[i] = sp[i + 1];
3721 continue;
3722 }
3723 this_sack++, swalk++;
3724 }
3725 }
3726
3727 static inline void tcp_sack_swap(struct tcp_sack_block *sack1,
3728 struct tcp_sack_block *sack2)
3729 {
3730 __u32 tmp;
3731
3732 tmp = sack1->start_seq;
3733 sack1->start_seq = sack2->start_seq;
3734 sack2->start_seq = tmp;
3735
3736 tmp = sack1->end_seq;
3737 sack1->end_seq = sack2->end_seq;
3738 sack2->end_seq = tmp;
3739 }
3740
3741 static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
3742 {
3743 struct tcp_sock *tp = tcp_sk(sk);
3744 struct tcp_sack_block *sp = &tp->selective_acks[0];
3745 int cur_sacks = tp->rx_opt.num_sacks;
3746 int this_sack;
3747
3748 if (!cur_sacks)
3749 goto new_sack;
3750
3751 for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) {
3752 if (tcp_sack_extend(sp, seq, end_seq)) {
3753 /* Rotate this_sack to the first one. */
3754 for (; this_sack > 0; this_sack--, sp--)
3755 tcp_sack_swap(sp, sp - 1);
3756 if (cur_sacks > 1)
3757 tcp_sack_maybe_coalesce(tp);
3758 return;
3759 }
3760 }
3761
3762 /* Could not find an adjacent existing SACK, build a new one,
3763 * put it at the front, and shift everyone else down. We
3764 * always know there is at least one SACK present already here.
3765 *
3766 * If the sack array is full, forget about the last one.
3767 */
3768 if (this_sack >= 4) {
3769 this_sack--;
3770 tp->rx_opt.num_sacks--;
3771 sp--;
3772 }
3773 for (; this_sack > 0; this_sack--, sp--)
3774 *sp = *(sp - 1);
3775
3776 new_sack:
3777 /* Build the new head SACK, and we're done. */
3778 sp->start_seq = seq;
3779 sp->end_seq = end_seq;
3780 tp->rx_opt.num_sacks++;
3781 tp->rx_opt.eff_sacks = min(tp->rx_opt.num_sacks + tp->rx_opt.dsack,
3782 4 - tp->rx_opt.tstamp_ok);
3783 }
3784
3785 /* RCV.NXT advances, some SACKs should be eaten. */
3786
3787 static void tcp_sack_remove(struct tcp_sock *tp)
3788 {
3789 struct tcp_sack_block *sp = &tp->selective_acks[0];
3790 int num_sacks = tp->rx_opt.num_sacks;
3791 int this_sack;
3792
3793 /* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
3794 if (skb_queue_empty(&tp->out_of_order_queue)) {
3795 tp->rx_opt.num_sacks = 0;
3796 tp->rx_opt.eff_sacks = tp->rx_opt.dsack;
3797 return;
3798 }
3799
3800 for (this_sack = 0; this_sack < num_sacks;) {
3801 /* Check if the start of the sack is covered by RCV.NXT. */
3802 if (!before(tp->rcv_nxt, sp->start_seq)) {
3803 int i;
3804
3805 /* RCV.NXT must cover all the block! */
3806 BUG_TRAP(!before(tp->rcv_nxt, sp->end_seq));
3807
3808 /* Zap this SACK, by moving forward any other SACKS. */
3809 for (i=this_sack+1; i < num_sacks; i++)
3810 tp->selective_acks[i-1] = tp->selective_acks[i];
3811 num_sacks--;
3812 continue;
3813 }
3814 this_sack++;
3815 sp++;
3816 }
3817 if (num_sacks != tp->rx_opt.num_sacks) {
3818 tp->rx_opt.num_sacks = num_sacks;
3819 tp->rx_opt.eff_sacks = min(tp->rx_opt.num_sacks +
3820 tp->rx_opt.dsack,
3821 4 - tp->rx_opt.tstamp_ok);
3822 }
3823 }
3824
3825 /* This one checks to see if we can put data from the
3826 * out_of_order queue into the receive_queue.
3827 */
3828 static void tcp_ofo_queue(struct sock *sk)
3829 {
3830 struct tcp_sock *tp = tcp_sk(sk);
3831 __u32 dsack_high = tp->rcv_nxt;
3832 struct sk_buff *skb;
3833
3834 while ((skb = skb_peek(&tp->out_of_order_queue)) != NULL) {
3835 if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
3836 break;
3837
3838 if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
3839 __u32 dsack = dsack_high;
3840 if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
3841 dsack_high = TCP_SKB_CB(skb)->end_seq;
3842 tcp_dsack_extend(tp, TCP_SKB_CB(skb)->seq, dsack);
3843 }
3844
3845 if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
3846 SOCK_DEBUG(sk, "ofo packet was already received \n");
3847 __skb_unlink(skb, &tp->out_of_order_queue);
3848 __kfree_skb(skb);
3849 continue;
3850 }
3851 SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n",
3852 tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
3853 TCP_SKB_CB(skb)->end_seq);
3854
3855 __skb_unlink(skb, &tp->out_of_order_queue);
3856 __skb_queue_tail(&sk->sk_receive_queue, skb);
3857 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
3858 if (tcp_hdr(skb)->fin)
3859 tcp_fin(skb, sk, tcp_hdr(skb));
3860 }
3861 }
3862
3863 static int tcp_prune_ofo_queue(struct sock *sk);
3864 static int tcp_prune_queue(struct sock *sk);
3865
3866 static inline int tcp_try_rmem_schedule(struct sock *sk, unsigned int size)
3867 {
3868 if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
3869 !sk_rmem_schedule(sk, size)) {
3870
3871 if (tcp_prune_queue(sk) < 0)
3872 return -1;
3873
3874 if (!sk_rmem_schedule(sk, size)) {
3875 if (!tcp_prune_ofo_queue(sk))
3876 return -1;
3877
3878 if (!sk_rmem_schedule(sk, size))
3879 return -1;
3880 }
3881 }
3882 return 0;
3883 }
3884
3885 static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
3886 {
3887 struct tcphdr *th = tcp_hdr(skb);
3888 struct tcp_sock *tp = tcp_sk(sk);
3889 int eaten = -1;
3890
3891 if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq)
3892 goto drop;
3893
3894 __skb_pull(skb, th->doff * 4);
3895
3896 TCP_ECN_accept_cwr(tp, skb);
3897
3898 if (tp->rx_opt.dsack) {
3899 tp->rx_opt.dsack = 0;
3900 tp->rx_opt.eff_sacks = min_t(unsigned int, tp->rx_opt.num_sacks,
3901 4 - tp->rx_opt.tstamp_ok);
3902 }
3903
3904 /* Queue data for delivery to the user.
3905 * Packets in sequence go to the receive queue.
3906 * Out of sequence packets to the out_of_order_queue.
3907 */
3908 if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
3909 if (tcp_receive_window(tp) == 0)
3910 goto out_of_window;
3911
3912 /* Ok. In sequence. In window. */
3913 if (tp->ucopy.task == current &&
3914 tp->copied_seq == tp->rcv_nxt && tp->ucopy.len &&
3915 sock_owned_by_user(sk) && !tp->urg_data) {
3916 int chunk = min_t(unsigned int, skb->len,
3917 tp->ucopy.len);
3918
3919 __set_current_state(TASK_RUNNING);
3920
3921 local_bh_enable();
3922 if (!skb_copy_datagram_iovec(skb, 0, tp->ucopy.iov, chunk)) {
3923 tp->ucopy.len -= chunk;
3924 tp->copied_seq += chunk;
3925 eaten = (chunk == skb->len && !th->fin);
3926 tcp_rcv_space_adjust(sk);
3927 }
3928 local_bh_disable();
3929 }
3930
3931 if (eaten <= 0) {
3932 queue_and_out:
3933 if (eaten < 0 &&
3934 tcp_try_rmem_schedule(sk, skb->truesize))
3935 goto drop;
3936
3937 skb_set_owner_r(skb, sk);
3938 __skb_queue_tail(&sk->sk_receive_queue, skb);
3939 }
3940 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
3941 if (skb->len)
3942 tcp_event_data_recv(sk, skb);
3943 if (th->fin)
3944 tcp_fin(skb, sk, th);
3945
3946 if (!skb_queue_empty(&tp->out_of_order_queue)) {
3947 tcp_ofo_queue(sk);
3948
3949 /* RFC2581. 4.2. SHOULD send immediate ACK, when
3950 * gap in queue is filled.
3951 */
3952 if (skb_queue_empty(&tp->out_of_order_queue))
3953 inet_csk(sk)->icsk_ack.pingpong = 0;
3954 }
3955
3956 if (tp->rx_opt.num_sacks)
3957 tcp_sack_remove(tp);
3958
3959 tcp_fast_path_check(sk);
3960
3961 if (eaten > 0)
3962 __kfree_skb(skb);
3963 else if (!sock_flag(sk, SOCK_DEAD))
3964 sk->sk_data_ready(sk, 0);
3965 return;
3966 }
3967
3968 if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
3969 /* A retransmit, 2nd most common case. Force an immediate ack. */
3970 NET_INC_STATS_BH(LINUX_MIB_DELAYEDACKLOST);
3971 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
3972
3973 out_of_window:
3974 tcp_enter_quickack_mode(sk);
3975 inet_csk_schedule_ack(sk);
3976 drop:
3977 __kfree_skb(skb);
3978 return;
3979 }
3980
3981 /* Out of window. F.e. zero window probe. */
3982 if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp)))
3983 goto out_of_window;
3984
3985 tcp_enter_quickack_mode(sk);
3986
3987 if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
3988 /* Partial packet, seq < rcv_next < end_seq */
3989 SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n",
3990 tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
3991 TCP_SKB_CB(skb)->end_seq);
3992
3993 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
3994
3995 /* If window is closed, drop tail of packet. But after
3996 * remembering D-SACK for its head made in previous line.
3997 */
3998 if (!tcp_receive_window(tp))
3999 goto out_of_window;
4000 goto queue_and_out;
4001 }
4002
4003 TCP_ECN_check_ce(tp, skb);
4004
4005 if (tcp_try_rmem_schedule(sk, skb->truesize))
4006 goto drop;
4007
4008 /* Disable header prediction. */
4009 tp->pred_flags = 0;
4010 inet_csk_schedule_ack(sk);
4011
4012 SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n",
4013 tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
4014
4015 skb_set_owner_r(skb, sk);
4016
4017 if (!skb_peek(&tp->out_of_order_queue)) {
4018 /* Initial out of order segment, build 1 SACK. */
4019 if (tcp_is_sack(tp)) {
4020 tp->rx_opt.num_sacks = 1;
4021 tp->rx_opt.dsack = 0;
4022 tp->rx_opt.eff_sacks = 1;
4023 tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq;
4024 tp->selective_acks[0].end_seq =
4025 TCP_SKB_CB(skb)->end_seq;
4026 }
4027 __skb_queue_head(&tp->out_of_order_queue, skb);
4028 } else {
4029 struct sk_buff *skb1 = tp->out_of_order_queue.prev;
4030 u32 seq = TCP_SKB_CB(skb)->seq;
4031 u32 end_seq = TCP_SKB_CB(skb)->end_seq;
4032
4033 if (seq == TCP_SKB_CB(skb1)->end_seq) {
4034 __skb_append(skb1, skb, &tp->out_of_order_queue);
4035
4036 if (!tp->rx_opt.num_sacks ||
4037 tp->selective_acks[0].end_seq != seq)
4038 goto add_sack;
4039
4040 /* Common case: data arrive in order after hole. */
4041 tp->selective_acks[0].end_seq = end_seq;
4042 return;
4043 }
4044
4045 /* Find place to insert this segment. */
4046 do {
4047 if (!after(TCP_SKB_CB(skb1)->seq, seq))
4048 break;
4049 } while ((skb1 = skb1->prev) !=
4050 (struct sk_buff *)&tp->out_of_order_queue);
4051
4052 /* Do skb overlap to previous one? */
4053 if (skb1 != (struct sk_buff *)&tp->out_of_order_queue &&
4054 before(seq, TCP_SKB_CB(skb1)->end_seq)) {
4055 if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
4056 /* All the bits are present. Drop. */
4057 __kfree_skb(skb);
4058 tcp_dsack_set(tp, seq, end_seq);
4059 goto add_sack;
4060 }
4061 if (after(seq, TCP_SKB_CB(skb1)->seq)) {
4062 /* Partial overlap. */
4063 tcp_dsack_set(tp, seq,
4064 TCP_SKB_CB(skb1)->end_seq);
4065 } else {
4066 skb1 = skb1->prev;
4067 }
4068 }
4069 __skb_insert(skb, skb1, skb1->next, &tp->out_of_order_queue);
4070
4071 /* And clean segments covered by new one as whole. */
4072 while ((skb1 = skb->next) !=
4073 (struct sk_buff *)&tp->out_of_order_queue &&
4074 after(end_seq, TCP_SKB_CB(skb1)->seq)) {
4075 if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
4076 tcp_dsack_extend(tp, TCP_SKB_CB(skb1)->seq,
4077 end_seq);
4078 break;
4079 }
4080 __skb_unlink(skb1, &tp->out_of_order_queue);
4081 tcp_dsack_extend(tp, TCP_SKB_CB(skb1)->seq,
4082 TCP_SKB_CB(skb1)->end_seq);
4083 __kfree_skb(skb1);
4084 }
4085
4086 add_sack:
4087 if (tcp_is_sack(tp))
4088 tcp_sack_new_ofo_skb(sk, seq, end_seq);
4089 }
4090 }
4091
4092 /* Collapse contiguous sequence of skbs head..tail with
4093 * sequence numbers start..end.
4094 * Segments with FIN/SYN are not collapsed (only because this
4095 * simplifies code)
4096 */
4097 static void
4098 tcp_collapse(struct sock *sk, struct sk_buff_head *list,
4099 struct sk_buff *head, struct sk_buff *tail,
4100 u32 start, u32 end)
4101 {
4102 struct sk_buff *skb;
4103
4104 /* First, check that queue is collapsible and find
4105 * the point where collapsing can be useful. */
4106 for (skb = head; skb != tail;) {
4107 /* No new bits? It is possible on ofo queue. */
4108 if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
4109 struct sk_buff *next = skb->next;
4110 __skb_unlink(skb, list);
4111 __kfree_skb(skb);
4112 NET_INC_STATS_BH(LINUX_MIB_TCPRCVCOLLAPSED);
4113 skb = next;
4114 continue;
4115 }
4116
4117 /* The first skb to collapse is:
4118 * - not SYN/FIN and
4119 * - bloated or contains data before "start" or
4120 * overlaps to the next one.
4121 */
4122 if (!tcp_hdr(skb)->syn && !tcp_hdr(skb)->fin &&
4123 (tcp_win_from_space(skb->truesize) > skb->len ||
4124 before(TCP_SKB_CB(skb)->seq, start) ||
4125 (skb->next != tail &&
4126 TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb->next)->seq)))
4127 break;
4128
4129 /* Decided to skip this, advance start seq. */
4130 start = TCP_SKB_CB(skb)->end_seq;
4131 skb = skb->next;
4132 }
4133 if (skb == tail || tcp_hdr(skb)->syn || tcp_hdr(skb)->fin)
4134 return;
4135
4136 while (before(start, end)) {
4137 struct sk_buff *nskb;
4138 unsigned int header = skb_headroom(skb);
4139 int copy = SKB_MAX_ORDER(header, 0);
4140
4141 /* Too big header? This can happen with IPv6. */
4142 if (copy < 0)
4143 return;
4144 if (end - start < copy)
4145 copy = end - start;
4146 nskb = alloc_skb(copy + header, GFP_ATOMIC);
4147 if (!nskb)
4148 return;
4149
4150 skb_set_mac_header(nskb, skb_mac_header(skb) - skb->head);
4151 skb_set_network_header(nskb, (skb_network_header(skb) -
4152 skb->head));
4153 skb_set_transport_header(nskb, (skb_transport_header(skb) -
4154 skb->head));
4155 skb_reserve(nskb, header);
4156 memcpy(nskb->head, skb->head, header);
4157 memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
4158 TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
4159 __skb_insert(nskb, skb->prev, skb, list);
4160 skb_set_owner_r(nskb, sk);
4161
4162 /* Copy data, releasing collapsed skbs. */
4163 while (copy > 0) {
4164 int offset = start - TCP_SKB_CB(skb)->seq;
4165 int size = TCP_SKB_CB(skb)->end_seq - start;
4166
4167 BUG_ON(offset < 0);
4168 if (size > 0) {
4169 size = min(copy, size);
4170 if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
4171 BUG();
4172 TCP_SKB_CB(nskb)->end_seq += size;
4173 copy -= size;
4174 start += size;
4175 }
4176 if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
4177 struct sk_buff *next = skb->next;
4178 __skb_unlink(skb, list);
4179 __kfree_skb(skb);
4180 NET_INC_STATS_BH(LINUX_MIB_TCPRCVCOLLAPSED);
4181 skb = next;
4182 if (skb == tail ||
4183 tcp_hdr(skb)->syn ||
4184 tcp_hdr(skb)->fin)
4185 return;
4186 }
4187 }
4188 }
4189 }
4190
4191 /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
4192 * and tcp_collapse() them until all the queue is collapsed.
4193 */
4194 static void tcp_collapse_ofo_queue(struct sock *sk)
4195 {
4196 struct tcp_sock *tp = tcp_sk(sk);
4197 struct sk_buff *skb = skb_peek(&tp->out_of_order_queue);
4198 struct sk_buff *head;
4199 u32 start, end;
4200
4201 if (skb == NULL)
4202 return;
4203
4204 start = TCP_SKB_CB(skb)->seq;
4205 end = TCP_SKB_CB(skb)->end_seq;
4206 head = skb;
4207
4208 for (;;) {
4209 skb = skb->next;
4210
4211 /* Segment is terminated when we see gap or when
4212 * we are at the end of all the queue. */
4213 if (skb == (struct sk_buff *)&tp->out_of_order_queue ||
4214 after(TCP_SKB_CB(skb)->seq, end) ||
4215 before(TCP_SKB_CB(skb)->end_seq, start)) {
4216 tcp_collapse(sk, &tp->out_of_order_queue,
4217 head, skb, start, end);
4218 head = skb;
4219 if (skb == (struct sk_buff *)&tp->out_of_order_queue)
4220 break;
4221 /* Start new segment */
4222 start = TCP_SKB_CB(skb)->seq;
4223 end = TCP_SKB_CB(skb)->end_seq;
4224 } else {
4225 if (before(TCP_SKB_CB(skb)->seq, start))
4226 start = TCP_SKB_CB(skb)->seq;
4227 if (after(TCP_SKB_CB(skb)->end_seq, end))
4228 end = TCP_SKB_CB(skb)->end_seq;
4229 }
4230 }
4231 }
4232
4233 /*
4234 * Purge the out-of-order queue.
4235 * Return true if queue was pruned.
4236 */
4237 static int tcp_prune_ofo_queue(struct sock *sk)
4238 {
4239 struct tcp_sock *tp = tcp_sk(sk);
4240 int res = 0;
4241
4242 if (!skb_queue_empty(&tp->out_of_order_queue)) {
4243 NET_INC_STATS_BH(LINUX_MIB_OFOPRUNED);
4244 __skb_queue_purge(&tp->out_of_order_queue);
4245
4246 /* Reset SACK state. A conforming SACK implementation will
4247 * do the same at a timeout based retransmit. When a connection
4248 * is in a sad state like this, we care only about integrity
4249 * of the connection not performance.
4250 */
4251 if (tp->rx_opt.sack_ok)
4252 tcp_sack_reset(&tp->rx_opt);
4253 sk_mem_reclaim(sk);
4254 res = 1;
4255 }
4256 return res;
4257 }
4258
4259 /* Reduce allocated memory if we can, trying to get
4260 * the socket within its memory limits again.
4261 *
4262 * Return less than zero if we should start dropping frames
4263 * until the socket owning process reads some of the data
4264 * to stabilize the situation.
4265 */
4266 static int tcp_prune_queue(struct sock *sk)
4267 {
4268 struct tcp_sock *tp = tcp_sk(sk);
4269
4270 SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq);
4271
4272 NET_INC_STATS_BH(LINUX_MIB_PRUNECALLED);
4273
4274 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
4275 tcp_clamp_window(sk);
4276 else if (tcp_memory_pressure)
4277 tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss);
4278
4279 tcp_collapse_ofo_queue(sk);
4280 tcp_collapse(sk, &sk->sk_receive_queue,
4281 sk->sk_receive_queue.next,
4282 (struct sk_buff *)&sk->sk_receive_queue,
4283 tp->copied_seq, tp->rcv_nxt);
4284 sk_mem_reclaim(sk);
4285
4286 if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
4287 return 0;
4288
4289 /* Collapsing did not help, destructive actions follow.
4290 * This must not ever occur. */
4291
4292 tcp_prune_ofo_queue(sk);
4293
4294 if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
4295 return 0;
4296
4297 /* If we are really being abused, tell the caller to silently
4298 * drop receive data on the floor. It will get retransmitted
4299 * and hopefully then we'll have sufficient space.
4300 */
4301 NET_INC_STATS_BH(LINUX_MIB_RCVPRUNED);
4302
4303 /* Massive buffer overcommit. */
4304 tp->pred_flags = 0;
4305 return -1;
4306 }
4307
4308 /* RFC2861, slow part. Adjust cwnd, after it was not full during one rto.
4309 * As additional protections, we do not touch cwnd in retransmission phases,
4310 * and if application hit its sndbuf limit recently.
4311 */
4312 void tcp_cwnd_application_limited(struct sock *sk)
4313 {
4314 struct tcp_sock *tp = tcp_sk(sk);
4315
4316 if (inet_csk(sk)->icsk_ca_state == TCP_CA_Open &&
4317 sk->sk_socket && !test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
4318 /* Limited by application or receiver window. */
4319 u32 init_win = tcp_init_cwnd(tp, __sk_dst_get(sk));
4320 u32 win_used = max(tp->snd_cwnd_used, init_win);
4321 if (win_used < tp->snd_cwnd) {
4322 tp->snd_ssthresh = tcp_current_ssthresh(sk);
4323 tp->snd_cwnd = (tp->snd_cwnd + win_used) >> 1;
4324 }
4325 tp->snd_cwnd_used = 0;
4326 }
4327 tp->snd_cwnd_stamp = tcp_time_stamp;
4328 }
4329
4330 static int tcp_should_expand_sndbuf(struct sock *sk)
4331 {
4332 struct tcp_sock *tp = tcp_sk(sk);
4333
4334 /* If the user specified a specific send buffer setting, do
4335 * not modify it.
4336 */
4337 if (sk->sk_userlocks & SOCK_SNDBUF_LOCK)
4338 return 0;
4339
4340 /* If we are under global TCP memory pressure, do not expand. */
4341 if (tcp_memory_pressure)
4342 return 0;
4343
4344 /* If we are under soft global TCP memory pressure, do not expand. */
4345 if (atomic_read(&tcp_memory_allocated) >= sysctl_tcp_mem[0])
4346 return 0;
4347
4348 /* If we filled the congestion window, do not expand. */
4349 if (tp->packets_out >= tp->snd_cwnd)
4350 return 0;
4351
4352 return 1;
4353 }
4354
4355 /* When incoming ACK allowed to free some skb from write_queue,
4356 * we remember this event in flag SOCK_QUEUE_SHRUNK and wake up socket
4357 * on the exit from tcp input handler.
4358 *
4359 * PROBLEM: sndbuf expansion does not work well with largesend.
4360 */
4361 static void tcp_new_space(struct sock *sk)
4362 {
4363 struct tcp_sock *tp = tcp_sk(sk);
4364
4365 if (tcp_should_expand_sndbuf(sk)) {
4366 int sndmem = max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) +
4367 MAX_TCP_HEADER + 16 + sizeof(struct sk_buff),
4368 demanded = max_t(unsigned int, tp->snd_cwnd,
4369 tp->reordering + 1);
4370 sndmem *= 2 * demanded;
4371 if (sndmem > sk->sk_sndbuf)
4372 sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]);
4373 tp->snd_cwnd_stamp = tcp_time_stamp;
4374 }
4375
4376 sk->sk_write_space(sk);
4377 }
4378
4379 static void tcp_check_space(struct sock *sk)
4380 {
4381 if (sock_flag(sk, SOCK_QUEUE_SHRUNK)) {
4382 sock_reset_flag(sk, SOCK_QUEUE_SHRUNK);
4383 if (sk->sk_socket &&
4384 test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
4385 tcp_new_space(sk);
4386 }
4387 }
4388
4389 static inline void tcp_data_snd_check(struct sock *sk)
4390 {
4391 tcp_push_pending_frames(sk);
4392 tcp_check_space(sk);
4393 }
4394
4395 /*
4396 * Check if sending an ack is needed.
4397 */
4398 static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
4399 {
4400 struct tcp_sock *tp = tcp_sk(sk);
4401
4402 /* More than one full frame received... */
4403 if (((tp->rcv_nxt - tp->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss
4404 /* ... and right edge of window advances far enough.
4405 * (tcp_recvmsg() will send ACK otherwise). Or...
4406 */
4407 && __tcp_select_window(sk) >= tp->rcv_wnd) ||
4408 /* We ACK each frame or... */
4409 tcp_in_quickack_mode(sk) ||
4410 /* We have out of order data. */
4411 (ofo_possible && skb_peek(&tp->out_of_order_queue))) {
4412 /* Then ack it now */
4413 tcp_send_ack(sk);
4414 } else {
4415 /* Else, send delayed ack. */
4416 tcp_send_delayed_ack(sk);
4417 }
4418 }
4419
4420 static inline void tcp_ack_snd_check(struct sock *sk)
4421 {
4422 if (!inet_csk_ack_scheduled(sk)) {
4423 /* We sent a data segment already. */
4424 return;
4425 }
4426 __tcp_ack_snd_check(sk, 1);
4427 }
4428
4429 /*
4430 * This routine is only called when we have urgent data
4431 * signaled. Its the 'slow' part of tcp_urg. It could be
4432 * moved inline now as tcp_urg is only called from one
4433 * place. We handle URGent data wrong. We have to - as
4434 * BSD still doesn't use the correction from RFC961.
4435 * For 1003.1g we should support a new option TCP_STDURG to permit
4436 * either form (or just set the sysctl tcp_stdurg).
4437 */
4438
4439 static void tcp_check_urg(struct sock *sk, struct tcphdr *th)
4440 {
4441 struct tcp_sock *tp = tcp_sk(sk);
4442 u32 ptr = ntohs(th->urg_ptr);
4443
4444 if (ptr && !sysctl_tcp_stdurg)
4445 ptr--;
4446 ptr += ntohl(th->seq);
4447
4448 /* Ignore urgent data that we've already seen and read. */
4449 if (after(tp->copied_seq, ptr))
4450 return;
4451
4452 /* Do not replay urg ptr.
4453 *
4454 * NOTE: interesting situation not covered by specs.
4455 * Misbehaving sender may send urg ptr, pointing to segment,
4456 * which we already have in ofo queue. We are not able to fetch
4457 * such data and will stay in TCP_URG_NOTYET until will be eaten
4458 * by recvmsg(). Seems, we are not obliged to handle such wicked
4459 * situations. But it is worth to think about possibility of some
4460 * DoSes using some hypothetical application level deadlock.
4461 */
4462 if (before(ptr, tp->rcv_nxt))
4463 return;
4464
4465 /* Do we already have a newer (or duplicate) urgent pointer? */
4466 if (tp->urg_data && !after(ptr, tp->urg_seq))
4467 return;
4468
4469 /* Tell the world about our new urgent pointer. */
4470 sk_send_sigurg(sk);
4471
4472 /* We may be adding urgent data when the last byte read was
4473 * urgent. To do this requires some care. We cannot just ignore
4474 * tp->copied_seq since we would read the last urgent byte again
4475 * as data, nor can we alter copied_seq until this data arrives
4476 * or we break the semantics of SIOCATMARK (and thus sockatmark())
4477 *
4478 * NOTE. Double Dutch. Rendering to plain English: author of comment
4479 * above did something sort of send("A", MSG_OOB); send("B", MSG_OOB);
4480 * and expect that both A and B disappear from stream. This is _wrong_.
4481 * Though this happens in BSD with high probability, this is occasional.
4482 * Any application relying on this is buggy. Note also, that fix "works"
4483 * only in this artificial test. Insert some normal data between A and B and we will
4484 * decline of BSD again. Verdict: it is better to remove to trap
4485 * buggy users.
4486 */
4487 if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
4488 !sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) {
4489 struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
4490 tp->copied_seq++;
4491 if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
4492 __skb_unlink(skb, &sk->sk_receive_queue);
4493 __kfree_skb(skb);
4494 }
4495 }
4496
4497 tp->urg_data = TCP_URG_NOTYET;
4498 tp->urg_seq = ptr;
4499
4500 /* Disable header prediction. */
4501 tp->pred_flags = 0;
4502 }
4503
4504 /* This is the 'fast' part of urgent handling. */
4505 static void tcp_urg(struct sock *sk, struct sk_buff *skb, struct tcphdr *th)
4506 {
4507 struct tcp_sock *tp = tcp_sk(sk);
4508
4509 /* Check if we get a new urgent pointer - normally not. */
4510 if (th->urg)
4511 tcp_check_urg(sk, th);
4512
4513 /* Do we wait for any urgent data? - normally not... */
4514 if (tp->urg_data == TCP_URG_NOTYET) {
4515 u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) -
4516 th->syn;
4517
4518 /* Is the urgent pointer pointing into this packet? */
4519 if (ptr < skb->len) {
4520 u8 tmp;
4521 if (skb_copy_bits(skb, ptr, &tmp, 1))
4522 BUG();
4523 tp->urg_data = TCP_URG_VALID | tmp;
4524 if (!sock_flag(sk, SOCK_DEAD))
4525 sk->sk_data_ready(sk, 0);
4526 }
4527 }
4528 }
4529
4530 static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen)
4531 {
4532 struct tcp_sock *tp = tcp_sk(sk);
4533 int chunk = skb->len - hlen;
4534 int err;
4535
4536 local_bh_enable();
4537 if (skb_csum_unnecessary(skb))
4538 err = skb_copy_datagram_iovec(skb, hlen, tp->ucopy.iov, chunk);
4539 else
4540 err = skb_copy_and_csum_datagram_iovec(skb, hlen,
4541 tp->ucopy.iov);
4542
4543 if (!err) {
4544 tp->ucopy.len -= chunk;
4545 tp->copied_seq += chunk;
4546 tcp_rcv_space_adjust(sk);
4547 }
4548
4549 local_bh_disable();
4550 return err;
4551 }
4552
4553 static __sum16 __tcp_checksum_complete_user(struct sock *sk,
4554 struct sk_buff *skb)
4555 {
4556 __sum16 result;
4557
4558 if (sock_owned_by_user(sk)) {
4559 local_bh_enable();
4560 result = __tcp_checksum_complete(skb);
4561 local_bh_disable();
4562 } else {
4563 result = __tcp_checksum_complete(skb);
4564 }
4565 return result;
4566 }
4567
4568 static inline int tcp_checksum_complete_user(struct sock *sk,
4569 struct sk_buff *skb)
4570 {
4571 return !skb_csum_unnecessary(skb) &&
4572 __tcp_checksum_complete_user(sk, skb);
4573 }
4574
4575 #ifdef CONFIG_NET_DMA
4576 static int tcp_dma_try_early_copy(struct sock *sk, struct sk_buff *skb,
4577 int hlen)
4578 {
4579 struct tcp_sock *tp = tcp_sk(sk);
4580 int chunk = skb->len - hlen;
4581 int dma_cookie;
4582 int copied_early = 0;
4583
4584 if (tp->ucopy.wakeup)
4585 return 0;
4586
4587 if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)
4588 tp->ucopy.dma_chan = get_softnet_dma();
4589
4590 if (tp->ucopy.dma_chan && skb_csum_unnecessary(skb)) {
4591
4592 dma_cookie = dma_skb_copy_datagram_iovec(tp->ucopy.dma_chan,
4593 skb, hlen,
4594 tp->ucopy.iov, chunk,
4595 tp->ucopy.pinned_list);
4596
4597 if (dma_cookie < 0)
4598 goto out;
4599
4600 tp->ucopy.dma_cookie = dma_cookie;
4601 copied_early = 1;
4602
4603 tp->ucopy.len -= chunk;
4604 tp->copied_seq += chunk;
4605 tcp_rcv_space_adjust(sk);
4606
4607 if ((tp->ucopy.len == 0) ||
4608 (tcp_flag_word(tcp_hdr(skb)) & TCP_FLAG_PSH) ||
4609 (atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1))) {
4610 tp->ucopy.wakeup = 1;
4611 sk->sk_data_ready(sk, 0);
4612 }
4613 } else if (chunk > 0) {
4614 tp->ucopy.wakeup = 1;
4615 sk->sk_data_ready(sk, 0);
4616 }
4617 out:
4618 return copied_early;
4619 }
4620 #endif /* CONFIG_NET_DMA */
4621
4622 /*
4623 * TCP receive function for the ESTABLISHED state.
4624 *
4625 * It is split into a fast path and a slow path. The fast path is
4626 * disabled when:
4627 * - A zero window was announced from us - zero window probing
4628 * is only handled properly in the slow path.
4629 * - Out of order segments arrived.
4630 * - Urgent data is expected.
4631 * - There is no buffer space left
4632 * - Unexpected TCP flags/window values/header lengths are received
4633 * (detected by checking the TCP header against pred_flags)
4634 * - Data is sent in both directions. Fast path only supports pure senders
4635 * or pure receivers (this means either the sequence number or the ack
4636 * value must stay constant)
4637 * - Unexpected TCP option.
4638 *
4639 * When these conditions are not satisfied it drops into a standard
4640 * receive procedure patterned after RFC793 to handle all cases.
4641 * The first three cases are guaranteed by proper pred_flags setting,
4642 * the rest is checked inline. Fast processing is turned on in
4643 * tcp_data_queue when everything is OK.
4644 */
4645 int tcp_rcv_established(struct sock *sk, struct sk_buff *skb,
4646 struct tcphdr *th, unsigned len)
4647 {
4648 struct tcp_sock *tp = tcp_sk(sk);
4649
4650 /*
4651 * Header prediction.
4652 * The code loosely follows the one in the famous
4653 * "30 instruction TCP receive" Van Jacobson mail.
4654 *
4655 * Van's trick is to deposit buffers into socket queue
4656 * on a device interrupt, to call tcp_recv function
4657 * on the receive process context and checksum and copy
4658 * the buffer to user space. smart...
4659 *
4660 * Our current scheme is not silly either but we take the
4661 * extra cost of the net_bh soft interrupt processing...
4662 * We do checksum and copy also but from device to kernel.
4663 */
4664
4665 tp->rx_opt.saw_tstamp = 0;
4666
4667 /* pred_flags is 0xS?10 << 16 + snd_wnd
4668 * if header_prediction is to be made
4669 * 'S' will always be tp->tcp_header_len >> 2
4670 * '?' will be 0 for the fast path, otherwise pred_flags is 0 to
4671 * turn it off (when there are holes in the receive
4672 * space for instance)
4673 * PSH flag is ignored.
4674 */
4675
4676 if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
4677 TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
4678 int tcp_header_len = tp->tcp_header_len;
4679
4680 /* Timestamp header prediction: tcp_header_len
4681 * is automatically equal to th->doff*4 due to pred_flags
4682 * match.
4683 */
4684
4685 /* Check timestamp */
4686 if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
4687 __be32 *ptr = (__be32 *)(th + 1);
4688
4689 /* No? Slow path! */
4690 if (*ptr != htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
4691 | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP))
4692 goto slow_path;
4693
4694 tp->rx_opt.saw_tstamp = 1;
4695 ++ptr;
4696 tp->rx_opt.rcv_tsval = ntohl(*ptr);
4697 ++ptr;
4698 tp->rx_opt.rcv_tsecr = ntohl(*ptr);
4699
4700 /* If PAWS failed, check it more carefully in slow path */
4701 if ((s32)(tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent) < 0)
4702 goto slow_path;
4703
4704 /* DO NOT update ts_recent here, if checksum fails
4705 * and timestamp was corrupted part, it will result
4706 * in a hung connection since we will drop all
4707 * future packets due to the PAWS test.
4708 */
4709 }
4710
4711 if (len <= tcp_header_len) {
4712 /* Bulk data transfer: sender */
4713 if (len == tcp_header_len) {
4714 /* Predicted packet is in window by definition.
4715 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
4716 * Hence, check seq<=rcv_wup reduces to:
4717 */
4718 if (tcp_header_len ==
4719 (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
4720 tp->rcv_nxt == tp->rcv_wup)
4721 tcp_store_ts_recent(tp);
4722
4723 /* We know that such packets are checksummed
4724 * on entry.
4725 */
4726 tcp_ack(sk, skb, 0);
4727 __kfree_skb(skb);
4728 tcp_data_snd_check(sk);
4729 return 0;
4730 } else { /* Header too small */
4731 TCP_INC_STATS_BH(TCP_MIB_INERRS);
4732 goto discard;
4733 }
4734 } else {
4735 int eaten = 0;
4736 int copied_early = 0;
4737
4738 if (tp->copied_seq == tp->rcv_nxt &&
4739 len - tcp_header_len <= tp->ucopy.len) {
4740 #ifdef CONFIG_NET_DMA
4741 if (tcp_dma_try_early_copy(sk, skb, tcp_header_len)) {
4742 copied_early = 1;
4743 eaten = 1;
4744 }
4745 #endif
4746 if (tp->ucopy.task == current &&
4747 sock_owned_by_user(sk) && !copied_early) {
4748 __set_current_state(TASK_RUNNING);
4749
4750 if (!tcp_copy_to_iovec(sk, skb, tcp_header_len))
4751 eaten = 1;
4752 }
4753 if (eaten) {
4754 /* Predicted packet is in window by definition.
4755 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
4756 * Hence, check seq<=rcv_wup reduces to:
4757 */
4758 if (tcp_header_len ==
4759 (sizeof(struct tcphdr) +
4760 TCPOLEN_TSTAMP_ALIGNED) &&
4761 tp->rcv_nxt == tp->rcv_wup)
4762 tcp_store_ts_recent(tp);
4763
4764 tcp_rcv_rtt_measure_ts(sk, skb);
4765
4766 __skb_pull(skb, tcp_header_len);
4767 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
4768 NET_INC_STATS_BH(LINUX_MIB_TCPHPHITSTOUSER);
4769 }
4770 if (copied_early)
4771 tcp_cleanup_rbuf(sk, skb->len);
4772 }
4773 if (!eaten) {
4774 if (tcp_checksum_complete_user(sk, skb))
4775 goto csum_error;
4776
4777 /* Predicted packet is in window by definition.
4778 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
4779 * Hence, check seq<=rcv_wup reduces to:
4780 */
4781 if (tcp_header_len ==
4782 (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
4783 tp->rcv_nxt == tp->rcv_wup)
4784 tcp_store_ts_recent(tp);
4785
4786 tcp_rcv_rtt_measure_ts(sk, skb);
4787
4788 if ((int)skb->truesize > sk->sk_forward_alloc)
4789 goto step5;
4790
4791 NET_INC_STATS_BH(LINUX_MIB_TCPHPHITS);
4792
4793 /* Bulk data transfer: receiver */
4794 __skb_pull(skb, tcp_header_len);
4795 __skb_queue_tail(&sk->sk_receive_queue, skb);
4796 skb_set_owner_r(skb, sk);
4797 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
4798 }
4799
4800 tcp_event_data_recv(sk, skb);
4801
4802 if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
4803 /* Well, only one small jumplet in fast path... */
4804 tcp_ack(sk, skb, FLAG_DATA);
4805 tcp_data_snd_check(sk);
4806 if (!inet_csk_ack_scheduled(sk))
4807 goto no_ack;
4808 }
4809
4810 __tcp_ack_snd_check(sk, 0);
4811 no_ack:
4812 #ifdef CONFIG_NET_DMA
4813 if (copied_early)
4814 __skb_queue_tail(&sk->sk_async_wait_queue, skb);
4815 else
4816 #endif
4817 if (eaten)
4818 __kfree_skb(skb);
4819 else
4820 sk->sk_data_ready(sk, 0);
4821 return 0;
4822 }
4823 }
4824
4825 slow_path:
4826 if (len < (th->doff << 2) || tcp_checksum_complete_user(sk, skb))
4827 goto csum_error;
4828
4829 /*
4830 * RFC1323: H1. Apply PAWS check first.
4831 */
4832 if (tcp_fast_parse_options(skb, th, tp) && tp->rx_opt.saw_tstamp &&
4833 tcp_paws_discard(sk, skb)) {
4834 if (!th->rst) {
4835 NET_INC_STATS_BH(LINUX_MIB_PAWSESTABREJECTED);
4836 tcp_send_dupack(sk, skb);
4837 goto discard;
4838 }
4839 /* Resets are accepted even if PAWS failed.
4840
4841 ts_recent update must be made after we are sure
4842 that the packet is in window.
4843 */
4844 }
4845
4846 /*
4847 * Standard slow path.
4848 */
4849
4850 if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
4851 /* RFC793, page 37: "In all states except SYN-SENT, all reset
4852 * (RST) segments are validated by checking their SEQ-fields."
4853 * And page 69: "If an incoming segment is not acceptable,
4854 * an acknowledgment should be sent in reply (unless the RST bit
4855 * is set, if so drop the segment and return)".
4856 */
4857 if (!th->rst)
4858 tcp_send_dupack(sk, skb);
4859 goto discard;
4860 }
4861
4862 if (th->rst) {
4863 tcp_reset(sk);
4864 goto discard;
4865 }
4866
4867 tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
4868
4869 if (th->syn && !before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4870 TCP_INC_STATS_BH(TCP_MIB_INERRS);
4871 NET_INC_STATS_BH(LINUX_MIB_TCPABORTONSYN);
4872 tcp_reset(sk);
4873 return 1;
4874 }
4875
4876 step5:
4877 if (th->ack)
4878 tcp_ack(sk, skb, FLAG_SLOWPATH);
4879
4880 tcp_rcv_rtt_measure_ts(sk, skb);
4881
4882 /* Process urgent data. */
4883 tcp_urg(sk, skb, th);
4884
4885 /* step 7: process the segment text */
4886 tcp_data_queue(sk, skb);
4887
4888 tcp_data_snd_check(sk);
4889 tcp_ack_snd_check(sk);
4890 return 0;
4891
4892 csum_error:
4893 TCP_INC_STATS_BH(TCP_MIB_INERRS);
4894
4895 discard:
4896 __kfree_skb(skb);
4897 return 0;
4898 }
4899
4900 static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
4901 struct tcphdr *th, unsigned len)
4902 {
4903 struct tcp_sock *tp = tcp_sk(sk);
4904 struct inet_connection_sock *icsk = inet_csk(sk);
4905 int saved_clamp = tp->rx_opt.mss_clamp;
4906
4907 tcp_parse_options(skb, &tp->rx_opt, 0);
4908
4909 if (th->ack) {
4910 /* rfc793:
4911 * "If the state is SYN-SENT then
4912 * first check the ACK bit
4913 * If the ACK bit is set
4914 * If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
4915 * a reset (unless the RST bit is set, if so drop
4916 * the segment and return)"
4917 *
4918 * We do not send data with SYN, so that RFC-correct
4919 * test reduces to:
4920 */
4921 if (TCP_SKB_CB(skb)->ack_seq != tp->snd_nxt)
4922 goto reset_and_undo;
4923
4924 if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
4925 !between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp,
4926 tcp_time_stamp)) {
4927 NET_INC_STATS_BH(LINUX_MIB_PAWSACTIVEREJECTED);
4928 goto reset_and_undo;
4929 }
4930
4931 /* Now ACK is acceptable.
4932 *
4933 * "If the RST bit is set
4934 * If the ACK was acceptable then signal the user "error:
4935 * connection reset", drop the segment, enter CLOSED state,
4936 * delete TCB, and return."
4937 */
4938
4939 if (th->rst) {
4940 tcp_reset(sk);
4941 goto discard;
4942 }
4943
4944 /* rfc793:
4945 * "fifth, if neither of the SYN or RST bits is set then
4946 * drop the segment and return."
4947 *
4948 * See note below!
4949 * --ANK(990513)
4950 */
4951 if (!th->syn)
4952 goto discard_and_undo;
4953
4954 /* rfc793:
4955 * "If the SYN bit is on ...
4956 * are acceptable then ...
4957 * (our SYN has been ACKed), change the connection
4958 * state to ESTABLISHED..."
4959 */
4960
4961 TCP_ECN_rcv_synack(tp, th);
4962
4963 tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
4964 tcp_ack(sk, skb, FLAG_SLOWPATH);
4965
4966 /* Ok.. it's good. Set up sequence numbers and
4967 * move to established.
4968 */
4969 tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
4970 tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
4971
4972 /* RFC1323: The window in SYN & SYN/ACK segments is
4973 * never scaled.
4974 */
4975 tp->snd_wnd = ntohs(th->window);
4976 tcp_init_wl(tp, TCP_SKB_CB(skb)->ack_seq, TCP_SKB_CB(skb)->seq);
4977
4978 if (!tp->rx_opt.wscale_ok) {
4979 tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0;
4980 tp->window_clamp = min(tp->window_clamp, 65535U);
4981 }
4982
4983 if (tp->rx_opt.saw_tstamp) {
4984 tp->rx_opt.tstamp_ok = 1;
4985 tp->tcp_header_len =
4986 sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
4987 tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
4988 tcp_store_ts_recent(tp);
4989 } else {
4990 tp->tcp_header_len = sizeof(struct tcphdr);
4991 }
4992
4993 if (tcp_is_sack(tp) && sysctl_tcp_fack)
4994 tcp_enable_fack(tp);
4995
4996 tcp_mtup_init(sk);
4997 tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
4998 tcp_initialize_rcv_mss(sk);
4999
5000 /* Remember, tcp_poll() does not lock socket!
5001 * Change state from SYN-SENT only after copied_seq
5002 * is initialized. */
5003 tp->copied_seq = tp->rcv_nxt;
5004 smp_mb();
5005 tcp_set_state(sk, TCP_ESTABLISHED);
5006
5007 security_inet_conn_established(sk, skb);
5008
5009 /* Make sure socket is routed, for correct metrics. */
5010 icsk->icsk_af_ops->rebuild_header(sk);
5011
5012 tcp_init_metrics(sk);
5013
5014 tcp_init_congestion_control(sk);
5015
5016 /* Prevent spurious tcp_cwnd_restart() on first data
5017 * packet.
5018 */
5019 tp->lsndtime = tcp_time_stamp;
5020
5021 tcp_init_buffer_space(sk);
5022
5023 if (sock_flag(sk, SOCK_KEEPOPEN))
5024 inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tp));
5025
5026 if (!tp->rx_opt.snd_wscale)
5027 __tcp_fast_path_on(tp, tp->snd_wnd);
5028 else
5029 tp->pred_flags = 0;
5030
5031 if (!sock_flag(sk, SOCK_DEAD)) {
5032 sk->sk_state_change(sk);
5033 sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
5034 }
5035
5036 if (sk->sk_write_pending ||
5037 icsk->icsk_accept_queue.rskq_defer_accept ||
5038 icsk->icsk_ack.pingpong) {
5039 /* Save one ACK. Data will be ready after
5040 * several ticks, if write_pending is set.
5041 *
5042 * It may be deleted, but with this feature tcpdumps
5043 * look so _wonderfully_ clever, that I was not able
5044 * to stand against the temptation 8) --ANK
5045 */
5046 inet_csk_schedule_ack(sk);
5047 icsk->icsk_ack.lrcvtime = tcp_time_stamp;
5048 icsk->icsk_ack.ato = TCP_ATO_MIN;
5049 tcp_incr_quickack(sk);
5050 tcp_enter_quickack_mode(sk);
5051 inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK,
5052 TCP_DELACK_MAX, TCP_RTO_MAX);
5053
5054 discard:
5055 __kfree_skb(skb);
5056 return 0;
5057 } else {
5058 tcp_send_ack(sk);
5059 }
5060 return -1;
5061 }
5062
5063 /* No ACK in the segment */
5064
5065 if (th->rst) {
5066 /* rfc793:
5067 * "If the RST bit is set
5068 *
5069 * Otherwise (no ACK) drop the segment and return."
5070 */
5071
5072 goto discard_and_undo;
5073 }
5074
5075 /* PAWS check. */
5076 if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp &&
5077 tcp_paws_check(&tp->rx_opt, 0))
5078 goto discard_and_undo;
5079
5080 if (th->syn) {
5081 /* We see SYN without ACK. It is attempt of
5082 * simultaneous connect with crossed SYNs.
5083 * Particularly, it can be connect to self.
5084 */
5085 tcp_set_state(sk, TCP_SYN_RECV);
5086
5087 if (tp->rx_opt.saw_tstamp) {
5088 tp->rx_opt.tstamp_ok = 1;
5089 tcp_store_ts_recent(tp);
5090 tp->tcp_header_len =
5091 sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
5092 } else {
5093 tp->tcp_header_len = sizeof(struct tcphdr);
5094 }
5095
5096 tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
5097 tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
5098
5099 /* RFC1323: The window in SYN & SYN/ACK segments is
5100 * never scaled.
5101 */
5102 tp->snd_wnd = ntohs(th->window);
5103 tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
5104 tp->max_window = tp->snd_wnd;
5105
5106 TCP_ECN_rcv_syn(tp, th);
5107
5108 tcp_mtup_init(sk);
5109 tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
5110 tcp_initialize_rcv_mss(sk);
5111
5112 tcp_send_synack(sk);
5113 #if 0
5114 /* Note, we could accept data and URG from this segment.
5115 * There are no obstacles to make this.
5116 *
5117 * However, if we ignore data in ACKless segments sometimes,
5118 * we have no reasons to accept it sometimes.
5119 * Also, seems the code doing it in step6 of tcp_rcv_state_process
5120 * is not flawless. So, discard packet for sanity.
5121 * Uncomment this return to process the data.
5122 */
5123 return -1;
5124 #else
5125 goto discard;
5126 #endif
5127 }
5128 /* "fifth, if neither of the SYN or RST bits is set then
5129 * drop the segment and return."
5130 */
5131
5132 discard_and_undo:
5133 tcp_clear_options(&tp->rx_opt);
5134 tp->rx_opt.mss_clamp = saved_clamp;
5135 goto discard;
5136
5137 reset_and_undo:
5138 tcp_clear_options(&tp->rx_opt);
5139 tp->rx_opt.mss_clamp = saved_clamp;
5140 return 1;
5141 }
5142
5143 /*
5144 * This function implements the receiving procedure of RFC 793 for
5145 * all states except ESTABLISHED and TIME_WAIT.
5146 * It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
5147 * address independent.
5148 */
5149
5150 int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb,
5151 struct tcphdr *th, unsigned len)
5152 {
5153 struct tcp_sock *tp = tcp_sk(sk);
5154 struct inet_connection_sock *icsk = inet_csk(sk);
5155 int queued = 0;
5156
5157 tp->rx_opt.saw_tstamp = 0;
5158
5159 switch (sk->sk_state) {
5160 case TCP_CLOSE:
5161 goto discard;
5162
5163 case TCP_LISTEN:
5164 if (th->ack)
5165 return 1;
5166
5167 if (th->rst)
5168 goto discard;
5169
5170 if (th->syn) {
5171 if (icsk->icsk_af_ops->conn_request(sk, skb) < 0)
5172 return 1;
5173
5174 /* Now we have several options: In theory there is
5175 * nothing else in the frame. KA9Q has an option to
5176 * send data with the syn, BSD accepts data with the
5177 * syn up to the [to be] advertised window and
5178 * Solaris 2.1 gives you a protocol error. For now
5179 * we just ignore it, that fits the spec precisely
5180 * and avoids incompatibilities. It would be nice in
5181 * future to drop through and process the data.
5182 *
5183 * Now that TTCP is starting to be used we ought to
5184 * queue this data.
5185 * But, this leaves one open to an easy denial of
5186 * service attack, and SYN cookies can't defend
5187 * against this problem. So, we drop the data
5188 * in the interest of security over speed unless
5189 * it's still in use.
5190 */
5191 kfree_skb(skb);
5192 return 0;
5193 }
5194 goto discard;
5195
5196 case TCP_SYN_SENT:
5197 queued = tcp_rcv_synsent_state_process(sk, skb, th, len);
5198 if (queued >= 0)
5199 return queued;
5200
5201 /* Do step6 onward by hand. */
5202 tcp_urg(sk, skb, th);
5203 __kfree_skb(skb);
5204 tcp_data_snd_check(sk);
5205 return 0;
5206 }
5207
5208 if (tcp_fast_parse_options(skb, th, tp) && tp->rx_opt.saw_tstamp &&
5209 tcp_paws_discard(sk, skb)) {
5210 if (!th->rst) {
5211 NET_INC_STATS_BH(LINUX_MIB_PAWSESTABREJECTED);
5212 tcp_send_dupack(sk, skb);
5213 goto discard;
5214 }
5215 /* Reset is accepted even if it did not pass PAWS. */
5216 }
5217
5218 /* step 1: check sequence number */
5219 if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
5220 if (!th->rst)
5221 tcp_send_dupack(sk, skb);
5222 goto discard;
5223 }
5224
5225 /* step 2: check RST bit */
5226 if (th->rst) {
5227 tcp_reset(sk);
5228 goto discard;
5229 }
5230
5231 tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
5232
5233 /* step 3: check security and precedence [ignored] */
5234
5235 /* step 4:
5236 *
5237 * Check for a SYN in window.
5238 */
5239 if (th->syn && !before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
5240 NET_INC_STATS_BH(LINUX_MIB_TCPABORTONSYN);
5241 tcp_reset(sk);
5242 return 1;
5243 }
5244
5245 /* step 5: check the ACK field */
5246 if (th->ack) {
5247 int acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH);
5248
5249 switch (sk->sk_state) {
5250 case TCP_SYN_RECV:
5251 if (acceptable) {
5252 tp->copied_seq = tp->rcv_nxt;
5253 smp_mb();
5254 tcp_set_state(sk, TCP_ESTABLISHED);
5255 sk->sk_state_change(sk);
5256
5257 /* Note, that this wakeup is only for marginal
5258 * crossed SYN case. Passively open sockets
5259 * are not waked up, because sk->sk_sleep ==
5260 * NULL and sk->sk_socket == NULL.
5261 */
5262 if (sk->sk_socket)
5263 sk_wake_async(sk,
5264 SOCK_WAKE_IO, POLL_OUT);
5265
5266 tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
5267 tp->snd_wnd = ntohs(th->window) <<
5268 tp->rx_opt.snd_wscale;
5269 tcp_init_wl(tp, TCP_SKB_CB(skb)->ack_seq,
5270 TCP_SKB_CB(skb)->seq);
5271
5272 /* tcp_ack considers this ACK as duplicate
5273 * and does not calculate rtt.
5274 * Fix it at least with timestamps.
5275 */
5276 if (tp->rx_opt.saw_tstamp &&
5277 tp->rx_opt.rcv_tsecr && !tp->srtt)
5278 tcp_ack_saw_tstamp(sk, 0);
5279
5280 if (tp->rx_opt.tstamp_ok)
5281 tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
5282
5283 /* Make sure socket is routed, for
5284 * correct metrics.
5285 */
5286 icsk->icsk_af_ops->rebuild_header(sk);
5287
5288 tcp_init_metrics(sk);
5289
5290 tcp_init_congestion_control(sk);
5291
5292 /* Prevent spurious tcp_cwnd_restart() on
5293 * first data packet.
5294 */
5295 tp->lsndtime = tcp_time_stamp;
5296
5297 tcp_mtup_init(sk);
5298 tcp_initialize_rcv_mss(sk);
5299 tcp_init_buffer_space(sk);
5300 tcp_fast_path_on(tp);
5301 } else {
5302 return 1;
5303 }
5304 break;
5305
5306 case TCP_FIN_WAIT1:
5307 if (tp->snd_una == tp->write_seq) {
5308 tcp_set_state(sk, TCP_FIN_WAIT2);
5309 sk->sk_shutdown |= SEND_SHUTDOWN;
5310 dst_confirm(sk->sk_dst_cache);
5311
5312 if (!sock_flag(sk, SOCK_DEAD))
5313 /* Wake up lingering close() */
5314 sk->sk_state_change(sk);
5315 else {
5316 int tmo;
5317
5318 if (tp->linger2 < 0 ||
5319 (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
5320 after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) {
5321 tcp_done(sk);
5322 NET_INC_STATS_BH(LINUX_MIB_TCPABORTONDATA);
5323 return 1;
5324 }
5325
5326 tmo = tcp_fin_time(sk);
5327 if (tmo > TCP_TIMEWAIT_LEN) {
5328 inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
5329 } else if (th->fin || sock_owned_by_user(sk)) {
5330 /* Bad case. We could lose such FIN otherwise.
5331 * It is not a big problem, but it looks confusing
5332 * and not so rare event. We still can lose it now,
5333 * if it spins in bh_lock_sock(), but it is really
5334 * marginal case.
5335 */
5336 inet_csk_reset_keepalive_timer(sk, tmo);
5337 } else {
5338 tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
5339 goto discard;
5340 }
5341 }
5342 }
5343 break;
5344
5345 case TCP_CLOSING:
5346 if (tp->snd_una == tp->write_seq) {
5347 tcp_time_wait(sk, TCP_TIME_WAIT, 0);
5348 goto discard;
5349 }
5350 break;
5351
5352 case TCP_LAST_ACK:
5353 if (tp->snd_una == tp->write_seq) {
5354 tcp_update_metrics(sk);
5355 tcp_done(sk);
5356 goto discard;
5357 }
5358 break;
5359 }
5360 } else
5361 goto discard;
5362
5363 /* step 6: check the URG bit */
5364 tcp_urg(sk, skb, th);
5365
5366 /* step 7: process the segment text */
5367 switch (sk->sk_state) {
5368 case TCP_CLOSE_WAIT:
5369 case TCP_CLOSING:
5370 case TCP_LAST_ACK:
5371 if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
5372 break;
5373 case TCP_FIN_WAIT1:
5374 case TCP_FIN_WAIT2:
5375 /* RFC 793 says to queue data in these states,
5376 * RFC 1122 says we MUST send a reset.
5377 * BSD 4.4 also does reset.
5378 */
5379 if (sk->sk_shutdown & RCV_SHUTDOWN) {
5380 if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
5381 after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
5382 NET_INC_STATS_BH(LINUX_MIB_TCPABORTONDATA);
5383 tcp_reset(sk);
5384 return 1;
5385 }
5386 }
5387 /* Fall through */
5388 case TCP_ESTABLISHED:
5389 tcp_data_queue(sk, skb);
5390 queued = 1;
5391 break;
5392 }
5393
5394 /* tcp_data could move socket to TIME-WAIT */
5395 if (sk->sk_state != TCP_CLOSE) {
5396 tcp_data_snd_check(sk);
5397 tcp_ack_snd_check(sk);
5398 }
5399
5400 if (!queued) {
5401 discard:
5402 __kfree_skb(skb);
5403 }
5404 return 0;
5405 }
5406
5407 EXPORT_SYMBOL(sysctl_tcp_ecn);
5408 EXPORT_SYMBOL(sysctl_tcp_reordering);
5409 EXPORT_SYMBOL(tcp_parse_options);
5410 EXPORT_SYMBOL(tcp_rcv_established);
5411 EXPORT_SYMBOL(tcp_rcv_state_process);
5412 EXPORT_SYMBOL(tcp_initialize_rcv_mss);
5413
|
This page was automatically generated by the
LXR engine.
|