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