c7d711f5e6456973698e09d2c74f3af7b1ed7a16
[linux-2.6.git] / include / net / tcp.h
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  *              Definitions for the TCP module.
7  *
8  * Version:     @(#)tcp.h       1.0.5   05/23/93
9  *
10  * Authors:     Ross Biro, <bir7@leland.Stanford.Edu>
11  *              Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
12  *
13  *              This program is free software; you can redistribute it and/or
14  *              modify it under the terms of the GNU General Public License
15  *              as published by the Free Software Foundation; either version
16  *              2 of the License, or (at your option) any later version.
17  */
18 #ifndef _TCP_H
19 #define _TCP_H
20
21 #define TCP_DEBUG 1
22 #define FASTRETRANS_DEBUG 1
23
24 /* Cancel timers, when they are not required. */
25 #undef TCP_CLEAR_TIMERS
26
27 #include <linux/config.h>
28 #include <linux/list.h>
29 #include <linux/tcp.h>
30 #include <linux/slab.h>
31 #include <linux/cache.h>
32 #include <linux/percpu.h>
33 #include <net/checksum.h>
34 #include <net/sock.h>
35 #include <net/snmp.h>
36 #include <net/ip.h>
37 #if defined(CONFIG_IPV6) || defined (CONFIG_IPV6_MODULE)
38 #include <linux/ipv6.h>
39 #endif
40 #include <linux/seq_file.h>
41
42 /* This is for all connections with a full identity, no wildcards.
43  * New scheme, half the table is for TIME_WAIT, the other half is
44  * for the rest.  I'll experiment with dynamic table growth later.
45  */
46 struct tcp_ehash_bucket {
47         rwlock_t          lock;
48         struct hlist_head chain;
49 } __attribute__((__aligned__(8)));
50
51 /* This is for listening sockets, thus all sockets which possess wildcards. */
52 #define TCP_LHTABLE_SIZE        32      /* Yes, really, this is all you need. */
53
54 /* There are a few simple rules, which allow for local port reuse by
55  * an application.  In essence:
56  *
57  *      1) Sockets bound to different interfaces may share a local port.
58  *         Failing that, goto test 2.
59  *      2) If all sockets have sk->sk_reuse set, and none of them are in
60  *         TCP_LISTEN state, the port may be shared.
61  *         Failing that, goto test 3.
62  *      3) If all sockets are bound to a specific inet_sk(sk)->rcv_saddr local
63  *         address, and none of them are the same, the port may be
64  *         shared.
65  *         Failing this, the port cannot be shared.
66  *
67  * The interesting point, is test #2.  This is what an FTP server does
68  * all day.  To optimize this case we use a specific flag bit defined
69  * below.  As we add sockets to a bind bucket list, we perform a
70  * check of: (newsk->sk_reuse && (newsk->sk_state != TCP_LISTEN))
71  * As long as all sockets added to a bind bucket pass this test,
72  * the flag bit will be set.
73  * The resulting situation is that tcp_v[46]_verify_bind() can just check
74  * for this flag bit, if it is set and the socket trying to bind has
75  * sk->sk_reuse set, we don't even have to walk the owners list at all,
76  * we return that it is ok to bind this socket to the requested local port.
77  *
78  * Sounds like a lot of work, but it is worth it.  In a more naive
79  * implementation (ie. current FreeBSD etc.) the entire list of ports
80  * must be walked for each data port opened by an ftp server.  Needless
81  * to say, this does not scale at all.  With a couple thousand FTP
82  * users logged onto your box, isn't it nice to know that new data
83  * ports are created in O(1) time?  I thought so. ;-)   -DaveM
84  */
85 struct tcp_bind_bucket {
86         unsigned short          port;
87         signed short            fastreuse;
88         struct hlist_node       node;
89         struct hlist_head       owners;
90 };
91
92 #define tb_for_each(tb, node, head) hlist_for_each_entry(tb, node, head, node)
93
94 struct tcp_bind_hashbucket {
95         spinlock_t              lock;
96         struct hlist_head       chain;
97 };
98
99 static inline struct tcp_bind_bucket *__tb_head(struct tcp_bind_hashbucket *head)
100 {
101         return hlist_entry(head->chain.first, struct tcp_bind_bucket, node);
102 }
103
104 static inline struct tcp_bind_bucket *tb_head(struct tcp_bind_hashbucket *head)
105 {
106         return hlist_empty(&head->chain) ? NULL : __tb_head(head);
107 }
108
109 extern struct tcp_hashinfo {
110         /* This is for sockets with full identity only.  Sockets here will
111          * always be without wildcards and will have the following invariant:
112          *
113          *          TCP_ESTABLISHED <= sk->sk_state < TCP_CLOSE
114          *
115          * First half of the table is for sockets not in TIME_WAIT, second half
116          * is for TIME_WAIT sockets only.
117          */
118         struct tcp_ehash_bucket *__tcp_ehash;
119
120         /* Ok, let's try this, I give up, we do need a local binding
121          * TCP hash as well as the others for fast bind/connect.
122          */
123         struct tcp_bind_hashbucket *__tcp_bhash;
124
125         int __tcp_bhash_size;
126         int __tcp_ehash_size;
127
128         /* All sockets in TCP_LISTEN state will be in here.  This is the only
129          * table where wildcard'd TCP sockets can exist.  Hash function here
130          * is just local port number.
131          */
132         struct hlist_head __tcp_listening_hash[TCP_LHTABLE_SIZE];
133
134         /* All the above members are written once at bootup and
135          * never written again _or_ are predominantly read-access.
136          *
137          * Now align to a new cache line as all the following members
138          * are often dirty.
139          */
140         rwlock_t __tcp_lhash_lock ____cacheline_aligned;
141         atomic_t __tcp_lhash_users;
142         wait_queue_head_t __tcp_lhash_wait;
143         spinlock_t __tcp_portalloc_lock;
144 } tcp_hashinfo;
145
146 #define tcp_ehash       (tcp_hashinfo.__tcp_ehash)
147 #define tcp_bhash       (tcp_hashinfo.__tcp_bhash)
148 #define tcp_ehash_size  (tcp_hashinfo.__tcp_ehash_size)
149 #define tcp_bhash_size  (tcp_hashinfo.__tcp_bhash_size)
150 #define tcp_listening_hash (tcp_hashinfo.__tcp_listening_hash)
151 #define tcp_lhash_lock  (tcp_hashinfo.__tcp_lhash_lock)
152 #define tcp_lhash_users (tcp_hashinfo.__tcp_lhash_users)
153 #define tcp_lhash_wait  (tcp_hashinfo.__tcp_lhash_wait)
154 #define tcp_portalloc_lock (tcp_hashinfo.__tcp_portalloc_lock)
155
156 /* SLAB cache for TCP socks */
157 extern kmem_cache_t *tcp_sk_cachep;
158
159 extern kmem_cache_t *tcp_bucket_cachep;
160 extern struct tcp_bind_bucket *tcp_bucket_create(struct tcp_bind_hashbucket *head,
161                                                  unsigned short snum);
162 extern void tcp_bucket_destroy(struct tcp_bind_bucket *tb);
163 extern void tcp_bucket_unlock(struct sock *sk);
164 extern int tcp_port_rover;
165 extern struct sock *tcp_v4_lookup_listener(u32 addr, unsigned short hnum, int dif);
166
167 /* These are AF independent. */
168 static __inline__ int tcp_bhashfn(__u16 lport)
169 {
170         return (lport & (tcp_bhash_size - 1));
171 }
172
173 extern void tcp_bind_hash(struct sock *sk, struct tcp_bind_bucket *tb,
174                           unsigned short snum);
175
176 #if (BITS_PER_LONG == 64)
177 #define TCP_ADDRCMP_ALIGN_BYTES 8
178 #else
179 #define TCP_ADDRCMP_ALIGN_BYTES 4
180 #endif
181
182 /* This is a TIME_WAIT bucket.  It works around the memory consumption
183  * problems of sockets in such a state on heavily loaded servers, but
184  * without violating the protocol specification.
185  */
186 struct tcp_tw_bucket {
187         /*
188          * Now struct sock also uses sock_common, so please just
189          * don't add nothing before this first member (__tw_common) --acme
190          */
191         struct sock_common      __tw_common;
192 #define tw_family               __tw_common.skc_family
193 #define tw_state                __tw_common.skc_state
194 #define tw_reuse                __tw_common.skc_reuse
195 #define tw_bound_dev_if         __tw_common.skc_bound_dev_if
196 #define tw_node                 __tw_common.skc_node
197 #define tw_bind_node            __tw_common.skc_bind_node
198 #define tw_refcnt               __tw_common.skc_refcnt
199         volatile unsigned char  tw_substate;
200         unsigned char           tw_rcv_wscale;
201         __u16                   tw_sport;
202         /* Socket demultiplex comparisons on incoming packets. */
203         /* these five are in inet_opt */
204         __u32                   tw_daddr
205                 __attribute__((aligned(TCP_ADDRCMP_ALIGN_BYTES)));
206         __u32                   tw_rcv_saddr;
207         __u16                   tw_dport;
208         __u16                   tw_num;
209         /* And these are ours. */
210         int                     tw_hashent;
211         int                     tw_timeout;
212         __u32                   tw_rcv_nxt;
213         __u32                   tw_snd_nxt;
214         __u32                   tw_rcv_wnd;
215         __u32                   tw_ts_recent;
216         long                    tw_ts_recent_stamp;
217         unsigned long           tw_ttd;
218         struct tcp_bind_bucket  *tw_tb;
219         struct hlist_node       tw_death_node;
220 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
221         struct in6_addr         tw_v6_daddr;
222         struct in6_addr         tw_v6_rcv_saddr;
223         int                     tw_v6_ipv6only;
224 #endif
225 };
226
227 static __inline__ void tw_add_node(struct tcp_tw_bucket *tw,
228                                    struct hlist_head *list)
229 {
230         hlist_add_head(&tw->tw_node, list);
231 }
232
233 static __inline__ void tw_add_bind_node(struct tcp_tw_bucket *tw,
234                                         struct hlist_head *list)
235 {
236         hlist_add_head(&tw->tw_bind_node, list);
237 }
238
239 static inline int tw_dead_hashed(struct tcp_tw_bucket *tw)
240 {
241         return tw->tw_death_node.pprev != NULL;
242 }
243
244 static __inline__ void tw_dead_node_init(struct tcp_tw_bucket *tw)
245 {
246         tw->tw_death_node.pprev = NULL;
247 }
248
249 static __inline__ void __tw_del_dead_node(struct tcp_tw_bucket *tw)
250 {
251         __hlist_del(&tw->tw_death_node);
252         tw_dead_node_init(tw);
253 }
254
255 static __inline__ int tw_del_dead_node(struct tcp_tw_bucket *tw)
256 {
257         if (tw_dead_hashed(tw)) {
258                 __tw_del_dead_node(tw);
259                 return 1;
260         }
261         return 0;
262 }
263
264 #define tw_for_each(tw, node, head) \
265         hlist_for_each_entry(tw, node, head, tw_node)
266
267 #define tw_for_each_inmate(tw, node, jail) \
268         hlist_for_each_entry(tw, node, jail, tw_death_node)
269
270 #define tw_for_each_inmate_safe(tw, node, safe, jail) \
271         hlist_for_each_entry_safe(tw, node, safe, jail, tw_death_node)
272
273 #define tcptw_sk(__sk)  ((struct tcp_tw_bucket *)(__sk))
274
275 static inline u32 tcp_v4_rcv_saddr(const struct sock *sk)
276 {
277         return likely(sk->sk_state != TCP_TIME_WAIT) ?
278                 inet_sk(sk)->rcv_saddr : tcptw_sk(sk)->tw_rcv_saddr;
279 }
280
281 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
282 static inline struct in6_addr *__tcp_v6_rcv_saddr(const struct sock *sk)
283 {
284         return likely(sk->sk_state != TCP_TIME_WAIT) ?
285                 &inet6_sk(sk)->rcv_saddr : &tcptw_sk(sk)->tw_v6_rcv_saddr;
286 }
287
288 static inline struct in6_addr *tcp_v6_rcv_saddr(const struct sock *sk)
289 {
290         return sk->sk_family == AF_INET6 ? __tcp_v6_rcv_saddr(sk) : NULL;
291 }
292
293 #define tcptw_sk_ipv6only(__sk) (tcptw_sk(__sk)->tw_v6_ipv6only)
294
295 static inline int tcp_v6_ipv6only(const struct sock *sk)
296 {
297         return likely(sk->sk_state != TCP_TIME_WAIT) ?
298                 ipv6_only_sock(sk) : tcptw_sk_ipv6only(sk);
299 }
300 #else
301 # define __tcp_v6_rcv_saddr(__sk)       NULL
302 # define tcp_v6_rcv_saddr(__sk)         NULL
303 # define tcptw_sk_ipv6only(__sk)        0
304 # define tcp_v6_ipv6only(__sk)          0
305 #endif
306
307 extern kmem_cache_t *tcp_timewait_cachep;
308
309 static inline void tcp_tw_put(struct tcp_tw_bucket *tw)
310 {
311         if (atomic_dec_and_test(&tw->tw_refcnt)) {
312 #ifdef INET_REFCNT_DEBUG
313                 printk(KERN_DEBUG "tw_bucket %p released\n", tw);
314 #endif
315                 kmem_cache_free(tcp_timewait_cachep, tw);
316         }
317 }
318
319 extern atomic_t tcp_orphan_count;
320 extern int tcp_tw_count;
321 extern void tcp_time_wait(struct sock *sk, int state, int timeo);
322 extern void tcp_tw_schedule(struct tcp_tw_bucket *tw, int timeo);
323 extern void tcp_tw_deschedule(struct tcp_tw_bucket *tw);
324
325
326 /* Socket demux engine toys. */
327 #ifdef __BIG_ENDIAN
328 #define TCP_COMBINED_PORTS(__sport, __dport) \
329         (((__u32)(__sport)<<16) | (__u32)(__dport))
330 #else /* __LITTLE_ENDIAN */
331 #define TCP_COMBINED_PORTS(__sport, __dport) \
332         (((__u32)(__dport)<<16) | (__u32)(__sport))
333 #endif
334
335 #if (BITS_PER_LONG == 64)
336 #ifdef __BIG_ENDIAN
337 #define TCP_V4_ADDR_COOKIE(__name, __saddr, __daddr) \
338         __u64 __name = (((__u64)(__saddr))<<32)|((__u64)(__daddr));
339 #else /* __LITTLE_ENDIAN */
340 #define TCP_V4_ADDR_COOKIE(__name, __saddr, __daddr) \
341         __u64 __name = (((__u64)(__daddr))<<32)|((__u64)(__saddr));
342 #endif /* __BIG_ENDIAN */
343 #define TCP_IPV4_MATCH(__sk, __cookie, __saddr, __daddr, __ports, __dif)\
344         (((*((__u64 *)&(inet_sk(__sk)->daddr)))== (__cookie))   &&      \
345          ((*((__u32 *)&(inet_sk(__sk)->dport)))== (__ports))    &&      \
346          (!((__sk)->sk_bound_dev_if) || ((__sk)->sk_bound_dev_if == (__dif))))
347 #define TCP_IPV4_TW_MATCH(__sk, __cookie, __saddr, __daddr, __ports, __dif)\
348         (((*((__u64 *)&(tcptw_sk(__sk)->tw_daddr))) == (__cookie)) &&   \
349          ((*((__u32 *)&(tcptw_sk(__sk)->tw_dport))) == (__ports)) &&    \
350          (!((__sk)->sk_bound_dev_if) || ((__sk)->sk_bound_dev_if == (__dif))))
351 #else /* 32-bit arch */
352 #define TCP_V4_ADDR_COOKIE(__name, __saddr, __daddr)
353 #define TCP_IPV4_MATCH(__sk, __cookie, __saddr, __daddr, __ports, __dif)\
354         ((inet_sk(__sk)->daddr                  == (__saddr))   &&      \
355          (inet_sk(__sk)->rcv_saddr              == (__daddr))   &&      \
356          ((*((__u32 *)&(inet_sk(__sk)->dport)))== (__ports))    &&      \
357          (!((__sk)->sk_bound_dev_if) || ((__sk)->sk_bound_dev_if == (__dif))))
358 #define TCP_IPV4_TW_MATCH(__sk, __cookie, __saddr, __daddr, __ports, __dif)\
359         ((tcptw_sk(__sk)->tw_daddr              == (__saddr))   &&      \
360          (tcptw_sk(__sk)->tw_rcv_saddr          == (__daddr))   &&      \
361          ((*((__u32 *)&(tcptw_sk(__sk)->tw_dport))) == (__ports)) &&    \
362          (!((__sk)->sk_bound_dev_if) || ((__sk)->sk_bound_dev_if == (__dif))))
363 #endif /* 64-bit arch */
364
365 #define TCP_IPV6_MATCH(__sk, __saddr, __daddr, __ports, __dif)     \
366         (((*((__u32 *)&(inet_sk(__sk)->dport)))== (__ports))    && \
367          ((__sk)->sk_family             == AF_INET6)            && \
368          !ipv6_addr_cmp(&inet6_sk(__sk)->daddr, (__saddr))      && \
369          !ipv6_addr_cmp(&inet6_sk(__sk)->rcv_saddr, (__daddr))  && \
370          (!((__sk)->sk_bound_dev_if) || ((__sk)->sk_bound_dev_if == (__dif))))
371
372 /* These can have wildcards, don't try too hard. */
373 static __inline__ int tcp_lhashfn(unsigned short num)
374 {
375         return num & (TCP_LHTABLE_SIZE - 1);
376 }
377
378 static __inline__ int tcp_sk_listen_hashfn(struct sock *sk)
379 {
380         return tcp_lhashfn(inet_sk(sk)->num);
381 }
382
383 #define MAX_TCP_HEADER  (128 + MAX_HEADER)
384
385 /* 
386  * Never offer a window over 32767 without using window scaling. Some
387  * poor stacks do signed 16bit maths! 
388  */
389 #define MAX_TCP_WINDOW          32767U
390
391 /* Minimal accepted MSS. It is (60+60+8) - (20+20). */
392 #define TCP_MIN_MSS             88U
393
394 /* Minimal RCV_MSS. */
395 #define TCP_MIN_RCVMSS          536U
396
397 /* After receiving this amount of duplicate ACKs fast retransmit starts. */
398 #define TCP_FASTRETRANS_THRESH 3
399
400 /* Maximal reordering. */
401 #define TCP_MAX_REORDERING      127
402
403 /* Maximal number of ACKs sent quickly to accelerate slow-start. */
404 #define TCP_MAX_QUICKACKS       16U
405
406 /* urg_data states */
407 #define TCP_URG_VALID   0x0100
408 #define TCP_URG_NOTYET  0x0200
409 #define TCP_URG_READ    0x0400
410
411 #define TCP_RETR1       3       /*
412                                  * This is how many retries it does before it
413                                  * tries to figure out if the gateway is
414                                  * down. Minimal RFC value is 3; it corresponds
415                                  * to ~3sec-8min depending on RTO.
416                                  */
417
418 #define TCP_RETR2       15      /*
419                                  * This should take at least
420                                  * 90 minutes to time out.
421                                  * RFC1122 says that the limit is 100 sec.
422                                  * 15 is ~13-30min depending on RTO.
423                                  */
424
425 #define TCP_SYN_RETRIES  5      /* number of times to retry active opening a
426                                  * connection: ~180sec is RFC minumum   */
427
428 #define TCP_SYNACK_RETRIES 5    /* number of times to retry passive opening a
429                                  * connection: ~180sec is RFC minumum   */
430
431
432 #define TCP_ORPHAN_RETRIES 7    /* number of times to retry on an orphaned
433                                  * socket. 7 is ~50sec-16min.
434                                  */
435
436
437 #define TCP_TIMEWAIT_LEN (60*HZ) /* how long to wait to destroy TIME-WAIT
438                                   * state, about 60 seconds     */
439 #define TCP_FIN_TIMEOUT TCP_TIMEWAIT_LEN
440                                  /* BSD style FIN_WAIT2 deadlock breaker.
441                                   * It used to be 3min, new value is 60sec,
442                                   * to combine FIN-WAIT-2 timeout with
443                                   * TIME-WAIT timer.
444                                   */
445
446 #define TCP_DELACK_MAX  ((unsigned)(HZ/5))      /* maximal time to delay before sending an ACK */
447 #if HZ >= 100
448 #define TCP_DELACK_MIN  ((unsigned)(HZ/25))     /* minimal time to delay before sending an ACK */
449 #define TCP_ATO_MIN     ((unsigned)(HZ/25))
450 #else
451 #define TCP_DELACK_MIN  4U
452 #define TCP_ATO_MIN     4U
453 #endif
454 #define TCP_RTO_MAX     ((unsigned)(120*HZ))
455 #define TCP_RTO_MIN     ((unsigned)(HZ/5))
456 #define TCP_TIMEOUT_INIT ((unsigned)(3*HZ))     /* RFC 1122 initial RTO value   */
457
458 #define TCP_RESOURCE_PROBE_INTERVAL ((unsigned)(HZ/2U)) /* Maximal interval between probes
459                                                          * for local resources.
460                                                          */
461
462 #define TCP_KEEPALIVE_TIME      (120*60*HZ)     /* two hours */
463 #define TCP_KEEPALIVE_PROBES    9               /* Max of 9 keepalive probes    */
464 #define TCP_KEEPALIVE_INTVL     (75*HZ)
465
466 #define MAX_TCP_KEEPIDLE        32767
467 #define MAX_TCP_KEEPINTVL       32767
468 #define MAX_TCP_KEEPCNT         127
469 #define MAX_TCP_SYNCNT          127
470
471 #define TCP_SYNQ_INTERVAL       (HZ/5)  /* Period of SYNACK timer */
472 #define TCP_SYNQ_HSIZE          512     /* Size of SYNACK hash table */
473
474 #define TCP_PAWS_24DAYS (60 * 60 * 24 * 24)
475 #define TCP_PAWS_MSL    60              /* Per-host timestamps are invalidated
476                                          * after this time. It should be equal
477                                          * (or greater than) TCP_TIMEWAIT_LEN
478                                          * to provide reliability equal to one
479                                          * provided by timewait state.
480                                          */
481 #define TCP_PAWS_WINDOW 1               /* Replay window for per-host
482                                          * timestamps. It must be less than
483                                          * minimal timewait lifetime.
484                                          */
485
486 #define TCP_TW_RECYCLE_SLOTS_LOG        5
487 #define TCP_TW_RECYCLE_SLOTS            (1<<TCP_TW_RECYCLE_SLOTS_LOG)
488
489 /* If time > 4sec, it is "slow" path, no recycling is required,
490    so that we select tick to get range about 4 seconds.
491  */
492
493 #if HZ <= 16 || HZ > 4096
494 # error Unsupported: HZ <= 16 or HZ > 4096
495 #elif HZ <= 32
496 # define TCP_TW_RECYCLE_TICK (5+2-TCP_TW_RECYCLE_SLOTS_LOG)
497 #elif HZ <= 64
498 # define TCP_TW_RECYCLE_TICK (6+2-TCP_TW_RECYCLE_SLOTS_LOG)
499 #elif HZ <= 128
500 # define TCP_TW_RECYCLE_TICK (7+2-TCP_TW_RECYCLE_SLOTS_LOG)
501 #elif HZ <= 256
502 # define TCP_TW_RECYCLE_TICK (8+2-TCP_TW_RECYCLE_SLOTS_LOG)
503 #elif HZ <= 512
504 # define TCP_TW_RECYCLE_TICK (9+2-TCP_TW_RECYCLE_SLOTS_LOG)
505 #elif HZ <= 1024
506 # define TCP_TW_RECYCLE_TICK (10+2-TCP_TW_RECYCLE_SLOTS_LOG)
507 #elif HZ <= 2048
508 # define TCP_TW_RECYCLE_TICK (11+2-TCP_TW_RECYCLE_SLOTS_LOG)
509 #else
510 # define TCP_TW_RECYCLE_TICK (12+2-TCP_TW_RECYCLE_SLOTS_LOG)
511 #endif
512
513 #define BICTCP_1_OVER_BETA      8       /*
514                                          * Fast recovery
515                                          * multiplicative decrease factor
516                                          */
517 #define BICTCP_MAX_INCREMENT 32         /*
518                                          * Limit on the amount of
519                                          * increment allowed during
520                                          * binary search.
521                                          */
522 #define BICTCP_FUNC_OF_MIN_INCR 11      /*
523                                          * log(B/Smin)/log(B/(B-1))+1,
524                                          * Smin:min increment
525                                          * B:log factor
526                                          */
527 #define BICTCP_B                4        /*
528                                           * In binary search,
529                                           * go to point (max+min)/N
530                                           */
531
532 /*
533  *      TCP option
534  */
535  
536 #define TCPOPT_NOP              1       /* Padding */
537 #define TCPOPT_EOL              0       /* End of options */
538 #define TCPOPT_MSS              2       /* Segment size negotiating */
539 #define TCPOPT_WINDOW           3       /* Window scaling */
540 #define TCPOPT_SACK_PERM        4       /* SACK Permitted */
541 #define TCPOPT_SACK             5       /* SACK Block */
542 #define TCPOPT_TIMESTAMP        8       /* Better RTT estimations/PAWS */
543
544 /*
545  *     TCP option lengths
546  */
547
548 #define TCPOLEN_MSS            4
549 #define TCPOLEN_WINDOW         3
550 #define TCPOLEN_SACK_PERM      2
551 #define TCPOLEN_TIMESTAMP      10
552
553 /* But this is what stacks really send out. */
554 #define TCPOLEN_TSTAMP_ALIGNED          12
555 #define TCPOLEN_WSCALE_ALIGNED          4
556 #define TCPOLEN_SACKPERM_ALIGNED        4
557 #define TCPOLEN_SACK_BASE               2
558 #define TCPOLEN_SACK_BASE_ALIGNED       4
559 #define TCPOLEN_SACK_PERBLOCK           8
560
561 #define TCP_TIME_RETRANS        1       /* Retransmit timer */
562 #define TCP_TIME_DACK           2       /* Delayed ack timer */
563 #define TCP_TIME_PROBE0         3       /* Zero window probe timer */
564 #define TCP_TIME_KEEPOPEN       4       /* Keepalive timer */
565
566 /* Flags in tp->nonagle */
567 #define TCP_NAGLE_OFF           1       /* Nagle's algo is disabled */
568 #define TCP_NAGLE_CORK          2       /* Socket is corked         */
569 #define TCP_NAGLE_PUSH          4       /* Cork is overriden for already queued data */
570
571 /* sysctl variables for tcp */
572 extern int sysctl_max_syn_backlog;
573 extern int sysctl_tcp_timestamps;
574 extern int sysctl_tcp_window_scaling;
575 extern int sysctl_tcp_sack;
576 extern int sysctl_tcp_fin_timeout;
577 extern int sysctl_tcp_tw_recycle;
578 extern int sysctl_tcp_keepalive_time;
579 extern int sysctl_tcp_keepalive_probes;
580 extern int sysctl_tcp_keepalive_intvl;
581 extern int sysctl_tcp_syn_retries;
582 extern int sysctl_tcp_synack_retries;
583 extern int sysctl_tcp_retries1;
584 extern int sysctl_tcp_retries2;
585 extern int sysctl_tcp_orphan_retries;
586 extern int sysctl_tcp_syncookies;
587 extern int sysctl_tcp_retrans_collapse;
588 extern int sysctl_tcp_stdurg;
589 extern int sysctl_tcp_rfc1337;
590 extern int sysctl_tcp_abort_on_overflow;
591 extern int sysctl_tcp_max_orphans;
592 extern int sysctl_tcp_max_tw_buckets;
593 extern int sysctl_tcp_fack;
594 extern int sysctl_tcp_reordering;
595 extern int sysctl_tcp_ecn;
596 extern int sysctl_tcp_dsack;
597 extern int sysctl_tcp_mem[3];
598 extern int sysctl_tcp_wmem[3];
599 extern int sysctl_tcp_rmem[3];
600 extern int sysctl_tcp_app_win;
601 extern int sysctl_tcp_adv_win_scale;
602 extern int sysctl_tcp_tw_reuse;
603 extern int sysctl_tcp_frto;
604 extern int sysctl_tcp_low_latency;
605 extern int sysctl_tcp_westwood;
606 extern int sysctl_tcp_vegas_cong_avoid;
607 extern int sysctl_tcp_vegas_alpha;
608 extern int sysctl_tcp_vegas_beta;
609 extern int sysctl_tcp_vegas_gamma;
610 extern int sysctl_tcp_nometrics_save;
611 extern int sysctl_tcp_bic;
612 extern int sysctl_tcp_bic_fast_convergence;
613 extern int sysctl_tcp_bic_low_window;
614 extern int sysctl_tcp_default_win_scale;
615 extern int sysctl_tcp_moderate_rcvbuf;
616
617 extern atomic_t tcp_memory_allocated;
618 extern atomic_t tcp_sockets_allocated;
619 extern int tcp_memory_pressure;
620
621 struct open_request;
622
623 struct or_calltable {
624         int  family;
625         int  (*rtx_syn_ack)     (struct sock *sk, struct open_request *req, struct dst_entry*);
626         void (*send_ack)        (struct sk_buff *skb, struct open_request *req);
627         void (*destructor)      (struct open_request *req);
628         void (*send_reset)      (struct sk_buff *skb);
629 };
630
631 struct tcp_v4_open_req {
632         __u32                   loc_addr;
633         __u32                   rmt_addr;
634         struct ip_options       *opt;
635 };
636
637 #if defined(CONFIG_IPV6) || defined (CONFIG_IPV6_MODULE)
638 struct tcp_v6_open_req {
639         struct in6_addr         loc_addr;
640         struct in6_addr         rmt_addr;
641         struct sk_buff          *pktopts;
642         int                     iif;
643 };
644 #endif
645
646 /* this structure is too big */
647 struct open_request {
648         struct open_request     *dl_next; /* Must be first member! */
649         __u32                   rcv_isn;
650         __u32                   snt_isn;
651         __u16                   rmt_port;
652         __u16                   mss;
653         __u8                    retrans;
654         __u8                    __pad;
655         __u16   snd_wscale : 4, 
656                 rcv_wscale : 4, 
657                 tstamp_ok : 1,
658                 sack_ok : 1,
659                 wscale_ok : 1,
660                 ecn_ok : 1,
661                 acked : 1;
662         /* The following two fields can be easily recomputed I think -AK */
663         __u32                   window_clamp;   /* window clamp at creation time */
664         __u32                   rcv_wnd;        /* rcv_wnd offered first time */
665         __u32                   ts_recent;
666         unsigned long           expires;
667         struct or_calltable     *class;
668         struct sock             *sk;
669         union {
670                 struct tcp_v4_open_req v4_req;
671 #if defined(CONFIG_IPV6) || defined (CONFIG_IPV6_MODULE)
672                 struct tcp_v6_open_req v6_req;
673 #endif
674         } af;
675 };
676
677 /* SLAB cache for open requests. */
678 extern kmem_cache_t *tcp_openreq_cachep;
679
680 #define tcp_openreq_alloc()             kmem_cache_alloc(tcp_openreq_cachep, SLAB_ATOMIC)
681 #define tcp_openreq_fastfree(req)       kmem_cache_free(tcp_openreq_cachep, req)
682
683 static inline void tcp_openreq_free(struct open_request *req)
684 {
685         req->class->destructor(req);
686         tcp_openreq_fastfree(req);
687 }
688
689 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
690 #define TCP_INET_FAMILY(fam) ((fam) == AF_INET)
691 #else
692 #define TCP_INET_FAMILY(fam) 1
693 #endif
694
695 /*
696  *      Pointers to address related TCP functions
697  *      (i.e. things that depend on the address family)
698  */
699
700 struct tcp_func {
701         int                     (*queue_xmit)           (struct sk_buff *skb,
702                                                          int ipfragok);
703
704         void                    (*send_check)           (struct sock *sk,
705                                                          struct tcphdr *th,
706                                                          int len,
707                                                          struct sk_buff *skb);
708
709         int                     (*rebuild_header)       (struct sock *sk);
710
711         int                     (*conn_request)         (struct sock *sk,
712                                                          struct sk_buff *skb);
713
714         struct sock *           (*syn_recv_sock)        (struct sock *sk,
715                                                          struct sk_buff *skb,
716                                                          struct open_request *req,
717                                                          struct dst_entry *dst);
718     
719         int                     (*remember_stamp)       (struct sock *sk);
720
721         __u16                   net_header_len;
722
723         int                     (*setsockopt)           (struct sock *sk, 
724                                                          int level, 
725                                                          int optname, 
726                                                          char __user *optval, 
727                                                          int optlen);
728
729         int                     (*getsockopt)           (struct sock *sk, 
730                                                          int level, 
731                                                          int optname, 
732                                                          char __user *optval, 
733                                                          int __user *optlen);
734
735
736         void                    (*addr2sockaddr)        (struct sock *sk,
737                                                          struct sockaddr *);
738
739         int sockaddr_len;
740 };
741
742 /*
743  * The next routines deal with comparing 32 bit unsigned ints
744  * and worry about wraparound (automatic with unsigned arithmetic).
745  */
746
747 static inline int before(__u32 seq1, __u32 seq2)
748 {
749         return (__s32)(seq1-seq2) < 0;
750 }
751
752 static inline int after(__u32 seq1, __u32 seq2)
753 {
754         return (__s32)(seq2-seq1) < 0;
755 }
756
757
758 /* is s2<=s1<=s3 ? */
759 static inline int between(__u32 seq1, __u32 seq2, __u32 seq3)
760 {
761         return seq3 - seq2 >= seq1 - seq2;
762 }
763
764
765 extern struct proto tcp_prot;
766
767 DECLARE_SNMP_STAT(struct tcp_mib, tcp_statistics);
768 #define TCP_INC_STATS(field)            SNMP_INC_STATS(tcp_statistics, field)
769 #define TCP_INC_STATS_BH(field)         SNMP_INC_STATS_BH(tcp_statistics, field)
770 #define TCP_INC_STATS_USER(field)       SNMP_INC_STATS_USER(tcp_statistics, field)
771 #define TCP_DEC_STATS(field)            SNMP_DEC_STATS(tcp_statistics, field)
772 #define TCP_ADD_STATS_BH(field, val)    SNMP_ADD_STATS_BH(tcp_statistics, field, val)
773 #define TCP_ADD_STATS_USER(field, val)  SNMP_ADD_STATS_USER(tcp_statistics, field, val)
774
775 extern void                     tcp_put_port(struct sock *sk);
776 extern void                     tcp_inherit_port(struct sock *sk, struct sock *child);
777
778 extern void                     tcp_v4_err(struct sk_buff *skb, u32);
779
780 extern void                     tcp_shutdown (struct sock *sk, int how);
781
782 extern int                      tcp_v4_rcv(struct sk_buff *skb);
783
784 extern int                      tcp_v4_remember_stamp(struct sock *sk);
785
786 extern int                      tcp_v4_tw_remember_stamp(struct tcp_tw_bucket *tw);
787
788 extern int                      tcp_sendmsg(struct kiocb *iocb, struct sock *sk,
789                                             struct msghdr *msg, size_t size);
790 extern ssize_t                  tcp_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags);
791
792 extern int                      tcp_ioctl(struct sock *sk, 
793                                           int cmd, 
794                                           unsigned long arg);
795
796 extern int                      tcp_rcv_state_process(struct sock *sk, 
797                                                       struct sk_buff *skb,
798                                                       struct tcphdr *th,
799                                                       unsigned len);
800
801 extern int                      tcp_rcv_established(struct sock *sk, 
802                                                     struct sk_buff *skb,
803                                                     struct tcphdr *th, 
804                                                     unsigned len);
805
806 extern void                     tcp_rcv_space_adjust(struct sock *sk);
807
808 enum tcp_ack_state_t
809 {
810         TCP_ACK_SCHED = 1,
811         TCP_ACK_TIMER = 2,
812         TCP_ACK_PUSHED= 4
813 };
814
815 static inline void tcp_schedule_ack(struct tcp_opt *tp)
816 {
817         tp->ack.pending |= TCP_ACK_SCHED;
818 }
819
820 static inline int tcp_ack_scheduled(struct tcp_opt *tp)
821 {
822         return tp->ack.pending&TCP_ACK_SCHED;
823 }
824
825 static __inline__ void tcp_dec_quickack_mode(struct tcp_opt *tp)
826 {
827         if (tp->ack.quick && --tp->ack.quick == 0) {
828                 /* Leaving quickack mode we deflate ATO. */
829                 tp->ack.ato = TCP_ATO_MIN;
830         }
831 }
832
833 extern void tcp_enter_quickack_mode(struct tcp_opt *tp);
834
835 static __inline__ void tcp_delack_init(struct tcp_opt *tp)
836 {
837         memset(&tp->ack, 0, sizeof(tp->ack));
838 }
839
840 static inline void tcp_clear_options(struct tcp_opt *tp)
841 {
842         tp->tstamp_ok = tp->sack_ok = tp->wscale_ok = tp->snd_wscale = 0;
843 }
844
845 enum tcp_tw_status
846 {
847         TCP_TW_SUCCESS = 0,
848         TCP_TW_RST = 1,
849         TCP_TW_ACK = 2,
850         TCP_TW_SYN = 3
851 };
852
853
854 extern enum tcp_tw_status       tcp_timewait_state_process(struct tcp_tw_bucket *tw,
855                                                            struct sk_buff *skb,
856                                                            struct tcphdr *th,
857                                                            unsigned len);
858
859 extern struct sock *            tcp_check_req(struct sock *sk,struct sk_buff *skb,
860                                               struct open_request *req,
861                                               struct open_request **prev);
862 extern int                      tcp_child_process(struct sock *parent,
863                                                   struct sock *child,
864                                                   struct sk_buff *skb);
865 extern void                     tcp_enter_frto(struct sock *sk);
866 extern void                     tcp_enter_loss(struct sock *sk, int how);
867 extern void                     tcp_clear_retrans(struct tcp_opt *tp);
868 extern void                     tcp_update_metrics(struct sock *sk);
869
870 extern void                     tcp_close(struct sock *sk, 
871                                           long timeout);
872 extern struct sock *            tcp_accept(struct sock *sk, int flags, int *err);
873 extern unsigned int             tcp_poll(struct file * file, struct socket *sock, struct poll_table_struct *wait);
874
875 extern int                      tcp_getsockopt(struct sock *sk, int level, 
876                                                int optname,
877                                                char __user *optval, 
878                                                int __user *optlen);
879 extern int                      tcp_setsockopt(struct sock *sk, int level, 
880                                                int optname, char __user *optval, 
881                                                int optlen);
882 extern void                     tcp_set_keepalive(struct sock *sk, int val);
883 extern int                      tcp_recvmsg(struct kiocb *iocb, struct sock *sk,
884                                             struct msghdr *msg,
885                                             size_t len, int nonblock, 
886                                             int flags, int *addr_len);
887
888 extern int                      tcp_listen_start(struct sock *sk);
889
890 extern void                     tcp_parse_options(struct sk_buff *skb,
891                                                   struct tcp_opt *tp,
892                                                   int estab);
893
894 /*
895  *      TCP v4 functions exported for the inet6 API
896  */
897
898 extern int                      tcp_v4_rebuild_header(struct sock *sk);
899
900 extern int                      tcp_v4_build_header(struct sock *sk, 
901                                                     struct sk_buff *skb);
902
903 extern void                     tcp_v4_send_check(struct sock *sk, 
904                                                   struct tcphdr *th, int len, 
905                                                   struct sk_buff *skb);
906
907 extern int                      tcp_v4_conn_request(struct sock *sk,
908                                                     struct sk_buff *skb);
909
910 extern struct sock *            tcp_create_openreq_child(struct sock *sk,
911                                                          struct open_request *req,
912                                                          struct sk_buff *skb);
913
914 extern struct sock *            tcp_v4_syn_recv_sock(struct sock *sk,
915                                                      struct sk_buff *skb,
916                                                      struct open_request *req,
917                                                         struct dst_entry *dst);
918
919 extern int                      tcp_v4_do_rcv(struct sock *sk,
920                                               struct sk_buff *skb);
921
922 extern int                      tcp_v4_connect(struct sock *sk,
923                                                struct sockaddr *uaddr,
924                                                int addr_len);
925
926 extern int                      tcp_connect(struct sock *sk);
927
928 extern struct sk_buff *         tcp_make_synack(struct sock *sk,
929                                                 struct dst_entry *dst,
930                                                 struct open_request *req);
931
932 extern int                      tcp_disconnect(struct sock *sk, int flags);
933
934 extern void                     tcp_unhash(struct sock *sk);
935
936 extern int                      tcp_v4_hash_connecting(struct sock *sk);
937
938
939 /* From syncookies.c */
940 extern struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb, 
941                                     struct ip_options *opt);
942 extern __u32 cookie_v4_init_sequence(struct sock *sk, struct sk_buff *skb, 
943                                      __u16 *mss);
944
945 /* tcp_output.c */
946
947 extern int tcp_write_xmit(struct sock *, int nonagle);
948 extern int tcp_retransmit_skb(struct sock *, struct sk_buff *);
949 extern void tcp_xmit_retransmit_queue(struct sock *);
950 extern void tcp_simple_retransmit(struct sock *);
951
952 extern void tcp_send_probe0(struct sock *);
953 extern void tcp_send_partial(struct sock *);
954 extern int  tcp_write_wakeup(struct sock *);
955 extern void tcp_send_fin(struct sock *sk);
956 extern void tcp_send_active_reset(struct sock *sk, int priority);
957 extern int  tcp_send_synack(struct sock *);
958 extern int  tcp_transmit_skb(struct sock *, struct sk_buff *);
959 extern void tcp_push_one(struct sock *, unsigned mss_now);
960 extern void tcp_send_ack(struct sock *sk);
961 extern void tcp_send_delayed_ack(struct sock *sk);
962
963 /* tcp_timer.c */
964 extern void tcp_init_xmit_timers(struct sock *);
965 extern void tcp_clear_xmit_timers(struct sock *);
966
967 extern void tcp_delete_keepalive_timer (struct sock *);
968 extern void tcp_reset_keepalive_timer (struct sock *, unsigned long);
969 extern int tcp_sync_mss(struct sock *sk, u32 pmtu);
970
971 extern const char timer_bug_msg[];
972
973 /* tcp_diag.c */
974 extern void tcp_get_info(struct sock *, struct tcp_info *);
975
976 /* Read 'sendfile()'-style from a TCP socket */
977 typedef int (*sk_read_actor_t)(read_descriptor_t *, struct sk_buff *,
978                                 unsigned int, size_t);
979 extern int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
980                          sk_read_actor_t recv_actor);
981
982 static inline void tcp_clear_xmit_timer(struct sock *sk, int what)
983 {
984         struct tcp_opt *tp = tcp_sk(sk);
985         
986         switch (what) {
987         case TCP_TIME_RETRANS:
988         case TCP_TIME_PROBE0:
989                 tp->pending = 0;
990
991 #ifdef TCP_CLEAR_TIMERS
992                 sk_stop_timer(sk, &tp->retransmit_timer);
993 #endif
994                 break;
995         case TCP_TIME_DACK:
996                 tp->ack.blocked = 0;
997                 tp->ack.pending = 0;
998
999 #ifdef TCP_CLEAR_TIMERS
1000                 sk_stop_timer(sk, &tp->delack_timer);
1001 #endif
1002                 break;
1003         default:
1004                 printk(timer_bug_msg);
1005                 return;
1006         };
1007
1008 }
1009
1010 /*
1011  *      Reset the retransmission timer
1012  */
1013 static inline void tcp_reset_xmit_timer(struct sock *sk, int what, unsigned long when)
1014 {
1015         struct tcp_opt *tp = tcp_sk(sk);
1016
1017         if (when > TCP_RTO_MAX) {
1018 #ifdef TCP_DEBUG
1019                 printk(KERN_DEBUG "reset_xmit_timer sk=%p %d when=0x%lx, caller=%p\n", sk, what, when, current_text_addr());
1020 #endif
1021                 when = TCP_RTO_MAX;
1022         }
1023
1024         switch (what) {
1025         case TCP_TIME_RETRANS:
1026         case TCP_TIME_PROBE0:
1027                 tp->pending = what;
1028                 tp->timeout = jiffies+when;
1029                 sk_reset_timer(sk, &tp->retransmit_timer, tp->timeout);
1030                 break;
1031
1032         case TCP_TIME_DACK:
1033                 tp->ack.pending |= TCP_ACK_TIMER;
1034                 tp->ack.timeout = jiffies+when;
1035                 sk_reset_timer(sk, &tp->delack_timer, tp->ack.timeout);
1036                 break;
1037
1038         default:
1039                 printk(timer_bug_msg);
1040         };
1041 }
1042
1043 /* Compute the current effective MSS, taking SACKs and IP options,
1044  * and even PMTU discovery events into account.
1045  *
1046  * LARGESEND note: !urg_mode is overkill, only frames up to snd_up
1047  * cannot be large. However, taking into account rare use of URG, this
1048  * is not a big flaw.
1049  */
1050
1051 static __inline__ unsigned int tcp_current_mss(struct sock *sk, int large)
1052 {
1053         struct tcp_opt *tp = tcp_sk(sk);
1054         struct dst_entry *dst = __sk_dst_get(sk);
1055         int mss_now = large && (sk->sk_route_caps & NETIF_F_TSO) &&
1056                       !tp->urg_mode ?
1057                 tp->mss_cache : tp->mss_cache_std;
1058
1059         if (dst) {
1060                 u32 mtu = dst_pmtu(dst);
1061                 if (mtu != tp->pmtu_cookie ||
1062                     tp->ext2_header_len != dst->header_len)
1063                         mss_now = tcp_sync_mss(sk, mtu);
1064         }
1065         if (tp->eff_sacks)
1066                 mss_now -= (TCPOLEN_SACK_BASE_ALIGNED +
1067                             (tp->eff_sacks * TCPOLEN_SACK_PERBLOCK));
1068         return mss_now;
1069 }
1070
1071 /* Initialize RCV_MSS value.
1072  * RCV_MSS is an our guess about MSS used by the peer.
1073  * We haven't any direct information about the MSS.
1074  * It's better to underestimate the RCV_MSS rather than overestimate.
1075  * Overestimations make us ACKing less frequently than needed.
1076  * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
1077  */
1078
1079 static inline void tcp_initialize_rcv_mss(struct sock *sk)
1080 {
1081         struct tcp_opt *tp = tcp_sk(sk);
1082         unsigned int hint = min(tp->advmss, tp->mss_cache_std);
1083
1084         hint = min(hint, tp->rcv_wnd/2);
1085         hint = min(hint, TCP_MIN_RCVMSS);
1086         hint = max(hint, TCP_MIN_MSS);
1087
1088         tp->ack.rcv_mss = hint;
1089 }
1090
1091 static __inline__ void __tcp_fast_path_on(struct tcp_opt *tp, u32 snd_wnd)
1092 {
1093         tp->pred_flags = htonl((tp->tcp_header_len << 26) |
1094                                ntohl(TCP_FLAG_ACK) |
1095                                snd_wnd);
1096 }
1097
1098 static __inline__ void tcp_fast_path_on(struct tcp_opt *tp)
1099 {
1100         __tcp_fast_path_on(tp, tp->snd_wnd>>tp->snd_wscale);
1101 }
1102
1103 static inline void tcp_fast_path_check(struct sock *sk, struct tcp_opt *tp)
1104 {
1105         if (skb_queue_len(&tp->out_of_order_queue) == 0 &&
1106             tp->rcv_wnd &&
1107             atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf &&
1108             !tp->urg_data)
1109                 tcp_fast_path_on(tp);
1110 }
1111
1112 /* Compute the actual receive window we are currently advertising.
1113  * Rcv_nxt can be after the window if our peer push more data
1114  * than the offered window.
1115  */
1116 static __inline__ u32 tcp_receive_window(struct tcp_opt *tp)
1117 {
1118         s32 win = tp->rcv_wup + tp->rcv_wnd - tp->rcv_nxt;
1119
1120         if (win < 0)
1121                 win = 0;
1122         return (u32) win;
1123 }
1124
1125 /* Choose a new window, without checks for shrinking, and without
1126  * scaling applied to the result.  The caller does these things
1127  * if necessary.  This is a "raw" window selection.
1128  */
1129 extern u32      __tcp_select_window(struct sock *sk);
1130
1131 /* TCP timestamps are only 32-bits, this causes a slight
1132  * complication on 64-bit systems since we store a snapshot
1133  * of jiffies in the buffer control blocks below.  We decidely
1134  * only use of the low 32-bits of jiffies and hide the ugly
1135  * casts with the following macro.
1136  */
1137 #define tcp_time_stamp          ((__u32)(jiffies))
1138
1139 /* This is what the send packet queueing engine uses to pass
1140  * TCP per-packet control information to the transmission
1141  * code.  We also store the host-order sequence numbers in
1142  * here too.  This is 36 bytes on 32-bit architectures,
1143  * 40 bytes on 64-bit machines, if this grows please adjust
1144  * skbuff.h:skbuff->cb[xxx] size appropriately.
1145  */
1146 struct tcp_skb_cb {
1147         union {
1148                 struct inet_skb_parm    h4;
1149 #if defined(CONFIG_IPV6) || defined (CONFIG_IPV6_MODULE)
1150                 struct inet6_skb_parm   h6;
1151 #endif
1152         } header;       /* For incoming frames          */
1153         __u32           seq;            /* Starting sequence number     */
1154         __u32           end_seq;        /* SEQ + FIN + SYN + datalen    */
1155         __u32           when;           /* used to compute rtt's        */
1156         __u8            flags;          /* TCP header flags.            */
1157
1158         /* NOTE: These must match up to the flags byte in a
1159          *       real TCP header.
1160          */
1161 #define TCPCB_FLAG_FIN          0x01
1162 #define TCPCB_FLAG_SYN          0x02
1163 #define TCPCB_FLAG_RST          0x04
1164 #define TCPCB_FLAG_PSH          0x08
1165 #define TCPCB_FLAG_ACK          0x10
1166 #define TCPCB_FLAG_URG          0x20
1167 #define TCPCB_FLAG_ECE          0x40
1168 #define TCPCB_FLAG_CWR          0x80
1169
1170         __u8            sacked;         /* State flags for SACK/FACK.   */
1171 #define TCPCB_SACKED_ACKED      0x01    /* SKB ACK'd by a SACK block    */
1172 #define TCPCB_SACKED_RETRANS    0x02    /* SKB retransmitted            */
1173 #define TCPCB_LOST              0x04    /* SKB is lost                  */
1174 #define TCPCB_TAGBITS           0x07    /* All tag bits                 */
1175
1176 #define TCPCB_EVER_RETRANS      0x80    /* Ever retransmitted frame     */
1177 #define TCPCB_RETRANS           (TCPCB_SACKED_RETRANS|TCPCB_EVER_RETRANS)
1178
1179 #define TCPCB_URG               0x20    /* Urgent pointer advenced here */
1180
1181 #define TCPCB_AT_TAIL           (TCPCB_URG)
1182
1183         __u16           urg_ptr;        /* Valid w/URG flags is set.    */
1184         __u32           ack_seq;        /* Sequence number ACK'd        */
1185 };
1186
1187 #define TCP_SKB_CB(__skb)       ((struct tcp_skb_cb *)&((__skb)->cb[0]))
1188
1189 #include <net/tcp_ecn.h>
1190
1191 /* This determines how many packets are "in the network" to the best
1192  * of our knowledge.  In many cases it is conservative, but where
1193  * detailed information is available from the receiver (via SACK
1194  * blocks etc.) we can make more aggressive calculations.
1195  *
1196  * Use this for decisions involving congestion control, use just
1197  * tp->packets_out to determine if the send queue is empty or not.
1198  *
1199  * Read this equation as:
1200  *
1201  *      "Packets sent once on transmission queue" MINUS
1202  *      "Packets left network, but not honestly ACKed yet" PLUS
1203  *      "Packets fast retransmitted"
1204  */
1205 static __inline__ unsigned int tcp_packets_in_flight(struct tcp_opt *tp)
1206 {
1207         return tp->packets_out - tp->left_out + tp->retrans_out;
1208 }
1209
1210 /* Recalculate snd_ssthresh, we want to set it to:
1211  *
1212  * Reno:
1213  *      one half the current congestion window, but no
1214  *      less than two segments
1215  *
1216  * BIC:
1217  *      behave like Reno until low_window is reached,
1218  *      then increase congestion window slowly
1219  */
1220 static inline __u32 tcp_recalc_ssthresh(struct tcp_opt *tp)
1221 {
1222         if (sysctl_tcp_bic) {
1223                 if (sysctl_tcp_bic_fast_convergence &&
1224                     tp->snd_cwnd < tp->bictcp.last_max_cwnd)
1225                         tp->bictcp.last_max_cwnd
1226                                 = (tp->snd_cwnd * (2*BICTCP_1_OVER_BETA-1))
1227                                 / (BICTCP_1_OVER_BETA/2);
1228                 else
1229                         tp->bictcp.last_max_cwnd = tp->snd_cwnd;
1230
1231                 if (tp->snd_cwnd > sysctl_tcp_bic_low_window)
1232                         return max(tp->snd_cwnd - (tp->snd_cwnd/BICTCP_1_OVER_BETA),
1233                                    2U);
1234         }
1235
1236         return max(tp->snd_cwnd >> 1U, 2U);
1237 }
1238
1239 /* Stop taking Vegas samples for now. */
1240 #define tcp_vegas_disable(__tp) ((__tp)->vegas.doing_vegas_now = 0)
1241
1242 /* Is this TCP connection using Vegas (regardless of whether it is taking
1243  * Vegas measurements at the current time)?
1244  */
1245 #define tcp_is_vegas(__tp)      ((__tp)->vegas.do_vegas)
1246     
1247 static inline void tcp_vegas_enable(struct tcp_opt *tp)
1248 {
1249         /* There are several situations when we must "re-start" Vegas:
1250          *
1251          *  o when a connection is established
1252          *  o after an RTO
1253          *  o after fast recovery
1254          *  o when we send a packet and there is no outstanding
1255          *    unacknowledged data (restarting an idle connection)
1256          *
1257          * In these circumstances we cannot do a Vegas calculation at the
1258          * end of the first RTT, because any calculation we do is using
1259          * stale info -- both the saved cwnd and congestion feedback are
1260          * stale.
1261          *
1262          * Instead we must wait until the completion of an RTT during
1263          * which we actually receive ACKs.
1264          */
1265     
1266         /* Begin taking Vegas samples next time we send something. */
1267         tp->vegas.doing_vegas_now = 1;
1268      
1269         /* Set the beginning of the next send window. */
1270         tp->vegas.beg_snd_nxt = tp->snd_nxt;
1271
1272         tp->vegas.cntRTT = 0;
1273         tp->vegas.minRTT = 0x7fffffff;
1274 }
1275
1276 /* Should we be taking Vegas samples right now? */
1277 #define tcp_vegas_enabled(__tp) ((__tp)->vegas.doing_vegas_now)
1278
1279 extern void tcp_vegas_init(struct tcp_opt *tp);
1280
1281 static inline void tcp_set_ca_state(struct tcp_opt *tp, u8 ca_state)
1282 {
1283         if (tcp_is_vegas(tp)) {
1284                 if (ca_state == TCP_CA_Open) 
1285                         tcp_vegas_enable(tp);
1286                 else
1287                         tcp_vegas_disable(tp);
1288         }
1289         tp->ca_state = ca_state;
1290 }
1291
1292 /* If cwnd > ssthresh, we may raise ssthresh to be half-way to cwnd.
1293  * The exception is rate halving phase, when cwnd is decreasing towards
1294  * ssthresh.
1295  */
1296 static inline __u32 tcp_current_ssthresh(struct tcp_opt *tp)
1297 {
1298         if ((1<<tp->ca_state)&(TCPF_CA_CWR|TCPF_CA_Recovery))
1299                 return tp->snd_ssthresh;
1300         else
1301                 return max(tp->snd_ssthresh,
1302                            ((tp->snd_cwnd >> 1) +
1303                             (tp->snd_cwnd >> 2)));
1304 }
1305
1306 static inline void tcp_sync_left_out(struct tcp_opt *tp)
1307 {
1308         if (tp->sack_ok && tp->sacked_out >= tp->packets_out - tp->lost_out)
1309                 tp->sacked_out = tp->packets_out - tp->lost_out;
1310         tp->left_out = tp->sacked_out + tp->lost_out;
1311 }
1312
1313 extern void tcp_cwnd_application_limited(struct sock *sk);
1314
1315 /* Congestion window validation. (RFC2861) */
1316
1317 static inline void tcp_cwnd_validate(struct sock *sk, struct tcp_opt *tp)
1318 {
1319         if (tp->packets_out >= tp->snd_cwnd) {
1320                 /* Network is feed fully. */
1321                 tp->snd_cwnd_used = 0;
1322                 tp->snd_cwnd_stamp = tcp_time_stamp;
1323         } else {
1324                 /* Network starves. */
1325                 if (tp->packets_out > tp->snd_cwnd_used)
1326                         tp->snd_cwnd_used = tp->packets_out;
1327
1328                 if ((s32)(tcp_time_stamp - tp->snd_cwnd_stamp) >= tp->rto)
1329                         tcp_cwnd_application_limited(sk);
1330         }
1331 }
1332
1333 /* Set slow start threshould and cwnd not falling to slow start */
1334 static inline void __tcp_enter_cwr(struct tcp_opt *tp)
1335 {
1336         tp->undo_marker = 0;
1337         tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
1338         tp->snd_cwnd = min(tp->snd_cwnd,
1339                            tcp_packets_in_flight(tp) + 1U);
1340         tp->snd_cwnd_cnt = 0;
1341         tp->high_seq = tp->snd_nxt;
1342         tp->snd_cwnd_stamp = tcp_time_stamp;
1343         TCP_ECN_queue_cwr(tp);
1344 }
1345
1346 static inline void tcp_enter_cwr(struct tcp_opt *tp)
1347 {
1348         tp->prior_ssthresh = 0;
1349         if (tp->ca_state < TCP_CA_CWR) {
1350                 __tcp_enter_cwr(tp);
1351                 tcp_set_ca_state(tp, TCP_CA_CWR);
1352         }
1353 }
1354
1355 extern __u32 tcp_init_cwnd(struct tcp_opt *tp, struct dst_entry *dst);
1356
1357 /* Slow start with delack produces 3 packets of burst, so that
1358  * it is safe "de facto".
1359  */
1360 static __inline__ __u32 tcp_max_burst(struct tcp_opt *tp)
1361 {
1362         return 3;
1363 }
1364
1365 static __inline__ int tcp_minshall_check(struct tcp_opt *tp)
1366 {
1367         return after(tp->snd_sml,tp->snd_una) &&
1368                 !after(tp->snd_sml, tp->snd_nxt);
1369 }
1370
1371 static __inline__ void tcp_minshall_update(struct tcp_opt *tp, int mss, struct sk_buff *skb)
1372 {
1373         if (skb->len < mss)
1374                 tp->snd_sml = TCP_SKB_CB(skb)->end_seq;
1375 }
1376
1377 /* Return 0, if packet can be sent now without violation Nagle's rules:
1378    1. It is full sized.
1379    2. Or it contains FIN.
1380    3. Or TCP_NODELAY was set.
1381    4. Or TCP_CORK is not set, and all sent packets are ACKed.
1382       With Minshall's modification: all sent small packets are ACKed.
1383  */
1384
1385 static __inline__ int
1386 tcp_nagle_check(struct tcp_opt *tp, struct sk_buff *skb, unsigned mss_now, int nonagle)
1387 {
1388         return (skb->len < mss_now &&
1389                 !(TCP_SKB_CB(skb)->flags & TCPCB_FLAG_FIN) &&
1390                 ((nonagle&TCP_NAGLE_CORK) ||
1391                  (!nonagle &&
1392                   tp->packets_out &&
1393                   tcp_minshall_check(tp))));
1394 }
1395
1396 /* This checks if the data bearing packet SKB (usually sk->sk_send_head)
1397  * should be put on the wire right now.
1398  */
1399 static __inline__ int tcp_snd_test(struct tcp_opt *tp, struct sk_buff *skb,
1400                                    unsigned cur_mss, int nonagle)
1401 {
1402         /*      RFC 1122 - section 4.2.3.4
1403          *
1404          *      We must queue if
1405          *
1406          *      a) The right edge of this frame exceeds the window
1407          *      b) There are packets in flight and we have a small segment
1408          *         [SWS avoidance and Nagle algorithm]
1409          *         (part of SWS is done on packetization)
1410          *         Minshall version sounds: there are no _small_
1411          *         segments in flight. (tcp_nagle_check)
1412          *      c) We have too many packets 'in flight'
1413          *
1414          *      Don't use the nagle rule for urgent data (or
1415          *      for the final FIN -DaveM).
1416          *
1417          *      Also, Nagle rule does not apply to frames, which
1418          *      sit in the middle of queue (they have no chances
1419          *      to get new data) and if room at tail of skb is
1420          *      not enough to save something seriously (<32 for now).
1421          */
1422
1423         /* Don't be strict about the congestion window for the
1424          * final FIN frame.  -DaveM
1425          */
1426         return (((nonagle&TCP_NAGLE_PUSH) || tp->urg_mode
1427                  || !tcp_nagle_check(tp, skb, cur_mss, nonagle)) &&
1428                 ((tcp_packets_in_flight(tp) < tp->snd_cwnd) ||
1429                  (TCP_SKB_CB(skb)->flags & TCPCB_FLAG_FIN)) &&
1430                 !after(TCP_SKB_CB(skb)->end_seq, tp->snd_una + tp->snd_wnd));
1431 }
1432
1433 static __inline__ void tcp_check_probe_timer(struct sock *sk, struct tcp_opt *tp)
1434 {
1435         if (!tp->packets_out && !tp->pending)
1436                 tcp_reset_xmit_timer(sk, TCP_TIME_PROBE0, tp->rto);
1437 }
1438
1439 static __inline__ int tcp_skb_is_last(struct sock *sk, struct sk_buff *skb)
1440 {
1441         return skb->next == (struct sk_buff *)&sk->sk_write_queue;
1442 }
1443
1444 /* Push out any pending frames which were held back due to
1445  * TCP_CORK or attempt at coalescing tiny packets.
1446  * The socket must be locked by the caller.
1447  */
1448 static __inline__ void __tcp_push_pending_frames(struct sock *sk,
1449                                                  struct tcp_opt *tp,
1450                                                  unsigned cur_mss,
1451                                                  int nonagle)
1452 {
1453         struct sk_buff *skb = sk->sk_send_head;
1454
1455         if (skb) {
1456                 if (!tcp_skb_is_last(sk, skb))
1457                         nonagle = TCP_NAGLE_PUSH;
1458                 if (!tcp_snd_test(tp, skb, cur_mss, nonagle) ||
1459                     tcp_write_xmit(sk, nonagle))
1460                         tcp_check_probe_timer(sk, tp);
1461         }
1462         tcp_cwnd_validate(sk, tp);
1463 }
1464
1465 static __inline__ void tcp_push_pending_frames(struct sock *sk,
1466                                                struct tcp_opt *tp)
1467 {
1468         __tcp_push_pending_frames(sk, tp, tcp_current_mss(sk, 1), tp->nonagle);
1469 }
1470
1471 static __inline__ int tcp_may_send_now(struct sock *sk, struct tcp_opt *tp)
1472 {
1473         struct sk_buff *skb = sk->sk_send_head;
1474
1475         return (skb &&
1476                 tcp_snd_test(tp, skb, tcp_current_mss(sk, 1),
1477                              tcp_skb_is_last(sk, skb) ? TCP_NAGLE_PUSH : tp->nonagle));
1478 }
1479
1480 static __inline__ void tcp_init_wl(struct tcp_opt *tp, u32 ack, u32 seq)
1481 {
1482         tp->snd_wl1 = seq;
1483 }
1484
1485 static __inline__ void tcp_update_wl(struct tcp_opt *tp, u32 ack, u32 seq)
1486 {
1487         tp->snd_wl1 = seq;
1488 }
1489
1490 extern void                     tcp_destroy_sock(struct sock *sk);
1491
1492
1493 /*
1494  * Calculate(/check) TCP checksum
1495  */
1496 static __inline__ u16 tcp_v4_check(struct tcphdr *th, int len,
1497                                    unsigned long saddr, unsigned long daddr, 
1498                                    unsigned long base)
1499 {
1500         return csum_tcpudp_magic(saddr,daddr,len,IPPROTO_TCP,base);
1501 }
1502
1503 static __inline__ int __tcp_checksum_complete(struct sk_buff *skb)
1504 {
1505         return (unsigned short)csum_fold(skb_checksum(skb, 0, skb->len, skb->csum));
1506 }
1507
1508 static __inline__ int tcp_checksum_complete(struct sk_buff *skb)
1509 {
1510         return skb->ip_summed != CHECKSUM_UNNECESSARY &&
1511                 __tcp_checksum_complete(skb);
1512 }
1513
1514 /* Prequeue for VJ style copy to user, combined with checksumming. */
1515
1516 static __inline__ void tcp_prequeue_init(struct tcp_opt *tp)
1517 {
1518         tp->ucopy.task = NULL;
1519         tp->ucopy.len = 0;
1520         tp->ucopy.memory = 0;
1521         skb_queue_head_init(&tp->ucopy.prequeue);
1522 }
1523
1524 /* Packet is added to VJ-style prequeue for processing in process
1525  * context, if a reader task is waiting. Apparently, this exciting
1526  * idea (VJ's mail "Re: query about TCP header on tcp-ip" of 07 Sep 93)
1527  * failed somewhere. Latency? Burstiness? Well, at least now we will
1528  * see, why it failed. 8)8)                               --ANK
1529  *
1530  * NOTE: is this not too big to inline?
1531  */
1532 static __inline__ int tcp_prequeue(struct sock *sk, struct sk_buff *skb)
1533 {
1534         struct tcp_opt *tp = tcp_sk(sk);
1535
1536         if (!sysctl_tcp_low_latency && tp->ucopy.task) {
1537                 __skb_queue_tail(&tp->ucopy.prequeue, skb);
1538                 tp->ucopy.memory += skb->truesize;
1539                 if (tp->ucopy.memory > sk->sk_rcvbuf) {
1540                         struct sk_buff *skb1;
1541
1542                         BUG_ON(sock_owned_by_user(sk));
1543
1544                         while ((skb1 = __skb_dequeue(&tp->ucopy.prequeue)) != NULL) {
1545                                 sk->sk_backlog_rcv(sk, skb1);
1546                                 NET_INC_STATS_BH(LINUX_MIB_TCPPREQUEUEDROPPED);
1547                         }
1548
1549                         tp->ucopy.memory = 0;
1550                 } else if (skb_queue_len(&tp->ucopy.prequeue) == 1) {
1551                         wake_up_interruptible(sk->sk_sleep);
1552                         if (!tcp_ack_scheduled(tp))
1553                                 tcp_reset_xmit_timer(sk, TCP_TIME_DACK, (3*TCP_RTO_MIN)/4);
1554                 }
1555                 return 1;
1556         }
1557         return 0;
1558 }
1559
1560
1561 #undef STATE_TRACE
1562
1563 #ifdef STATE_TRACE
1564 static char *statename[]={
1565         "Unused","Established","Syn Sent","Syn Recv",
1566         "Fin Wait 1","Fin Wait 2","Time Wait", "Close",
1567         "Close Wait","Last ACK","Listen","Closing"
1568 };
1569 #endif
1570
1571 static __inline__ void tcp_set_state(struct sock *sk, int state)
1572 {
1573         int oldstate = sk->sk_state;
1574
1575         switch (state) {
1576         case TCP_ESTABLISHED:
1577                 if (oldstate != TCP_ESTABLISHED)
1578                         TCP_INC_STATS(TCP_MIB_CURRESTAB);
1579                 break;
1580
1581         case TCP_CLOSE:
1582                 if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
1583                         TCP_INC_STATS(TCP_MIB_ESTABRESETS);
1584
1585                 sk->sk_prot->unhash(sk);
1586                 if (tcp_sk(sk)->bind_hash &&
1587                     !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
1588                         tcp_put_port(sk);
1589                 /* fall through */
1590         default:
1591                 if (oldstate==TCP_ESTABLISHED)
1592                         TCP_DEC_STATS(TCP_MIB_CURRESTAB);
1593         }
1594
1595         /* Change state AFTER socket is unhashed to avoid closed
1596          * socket sitting in hash tables.
1597          */
1598         sk->sk_state = state;
1599
1600 #ifdef STATE_TRACE
1601         SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n",sk, statename[oldstate],statename[state]);
1602 #endif  
1603 }
1604
1605 static __inline__ void tcp_done(struct sock *sk)
1606 {
1607         tcp_set_state(sk, TCP_CLOSE);
1608         tcp_clear_xmit_timers(sk);
1609
1610         sk->sk_shutdown = SHUTDOWN_MASK;
1611
1612         if (!sock_flag(sk, SOCK_DEAD))
1613                 sk->sk_state_change(sk);
1614         else
1615                 tcp_destroy_sock(sk);
1616 }
1617
1618 static __inline__ void tcp_sack_reset(struct tcp_opt *tp)
1619 {
1620         tp->dsack = 0;
1621         tp->eff_sacks = 0;
1622         tp->num_sacks = 0;
1623 }
1624
1625 static __inline__ void tcp_build_and_update_options(__u32 *ptr, struct tcp_opt *tp, __u32 tstamp)
1626 {
1627         if (tp->tstamp_ok) {
1628                 *ptr++ = __constant_htonl((TCPOPT_NOP << 24) |
1629                                           (TCPOPT_NOP << 16) |
1630                                           (TCPOPT_TIMESTAMP << 8) |
1631                                           TCPOLEN_TIMESTAMP);
1632                 *ptr++ = htonl(tstamp);
1633                 *ptr++ = htonl(tp->ts_recent);
1634         }
1635         if (tp->eff_sacks) {
1636                 struct tcp_sack_block *sp = tp->dsack ? tp->duplicate_sack : tp->selective_acks;
1637                 int this_sack;
1638
1639                 *ptr++ = __constant_htonl((TCPOPT_NOP << 24) |
1640                                           (TCPOPT_NOP << 16) |
1641                                           (TCPOPT_SACK << 8) |
1642                                           (TCPOLEN_SACK_BASE +
1643                                            (tp->eff_sacks * TCPOLEN_SACK_PERBLOCK)));
1644                 for(this_sack = 0; this_sack < tp->eff_sacks; this_sack++) {
1645                         *ptr++ = htonl(sp[this_sack].start_seq);
1646                         *ptr++ = htonl(sp[this_sack].end_seq);
1647                 }
1648                 if (tp->dsack) {
1649                         tp->dsack = 0;
1650                         tp->eff_sacks--;
1651                 }
1652         }
1653 }
1654
1655 /* Construct a tcp options header for a SYN or SYN_ACK packet.
1656  * If this is every changed make sure to change the definition of
1657  * MAX_SYN_SIZE to match the new maximum number of options that you
1658  * can generate.
1659  */
1660 static inline void tcp_syn_build_options(__u32 *ptr, int mss, int ts, int sack,
1661                                              int offer_wscale, int wscale, __u32 tstamp, __u32 ts_recent)
1662 {
1663         /* We always get an MSS option.
1664          * The option bytes which will be seen in normal data
1665          * packets should timestamps be used, must be in the MSS
1666          * advertised.  But we subtract them from tp->mss_cache so
1667          * that calculations in tcp_sendmsg are simpler etc.
1668          * So account for this fact here if necessary.  If we
1669          * don't do this correctly, as a receiver we won't
1670          * recognize data packets as being full sized when we
1671          * should, and thus we won't abide by the delayed ACK
1672          * rules correctly.
1673          * SACKs don't matter, we never delay an ACK when we
1674          * have any of those going out.
1675          */
1676         *ptr++ = htonl((TCPOPT_MSS << 24) | (TCPOLEN_MSS << 16) | mss);
1677         if (ts) {
1678                 if(sack)
1679                         *ptr++ = __constant_htonl((TCPOPT_SACK_PERM << 24) | (TCPOLEN_SACK_PERM << 16) |
1680                                                   (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP);
1681                 else
1682                         *ptr++ = __constant_htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) |
1683                                                   (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP);
1684                 *ptr++ = htonl(tstamp);         /* TSVAL */
1685                 *ptr++ = htonl(ts_recent);      /* TSECR */
1686         } else if(sack)
1687                 *ptr++ = __constant_htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) |
1688                                           (TCPOPT_SACK_PERM << 8) | TCPOLEN_SACK_PERM);
1689         if (offer_wscale)
1690                 *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_WINDOW << 16) | (TCPOLEN_WINDOW << 8) | (wscale));
1691 }
1692
1693 /* Determine a window scaling and initial window to offer.
1694  * Based on the assumption that the given amount of space
1695  * will be offered. Store the results in the tp structure.
1696  * NOTE: for smooth operation initial space offering should
1697  * be a multiple of mss if possible. We assume here that mss >= 1.
1698  * This MUST be enforced by all callers.
1699  */
1700 static inline void tcp_select_initial_window(int __space, __u32 mss,
1701         __u32 *rcv_wnd,
1702         __u32 *window_clamp,
1703         int wscale_ok,
1704         __u8 *rcv_wscale)
1705 {
1706         unsigned int space = (__space < 0 ? 0 : __space);
1707
1708         /* If no clamp set the clamp to the max possible scaled window */
1709         if (*window_clamp == 0)
1710                 (*window_clamp) = (65535 << 14);
1711         space = min(*window_clamp, space);
1712
1713         /* Quantize space offering to a multiple of mss if possible. */
1714         if (space > mss)
1715                 space = (space / mss) * mss;
1716
1717         /* NOTE: offering an initial window larger than 32767
1718          * will break some buggy TCP stacks. We try to be nice.
1719          * If we are not window scaling, then this truncates
1720          * our initial window offering to 32k. There should also
1721          * be a sysctl option to stop being nice.
1722          */
1723         (*rcv_wnd) = min(space, MAX_TCP_WINDOW);
1724         (*rcv_wscale) = 0;
1725         if (wscale_ok) {
1726                 /* See RFC1323 for an explanation of the limit to 14 */
1727                 while (space > 65535 && (*rcv_wscale) < 14) {
1728                         space >>= 1;
1729                         (*rcv_wscale)++;
1730                 }
1731                 if (*rcv_wscale && sysctl_tcp_app_win && space>=mss &&
1732                     space - max((space>>sysctl_tcp_app_win), mss>>*rcv_wscale) < 65536/2)
1733                         (*rcv_wscale)--;
1734
1735                 *rcv_wscale = max((__u8)sysctl_tcp_default_win_scale,
1736                                   *rcv_wscale);
1737         }
1738
1739         /* Set initial window to value enough for senders,
1740          * following RFC1414. Senders, not following this RFC,
1741          * will be satisfied with 2.
1742          */
1743         if (mss > (1<<*rcv_wscale)) {
1744                 int init_cwnd = 4;
1745                 if (mss > 1460*3)
1746                         init_cwnd = 2;
1747                 else if (mss > 1460)
1748                         init_cwnd = 3;
1749                 if (*rcv_wnd > init_cwnd*mss)
1750                         *rcv_wnd = init_cwnd*mss;
1751         }
1752         /* Set the clamp no higher than max representable value */
1753         (*window_clamp) = min(65535U << (*rcv_wscale), *window_clamp);
1754 }
1755
1756 static inline int tcp_win_from_space(int space)
1757 {
1758         return sysctl_tcp_adv_win_scale<=0 ?
1759                 (space>>(-sysctl_tcp_adv_win_scale)) :
1760                 space - (space>>sysctl_tcp_adv_win_scale);
1761 }
1762
1763 /* Note: caller must be prepared to deal with negative returns */ 
1764 static inline int tcp_space(struct sock *sk)
1765 {
1766         return tcp_win_from_space(sk->sk_rcvbuf -
1767                                   atomic_read(&sk->sk_rmem_alloc));
1768
1769
1770 static inline int tcp_full_space( struct sock *sk)
1771 {
1772         return tcp_win_from_space(sk->sk_rcvbuf); 
1773 }
1774
1775 static inline void tcp_acceptq_queue(struct sock *sk, struct open_request *req,
1776                                          struct sock *child)
1777 {
1778         struct tcp_opt *tp = tcp_sk(sk);
1779
1780         req->sk = child;
1781         sk_acceptq_added(sk);
1782
1783         if (!tp->accept_queue_tail) {
1784                 tp->accept_queue = req;
1785         } else {
1786                 tp->accept_queue_tail->dl_next = req;
1787         }
1788         tp->accept_queue_tail = req;
1789         req->dl_next = NULL;
1790 }
1791
1792 struct tcp_listen_opt
1793 {
1794         u8                      max_qlen_log;   /* log_2 of maximal queued SYNs */
1795         int                     qlen;
1796         int                     qlen_young;
1797         int                     clock_hand;
1798         u32                     hash_rnd;
1799         struct open_request     *syn_table[TCP_SYNQ_HSIZE];
1800 };
1801
1802 static inline void
1803 tcp_synq_removed(struct sock *sk, struct open_request *req)
1804 {
1805         struct tcp_listen_opt *lopt = tcp_sk(sk)->listen_opt;
1806
1807         if (--lopt->qlen == 0)
1808                 tcp_delete_keepalive_timer(sk);
1809         if (req->retrans == 0)
1810                 lopt->qlen_young--;
1811 }
1812
1813 static inline void tcp_synq_added(struct sock *sk)
1814 {
1815         struct tcp_listen_opt *lopt = tcp_sk(sk)->listen_opt;
1816
1817         if (lopt->qlen++ == 0)
1818                 tcp_reset_keepalive_timer(sk, TCP_TIMEOUT_INIT);
1819         lopt->qlen_young++;
1820 }
1821
1822 static inline int tcp_synq_len(struct sock *sk)
1823 {
1824         return tcp_sk(sk)->listen_opt->qlen;
1825 }
1826
1827 static inline int tcp_synq_young(struct sock *sk)
1828 {
1829         return tcp_sk(sk)->listen_opt->qlen_young;
1830 }
1831
1832 static inline int tcp_synq_is_full(struct sock *sk)
1833 {
1834         return tcp_synq_len(sk) >> tcp_sk(sk)->listen_opt->max_qlen_log;
1835 }
1836
1837 static inline void tcp_synq_unlink(struct tcp_opt *tp, struct open_request *req,
1838                                        struct open_request **prev)
1839 {
1840         write_lock(&tp->syn_wait_lock);
1841         *prev = req->dl_next;
1842         write_unlock(&tp->syn_wait_lock);
1843 }
1844
1845 static inline void tcp_synq_drop(struct sock *sk, struct open_request *req,
1846                                      struct open_request **prev)
1847 {
1848         tcp_synq_unlink(tcp_sk(sk), req, prev);
1849         tcp_synq_removed(sk, req);
1850         tcp_openreq_free(req);
1851 }
1852
1853 static __inline__ void tcp_openreq_init(struct open_request *req,
1854                                         struct tcp_opt *tp,
1855                                         struct sk_buff *skb)
1856 {
1857         req->rcv_wnd = 0;               /* So that tcp_send_synack() knows! */
1858         req->rcv_isn = TCP_SKB_CB(skb)->seq;
1859         req->mss = tp->mss_clamp;
1860         req->ts_recent = tp->saw_tstamp ? tp->rcv_tsval : 0;
1861         req->tstamp_ok = tp->tstamp_ok;
1862         req->sack_ok = tp->sack_ok;
1863         req->snd_wscale = tp->snd_wscale;
1864         req->wscale_ok = tp->wscale_ok;
1865         req->acked = 0;
1866         req->ecn_ok = 0;
1867         req->rmt_port = skb->h.th->source;
1868 }
1869
1870 extern void tcp_enter_memory_pressure(void);
1871
1872 extern void tcp_listen_wlock(void);
1873
1874 /* - We may sleep inside this lock.
1875  * - If sleeping is not required (or called from BH),
1876  *   use plain read_(un)lock(&tcp_lhash_lock).
1877  */
1878
1879 static inline void tcp_listen_lock(void)
1880 {
1881         /* read_lock synchronizes to candidates to writers */
1882         read_lock(&tcp_lhash_lock);
1883         atomic_inc(&tcp_lhash_users);
1884         read_unlock(&tcp_lhash_lock);
1885 }
1886
1887 static inline void tcp_listen_unlock(void)
1888 {
1889         if (atomic_dec_and_test(&tcp_lhash_users))
1890                 wake_up(&tcp_lhash_wait);
1891 }
1892
1893 static inline int keepalive_intvl_when(struct tcp_opt *tp)
1894 {
1895         return tp->keepalive_intvl ? : sysctl_tcp_keepalive_intvl;
1896 }
1897
1898 static inline int keepalive_time_when(struct tcp_opt *tp)
1899 {
1900         return tp->keepalive_time ? : sysctl_tcp_keepalive_time;
1901 }
1902
1903 static inline int tcp_fin_time(struct tcp_opt *tp)
1904 {
1905         int fin_timeout = tp->linger2 ? : sysctl_tcp_fin_timeout;
1906
1907         if (fin_timeout < (tp->rto<<2) - (tp->rto>>1))
1908                 fin_timeout = (tp->rto<<2) - (tp->rto>>1);
1909
1910         return fin_timeout;
1911 }
1912
1913 static inline int tcp_paws_check(struct tcp_opt *tp, int rst)
1914 {
1915         if ((s32)(tp->rcv_tsval - tp->ts_recent) >= 0)
1916                 return 0;
1917         if (xtime.tv_sec >= tp->ts_recent_stamp + TCP_PAWS_24DAYS)
1918                 return 0;
1919
1920         /* RST segments are not recommended to carry timestamp,
1921            and, if they do, it is recommended to ignore PAWS because
1922            "their cleanup function should take precedence over timestamps."
1923            Certainly, it is mistake. It is necessary to understand the reasons
1924            of this constraint to relax it: if peer reboots, clock may go
1925            out-of-sync and half-open connections will not be reset.
1926            Actually, the problem would be not existing if all
1927            the implementations followed draft about maintaining clock
1928            via reboots. Linux-2.2 DOES NOT!
1929
1930            However, we can relax time bounds for RST segments to MSL.
1931          */
1932         if (rst && xtime.tv_sec >= tp->ts_recent_stamp + TCP_PAWS_MSL)
1933                 return 0;
1934         return 1;
1935 }
1936
1937 static inline void tcp_v4_setup_caps(struct sock *sk, struct dst_entry *dst)
1938 {
1939         sk->sk_route_caps = dst->dev->features;
1940         if (sk->sk_route_caps & NETIF_F_TSO) {
1941                 if (sk->sk_no_largesend || dst->header_len)
1942                         sk->sk_route_caps &= ~NETIF_F_TSO;
1943         }
1944 }
1945
1946 #define TCP_CHECK_TIMER(sk) do { } while (0)
1947
1948 static inline int tcp_use_frto(const struct sock *sk)
1949 {
1950         const struct tcp_opt *tp = tcp_sk(sk);
1951         
1952         /* F-RTO must be activated in sysctl and there must be some
1953          * unsent new data, and the advertised window should allow
1954          * sending it.
1955          */
1956         return (sysctl_tcp_frto && sk->sk_send_head &&
1957                 !after(TCP_SKB_CB(sk->sk_send_head)->end_seq,
1958                        tp->snd_una + tp->snd_wnd));
1959 }
1960
1961 static inline void tcp_mib_init(void)
1962 {
1963         /* See RFC 2012 */
1964         TCP_ADD_STATS_USER(TCP_MIB_RTOALGORITHM, 1);
1965         TCP_ADD_STATS_USER(TCP_MIB_RTOMIN, TCP_RTO_MIN*1000/HZ);
1966         TCP_ADD_STATS_USER(TCP_MIB_RTOMAX, TCP_RTO_MAX*1000/HZ);
1967         TCP_ADD_STATS_USER(TCP_MIB_MAXCONN, -1);
1968 }
1969
1970 /* /proc */
1971 enum tcp_seq_states {
1972         TCP_SEQ_STATE_LISTENING,
1973         TCP_SEQ_STATE_OPENREQ,
1974         TCP_SEQ_STATE_ESTABLISHED,
1975         TCP_SEQ_STATE_TIME_WAIT,
1976 };
1977
1978 struct tcp_seq_afinfo {
1979         struct module           *owner;
1980         char                    *name;
1981         sa_family_t             family;
1982         int                     (*seq_show) (struct seq_file *m, void *v);
1983         struct file_operations  *seq_fops;
1984 };
1985
1986 struct tcp_iter_state {
1987         sa_family_t             family;
1988         enum tcp_seq_states     state;
1989         struct sock             *syn_wait_sk;
1990         int                     bucket, sbucket, num, uid;
1991         struct seq_operations   seq_ops;
1992 };
1993
1994 extern int tcp_proc_register(struct tcp_seq_afinfo *afinfo);
1995 extern void tcp_proc_unregister(struct tcp_seq_afinfo *afinfo);
1996
1997 /* TCP Westwood functions and constants */
1998
1999 #define TCP_WESTWOOD_INIT_RTT  (20*HZ)           /* maybe too conservative?! */
2000 #define TCP_WESTWOOD_RTT_MIN   (HZ/20)           /* 50ms */
2001
2002 static inline void tcp_westwood_update_rtt(struct tcp_opt *tp, __u32 rtt_seq)
2003 {
2004         if (sysctl_tcp_westwood)
2005                 tp->westwood.rtt = rtt_seq;
2006 }
2007
2008 void __tcp_westwood_fast_bw(struct sock *, struct sk_buff *);
2009 void __tcp_westwood_slow_bw(struct sock *, struct sk_buff *);
2010
2011 static inline void tcp_westwood_fast_bw(struct sock *sk, struct sk_buff *skb)
2012 {
2013         if (sysctl_tcp_westwood)
2014                 __tcp_westwood_fast_bw(sk, skb);
2015 }
2016
2017 static inline void tcp_westwood_slow_bw(struct sock *sk, struct sk_buff *skb)
2018 {
2019         if (sysctl_tcp_westwood)
2020                 __tcp_westwood_slow_bw(sk, skb);
2021 }
2022
2023 static inline __u32 __tcp_westwood_bw_rttmin(const struct tcp_opt *tp)
2024 {
2025         return max((tp->westwood.bw_est) * (tp->westwood.rtt_min) /
2026                    (__u32) (tp->mss_cache),
2027                    2U);
2028 }
2029
2030 static inline __u32 tcp_westwood_bw_rttmin(const struct tcp_opt *tp)
2031 {
2032         return sysctl_tcp_westwood ? __tcp_westwood_bw_rttmin(tp) : 0;
2033 }
2034
2035 static inline int tcp_westwood_ssthresh(struct tcp_opt *tp)
2036 {
2037         __u32 ssthresh = 0;
2038
2039         if (sysctl_tcp_westwood) {
2040                 ssthresh = __tcp_westwood_bw_rttmin(tp);
2041                 if (ssthresh)
2042                         tp->snd_ssthresh = ssthresh;  
2043         }
2044
2045         return (ssthresh != 0);
2046 }
2047
2048 static inline int tcp_westwood_cwnd(struct tcp_opt *tp)
2049 {
2050         __u32 cwnd = 0;
2051
2052         if (sysctl_tcp_westwood) {
2053                 cwnd = __tcp_westwood_bw_rttmin(tp);
2054                 if (cwnd)
2055                         tp->snd_cwnd = cwnd;
2056         }
2057
2058         return (cwnd != 0);
2059 }
2060 #endif  /* _TCP_H */