OSDN Git Service

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