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