home *** CD-ROM | disk | FTP | other *** search
/ Il CD di internet / CD.iso / SOURCE / KERNEL-S / V1.2 / LINUX-1.2 / LINUX-1 / linux / net / inet / tcp.c < prev    next >
Encoding:
Text File  |  1995-03-06  |  117.2 KB  |  5,098 lines

  1. /*
  2.  * INET        An implementation of the TCP/IP protocol suite for the LINUX
  3.  *        operating system.  INET is implemented using the  BSD Socket
  4.  *        interface as the means of communication with the user level.
  5.  *
  6.  *        Implementation of the Transmission Control Protocol(TCP).
  7.  *
  8.  * Version:    @(#)tcp.c    1.0.16    05/25/93
  9.  *
  10.  * Authors:    Ross Biro, <bir7@leland.Stanford.Edu>
  11.  *        Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  12.  *        Mark Evans, <evansmp@uhura.aston.ac.uk>
  13.  *        Corey Minyard <wf-rch!minyard@relay.EU.net>
  14.  *        Florian La Roche, <flla@stud.uni-sb.de>
  15.  *        Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
  16.  *        Linus Torvalds, <torvalds@cs.helsinki.fi>
  17.  *        Alan Cox, <gw4pts@gw4pts.ampr.org>
  18.  *        Matthew Dillon, <dillon@apollo.west.oic.com>
  19.  *        Arnt Gulbrandsen, <agulbra@no.unit.nvg>
  20.  *
  21.  * Fixes:    
  22.  *        Alan Cox    :    Numerous verify_area() calls
  23.  *        Alan Cox    :    Set the ACK bit on a reset
  24.  *        Alan Cox    :    Stopped it crashing if it closed while sk->inuse=1
  25.  *                    and was trying to connect (tcp_err()).
  26.  *        Alan Cox    :    All icmp error handling was broken
  27.  *                    pointers passed where wrong and the
  28.  *                    socket was looked up backwards. Nobody
  29.  *                    tested any icmp error code obviously.
  30.  *        Alan Cox    :    tcp_err() now handled properly. It wakes people
  31.  *                    on errors. select behaves and the icmp error race
  32.  *                    has gone by moving it into sock.c
  33.  *        Alan Cox    :    tcp_reset() fixed to work for everything not just
  34.  *                    packets for unknown sockets.
  35.  *        Alan Cox    :    tcp option processing.
  36.  *        Alan Cox    :    Reset tweaked (still not 100%) [Had syn rule wrong]
  37.  *        Herp Rosmanith  :    More reset fixes
  38.  *        Alan Cox    :    No longer acks invalid rst frames. Acking
  39.  *                    any kind of RST is right out.
  40.  *        Alan Cox    :    Sets an ignore me flag on an rst receive
  41.  *                    otherwise odd bits of prattle escape still
  42.  *        Alan Cox    :    Fixed another acking RST frame bug. Should stop
  43.  *                    LAN workplace lockups.
  44.  *        Alan Cox    :     Some tidyups using the new skb list facilities
  45.  *        Alan Cox    :    sk->keepopen now seems to work
  46.  *        Alan Cox    :    Pulls options out correctly on accepts
  47.  *        Alan Cox    :    Fixed assorted sk->rqueue->next errors
  48.  *        Alan Cox    :    PSH doesn't end a TCP read. Switched a bit to skb ops.
  49.  *        Alan Cox    :    Tidied tcp_data to avoid a potential nasty.
  50.  *        Alan Cox    :    Added some better commenting, as the tcp is hard to follow
  51.  *        Alan Cox    :    Removed incorrect check for 20 * psh
  52.  *    Michael O'Reilly    :    ack < copied bug fix.
  53.  *    Johannes Stille        :    Misc tcp fixes (not all in yet).
  54.  *        Alan Cox    :    FIN with no memory -> CRASH
  55.  *        Alan Cox    :    Added socket option proto entries. Also added awareness of them to accept.
  56.  *        Alan Cox    :    Added TCP options (SOL_TCP)
  57.  *        Alan Cox    :    Switched wakeup calls to callbacks, so the kernel can layer network sockets.
  58.  *        Alan Cox    :    Use ip_tos/ip_ttl settings.
  59.  *        Alan Cox    :    Handle FIN (more) properly (we hope).
  60.  *        Alan Cox    :    RST frames sent on unsynchronised state ack error/
  61.  *        Alan Cox    :    Put in missing check for SYN bit.
  62.  *        Alan Cox    :    Added tcp_select_window() aka NET2E 
  63.  *                    window non shrink trick.
  64.  *        Alan Cox    :    Added a couple of small NET2E timer fixes
  65.  *        Charles Hedrick :    TCP fixes
  66.  *        Toomas Tamm    :    TCP window fixes
  67.  *        Alan Cox    :    Small URG fix to rlogin ^C ack fight
  68.  *        Charles Hedrick    :    Rewrote most of it to actually work
  69.  *        Linus        :    Rewrote tcp_read() and URG handling
  70.  *                    completely
  71.  *        Gerhard Koerting:    Fixed some missing timer handling
  72.  *        Matthew Dillon  :    Reworked TCP machine states as per RFC
  73.  *        Gerhard Koerting:    PC/TCP workarounds
  74.  *        Adam Caldwell    :    Assorted timer/timing errors
  75.  *        Matthew Dillon    :    Fixed another RST bug
  76.  *        Alan Cox    :    Move to kernel side addressing changes.
  77.  *        Alan Cox    :    Beginning work on TCP fastpathing (not yet usable)
  78.  *        Arnt Gulbrandsen:    Turbocharged tcp_check() routine.
  79.  *        Alan Cox    :    TCP fast path debugging
  80.  *        Alan Cox    :    Window clamping
  81.  *        Michael Riepe    :    Bug in tcp_check()
  82.  *        Matt Dillon    :    More TCP improvements and RST bug fixes
  83.  *        Matt Dillon    :    Yet more small nasties remove from the TCP code
  84.  *                    (Be very nice to this man if tcp finally works 100%) 8)
  85.  *        Alan Cox    :    BSD accept semantics. 
  86.  *        Alan Cox    :    Reset on closedown bug.
  87.  *    Peter De Schrijver    :    ENOTCONN check missing in tcp_sendto().
  88.  *        Michael Pall    :    Handle select() after URG properly in all cases.
  89.  *        Michael Pall    :    Undo the last fix in tcp_read_urg() (multi URG PUSH broke rlogin).
  90.  *        Michael Pall    :    Fix the multi URG PUSH problem in tcp_readable(), select() after URG works now.
  91.  *        Michael Pall    :    recv(...,MSG_OOB) never blocks in the BSD api.
  92.  *        Alan Cox    :    Changed the semantics of sk->socket to 
  93.  *                    fix a race and a signal problem with
  94.  *                    accept() and async I/O.
  95.  *        Alan Cox    :    Relaxed the rules on tcp_sendto().
  96.  *        Yury Shevchuk    :    Really fixed accept() blocking problem.
  97.  *        Craig I. Hagan  :    Allow for BSD compatible TIME_WAIT for
  98.  *                    clients/servers which listen in on
  99.  *                    fixed ports.
  100.  *        Alan Cox    :    Cleaned the above up and shrank it to
  101.  *                    a sensible code size.
  102.  *        Alan Cox    :    Self connect lockup fix.
  103.  *        Alan Cox    :    No connect to multicast.
  104.  *        Ross Biro    :    Close unaccepted children on master
  105.  *                    socket close.
  106.  *        Alan Cox    :    Reset tracing code.
  107.  *        Alan Cox    :    Spurious resets on shutdown.
  108.  *        Alan Cox    :    Giant 15 minute/60 second timer error
  109.  *        Alan Cox    :    Small whoops in selecting before an accept.
  110.  *        Alan Cox    :    Kept the state trace facility since it's
  111.  *                    handy for debugging.
  112.  *        Alan Cox    :    More reset handler fixes.
  113.  *        Alan Cox    :    Started rewriting the code based on the RFC's
  114.  *                    for other useful protocol references see:  
  115.  *                    Comer, KA9Q NOS, and for a reference on the
  116.  *                    difference between specifications and how BSD
  117.  *                    works see the 4.4lite source.
  118.  *        A.N.Kuznetsov    :    Don't time wait on completion of tidy 
  119.  *                    close.
  120.  *        Linus Torvalds    :    Fin/Shutdown & copied_seq changes.
  121.  *        Linus Torvalds    :    Fixed BSD port reuse to work first syn
  122.  *        Alan Cox    :    Reimplemented timers as per the RFC and using multiple
  123.  *                    timers for sanity. 
  124.  *        Alan Cox    :    Small bug fixes, and a lot of new
  125.  *                    comments.
  126.  *        Alan Cox    :    Fixed dual reader crash by locking
  127.  *                    the buffers (much like datagram.c)
  128.  *        Alan Cox    :    Fixed stuck sockets in probe. A probe
  129.  *                    now gets fed up of retrying without
  130.  *                    (even a no space) answer.
  131.  *        Alan Cox    :    Extracted closing code better
  132.  *        Alan Cox    :    Fixed the closing state machine to
  133.  *                    resemble the RFC.
  134.  *        Alan Cox    :    More 'per spec' fixes.
  135.  *
  136.  *
  137.  * To Fix:
  138.  *        Fast path the code. Two things here - fix the window calculation
  139.  *        so it doesn't iterate over the queue, also spot packets with no funny
  140.  *        options arriving in order and process directly.
  141.  *
  142.  *        Implement RFC 1191 [Path MTU discovery]
  143.  *        Look at the effect of implementing RFC 1337 suggestions and their impact.
  144.  *        Rewrite output state machine to use a single queue and do low window
  145.  *        situations as per the spec (RFC 1122)
  146.  *        Speed up input assembly algorithm.
  147.  *        RFC1323 - PAWS and window scaling. PAWS is required for IPv6 so we
  148.  *        could do with it working on IPv4
  149.  *        User settable/learned rtt/max window/mtu
  150.  *        Cope with MTU/device switches when retransmitting in tcp.
  151.  *        Fix the window handling to use PR's new code.
  152.  *
  153.  *        Change the fundamental structure to a single send queue maintained
  154.  *        by TCP (removing the bogus ip stuff [thus fixing mtu drops on
  155.  *        active routes too]). Cut the queue off in tcp_retransmit/
  156.  *        tcp_transmit.
  157.  *        Change the receive queue to assemble as it goes. This lets us
  158.  *        dispose of most of tcp_sequence, half of tcp_ack and chunks of
  159.  *        tcp_data/tcp_read as well as the window shrink crud.
  160.  *        Separate out duplicated code - tcp_alloc_skb, tcp_build_ack
  161.  *        tcp_queue_skb seem obvious routines to extract.
  162.  *    
  163.  *        This program is free software; you can redistribute it and/or
  164.  *        modify it under the terms of the GNU General Public License
  165.  *        as published by the Free Software Foundation; either version
  166.  *        2 of the License, or(at your option) any later version.
  167.  *
  168.  * Description of States:
  169.  *
  170.  *    TCP_SYN_SENT        sent a connection request, waiting for ack
  171.  *
  172.  *    TCP_SYN_RECV        received a connection request, sent ack,
  173.  *                waiting for final ack in three-way handshake.
  174.  *
  175.  *    TCP_ESTABLISHED        connection established
  176.  *
  177.  *    TCP_FIN_WAIT1        our side has shutdown, waiting to complete
  178.  *                transmission of remaining buffered data
  179.  *
  180.  *    TCP_FIN_WAIT2        all buffered data sent, waiting for remote
  181.  *                to shutdown
  182.  *
  183.  *    TCP_CLOSING        both sides have shutdown but we still have
  184.  *                data we have to finish sending
  185.  *
  186.  *    TCP_TIME_WAIT        timeout to catch resent junk before entering
  187.  *                closed, can only be entered from FIN_WAIT2
  188.  *                or CLOSING.  Required because the other end
  189.  *                may not have gotten our last ACK causing it
  190.  *                to retransmit the data packet (which we ignore)
  191.  *
  192.  *    TCP_CLOSE_WAIT        remote side has shutdown and is waiting for
  193.  *                us to finish writing our data and to shutdown
  194.  *                (we have to close() to move on to LAST_ACK)
  195.  *
  196.  *    TCP_LAST_ACK        out side has shutdown after remote has
  197.  *                shutdown.  There may still be data in our
  198.  *                buffer that we have to finish sending
  199.  *        
  200.  *    TCP_CLOSE        socket is finished
  201.  */
  202.  
  203. #include <linux/types.h>
  204. #include <linux/sched.h>
  205. #include <linux/mm.h>
  206. #include <linux/time.h>
  207. #include <linux/string.h>
  208. #include <linux/config.h>
  209. #include <linux/socket.h>
  210. #include <linux/sockios.h>
  211. #include <linux/termios.h>
  212. #include <linux/in.h>
  213. #include <linux/fcntl.h>
  214. #include <linux/inet.h>
  215. #include <linux/netdevice.h>
  216. #include "snmp.h"
  217. #include "ip.h"
  218. #include "protocol.h"
  219. #include "icmp.h"
  220. #include "tcp.h"
  221. #include "arp.h"
  222. #include <linux/skbuff.h>
  223. #include "sock.h"
  224. #include "route.h"
  225. #include <linux/errno.h>
  226. #include <linux/timer.h>
  227. #include <asm/system.h>
  228. #include <asm/segment.h>
  229. #include <linux/mm.h>
  230.  
  231. /*
  232.  *    The MSL timer is the 'normal' timer.
  233.  */
  234.  
  235. #define reset_msl_timer(x,y,z)    reset_timer(x,y,z)
  236.  
  237. #define SEQ_TICK 3
  238. unsigned long seq_offset;
  239. struct tcp_mib    tcp_statistics;
  240.  
  241. static void tcp_close(struct sock *sk, int timeout);
  242.  
  243.  
  244. /*
  245.  *    The less said about this the better, but it works and will do for 1.2 
  246.  */
  247.  
  248. static struct wait_queue *master_select_wakeup;
  249.  
  250. static __inline__ int min(unsigned int a, unsigned int b)
  251. {
  252.     if (a < b) 
  253.         return(a);
  254.     return(b);
  255. }
  256.  
  257. #undef STATE_TRACE
  258.  
  259. #ifdef STATE_TRACE
  260. static char *statename[]={
  261.     "Unused","Established","Syn Sent","Syn Recv",
  262.     "Fin Wait 1","Fin Wait 2","Time Wait", "Close",
  263.     "Close Wait","Last ACK","Listen","Closing"
  264. };
  265. #endif
  266.  
  267. static __inline__ void tcp_set_state(struct sock *sk, int state)
  268. {
  269.     if(sk->state==TCP_ESTABLISHED)
  270.         tcp_statistics.TcpCurrEstab--;
  271. #ifdef STATE_TRACE
  272.     if(sk->debug)
  273.         printk("TCP sk=%p, State %s -> %s\n",sk, statename[sk->state],statename[state]);
  274. #endif    
  275.     /* This is a hack but it doesn't occur often and it's going to
  276.        be a real        to fix nicely */
  277.        
  278.     if(state==TCP_ESTABLISHED && sk->state==TCP_SYN_RECV)
  279.     {
  280.         wake_up_interruptible(&master_select_wakeup);
  281.     }
  282.     sk->state=state;
  283.     if(state==TCP_ESTABLISHED)
  284.         tcp_statistics.TcpCurrEstab++;
  285. }
  286.  
  287. /*
  288.  *    This routine picks a TCP windows for a socket based on
  289.  *    the following constraints
  290.  *  
  291.  *    1. The window can never be shrunk once it is offered (RFC 793)
  292.  *    2. We limit memory per socket
  293.  *   
  294.  *    For now we use NET2E3's heuristic of offering half the memory
  295.  *    we have handy. All is not as bad as this seems however because
  296.  *    of two things. Firstly we will bin packets even within the window
  297.  *    in order to get the data we are waiting for into the memory limit.
  298.  *    Secondly we bin common duplicate forms at receive time
  299.  *      Better heuristics welcome
  300.  */
  301.    
  302. int tcp_select_window(struct sock *sk)
  303. {
  304.     int new_window = sk->prot->rspace(sk);
  305.     
  306.     if(sk->window_clamp)
  307.         new_window=min(sk->window_clamp,new_window);
  308.     /*
  309.      *     Two things are going on here.  First, we don't ever offer a
  310.      *     window less than min(sk->mss, MAX_WINDOW/2).  This is the
  311.      *     receiver side of SWS as specified in RFC1122.
  312.      *     Second, we always give them at least the window they
  313.      *     had before, in order to avoid retracting window.  This
  314.      *     is technically allowed, but RFC1122 advises against it and
  315.      *     in practice it causes trouble.
  316.      *
  317.      *     Fixme: This doesn't correctly handle the case where
  318.      *    new_window > sk->window but not by enough to allow for the
  319.      *    shift in sequence space. 
  320.      */
  321.     if (new_window < min(sk->mss, MAX_WINDOW/2) || new_window < sk->window)
  322.         return(sk->window);
  323.     return(new_window);
  324. }
  325.  
  326. /*
  327.  *    Find someone to 'accept'. Must be called with
  328.  *    sk->inuse=1 or cli()
  329.  */ 
  330.  
  331. static struct sk_buff *tcp_find_established(struct sock *s)
  332. {
  333.     struct sk_buff *p=skb_peek(&s->receive_queue);
  334.     if(p==NULL)
  335.         return NULL;
  336.     do
  337.     {
  338.         if(p->sk->state == TCP_ESTABLISHED || p->sk->state >= TCP_FIN_WAIT1)
  339.             return p;
  340.         p=p->next;
  341.     }
  342.     while(p!=(struct sk_buff *)&s->receive_queue);
  343.     return NULL;
  344. }
  345.  
  346. /*
  347.  *    Remove a completed connection and return it. This is used by
  348.  *    tcp_accept() to get connections from the queue.
  349.  */
  350.  
  351. static struct sk_buff *tcp_dequeue_established(struct sock *s)
  352. {
  353.     struct sk_buff *skb;
  354.     unsigned long flags;
  355.     save_flags(flags);
  356.     cli(); 
  357.     skb=tcp_find_established(s);
  358.     if(skb!=NULL)
  359.         skb_unlink(skb);    /* Take it off the queue */
  360.     restore_flags(flags);
  361.     return skb;
  362. }
  363.  
  364. /* 
  365.  *    This routine closes sockets which have been at least partially
  366.  *    opened, but not yet accepted. Currently it is only called by
  367.  *    tcp_close, and timeout mirrors the value there. 
  368.  */
  369.  
  370. static void tcp_close_pending (struct sock *sk) 
  371. {
  372.     struct sk_buff *skb;
  373.  
  374.     while ((skb = skb_dequeue(&sk->receive_queue)) != NULL) 
  375.     {
  376.         skb->sk->dead=1;
  377.         tcp_close(skb->sk, 0);
  378.         kfree_skb(skb, FREE_READ);
  379.     }
  380.     return;
  381. }
  382.  
  383. /*
  384.  *    Enter the time wait state. 
  385.  */
  386.  
  387. static void tcp_time_wait(struct sock *sk)
  388. {
  389.     tcp_set_state(sk,TCP_TIME_WAIT);
  390.     sk->shutdown = SHUTDOWN_MASK;
  391.     if (!sk->dead)
  392.         sk->state_change(sk);
  393.     reset_msl_timer(sk, TIME_CLOSE, TCP_TIMEWAIT_LEN);
  394. }
  395.  
  396. /*
  397.  *    A socket has timed out on its send queue and wants to do a
  398.  *    little retransmitting. Currently this means TCP.
  399.  */
  400.  
  401. void tcp_do_retransmit(struct sock *sk, int all)
  402. {
  403.     struct sk_buff * skb;
  404.     struct proto *prot;
  405.     struct device *dev;
  406.     int ct=0;
  407.  
  408.     prot = sk->prot;
  409.     skb = sk->send_head;
  410.  
  411.     while (skb != NULL)
  412.     {
  413.         struct tcphdr *th;
  414.         struct iphdr *iph;
  415.         int size;
  416.  
  417.         dev = skb->dev;
  418.         IS_SKB(skb);
  419.         skb->when = jiffies;
  420.  
  421.         /*
  422.          * In general it's OK just to use the old packet.  However we
  423.          * need to use the current ack and window fields.  Urg and
  424.          * urg_ptr could possibly stand to be updated as well, but we
  425.          * don't keep the necessary data.  That shouldn't be a problem,
  426.          * if the other end is doing the right thing.  Since we're
  427.          * changing the packet, we have to issue a new IP identifier.
  428.          */
  429.  
  430.         iph = (struct iphdr *)(skb->data + dev->hard_header_len);
  431.         th = (struct tcphdr *)(((char *)iph) + (iph->ihl << 2));
  432.         size = skb->len - (((unsigned char *) th) - skb->data);
  433.         
  434.         /*
  435.          *    Note: We ought to check for window limits here but
  436.          *    currently this is done (less efficiently) elsewhere.
  437.          *    We do need to check for a route change but can't handle
  438.          *    that until we have the new 1.3.x buffers in.
  439.          *
  440.          */
  441.  
  442.         iph->id = htons(ip_id_count++);
  443.         ip_send_check(iph);
  444.  
  445.         /*
  446.          *    This is not the right way to handle this. We have to
  447.          *    issue an up to date window and ack report with this 
  448.          *    retransmit to keep the odd buggy tcp that relies on 
  449.          *    the fact BSD does this happy. 
  450.          *    We don't however need to recalculate the entire 
  451.          *    checksum, so someone wanting a small problem to play
  452.          *    with might like to implement RFC1141/RFC1624 and speed
  453.          *    this up by avoiding a full checksum.
  454.          */
  455.          
  456.         th->ack_seq = ntohl(sk->acked_seq);
  457.         th->window = ntohs(tcp_select_window(sk));
  458.         tcp_send_check(th, sk->saddr, sk->daddr, size, sk);
  459.         
  460.         /*
  461.          *    If the interface is (still) up and running, kick it.
  462.          */
  463.  
  464.         if (dev->flags & IFF_UP)
  465.         {
  466.             /*
  467.              *    If the packet is still being sent by the device/protocol
  468.              *    below then don't retransmit. This is both needed, and good -
  469.              *    especially with connected mode AX.25 where it stops resends
  470.              *    occurring of an as yet unsent anyway frame!
  471.              *    We still add up the counts as the round trip time wants
  472.              *    adjusting.
  473.              */
  474.             if (sk && !skb_device_locked(skb))
  475.             {
  476.                 /* Remove it from any existing driver queue first! */
  477.                 skb_unlink(skb);
  478.                 /* Now queue it */
  479.                 ip_statistics.IpOutRequests++;
  480.                 dev_queue_xmit(skb, dev, sk->priority);
  481.             }
  482.         }
  483.  
  484.         /*
  485.          *    Count retransmissions
  486.          */
  487.          
  488.         ct++;
  489.         sk->prot->retransmits ++;
  490.  
  491.         /*
  492.          *    Only one retransmit requested.
  493.          */
  494.     
  495.         if (!all)
  496.             break;
  497.  
  498.         /*
  499.          *    This should cut it off before we send too many packets.
  500.          */
  501.  
  502.         if (ct >= sk->cong_window)
  503.             break;
  504.         skb = skb->link3;
  505.     }
  506. }
  507.  
  508. /*
  509.  *    Reset the retransmission timer
  510.  */
  511.  
  512. static void reset_xmit_timer(struct sock *sk, int why, unsigned long when)
  513. {
  514.     del_timer(&sk->retransmit_timer);
  515.     sk->ip_xmit_timeout = why;
  516.     if((int)when < 0)
  517.     {
  518.         when=3;
  519.         printk("Error: Negative timer in xmit_timer\n");
  520.     }
  521.     sk->retransmit_timer.expires=when;
  522.     add_timer(&sk->retransmit_timer);
  523. }
  524.  
  525. /*
  526.  *     This is the normal code called for timeouts.  It does the retransmission
  527.  *     and then does backoff.  tcp_do_retransmit is separated out because
  528.  *     tcp_ack needs to send stuff from the retransmit queue without
  529.  *     initiating a backoff.
  530.  */
  531.  
  532.  
  533. void tcp_retransmit_time(struct sock *sk, int all)
  534. {
  535.     tcp_do_retransmit(sk, all);
  536.  
  537.     /*
  538.      * Increase the timeout each time we retransmit.  Note that
  539.      * we do not increase the rtt estimate.  rto is initialized
  540.      * from rtt, but increases here.  Jacobson (SIGCOMM 88) suggests
  541.      * that doubling rto each time is the least we can get away with.
  542.      * In KA9Q, Karn uses this for the first few times, and then
  543.      * goes to quadratic.  netBSD doubles, but only goes up to *64,
  544.      * and clamps at 1 to 64 sec afterwards.  Note that 120 sec is
  545.      * defined in the protocol as the maximum possible RTT.  I guess
  546.      * we'll have to use something other than TCP to talk to the
  547.      * University of Mars.
  548.      *
  549.      * PAWS allows us longer timeouts and large windows, so once
  550.      * implemented ftp to mars will work nicely. We will have to fix
  551.      * the 120 second clamps though!
  552.      */
  553.  
  554.     sk->retransmits++;
  555.     sk->backoff++;
  556.     sk->rto = min(sk->rto << 1, 120*HZ);
  557.     reset_xmit_timer(sk, TIME_WRITE, sk->rto);
  558. }
  559.  
  560.  
  561. /*
  562.  *    A timer event has trigger a tcp retransmit timeout. The
  563.  *    socket xmit queue is ready and set up to send. Because
  564.  *    the ack receive code keeps the queue straight we do
  565.  *    nothing clever here.
  566.  */
  567.  
  568. static void tcp_retransmit(struct sock *sk, int all)
  569. {
  570.     if (all) 
  571.     {
  572.         tcp_retransmit_time(sk, all);
  573.         return;
  574.     }
  575.  
  576.     sk->ssthresh = sk->cong_window >> 1; /* remember window where we lost */
  577.     /* sk->ssthresh in theory can be zero.  I guess that's OK */
  578.     sk->cong_count = 0;
  579.  
  580.     sk->cong_window = 1;
  581.  
  582.     /* Do the actual retransmit. */
  583.     tcp_retransmit_time(sk, all);
  584. }
  585.  
  586. /*
  587.  *    A write timeout has occurred. Process the after effects.
  588.  */
  589.  
  590. static int tcp_write_timeout(struct sock *sk)
  591. {
  592.     /*
  593.      *    Look for a 'soft' timeout.
  594.      */
  595.     if ((sk->state == TCP_ESTABLISHED && sk->retransmits && !(sk->retransmits & 7))
  596.         || (sk->state != TCP_ESTABLISHED && sk->retransmits > TCP_RETR1)) 
  597.     {
  598.         /*
  599.          *    Attempt to recover if arp has changed (unlikely!) or
  600.          *    a route has shifted (not supported prior to 1.3).
  601.          */
  602.         arp_destroy (sk->daddr, 0);
  603.         ip_route_check (sk->daddr);
  604.     }
  605.     /*
  606.      *    Has it gone just too far ?
  607.      */
  608.     if (sk->retransmits > TCP_RETR2) 
  609.     {
  610.         sk->err = ETIMEDOUT;
  611.         sk->error_report(sk);
  612.         del_timer(&sk->retransmit_timer);
  613.         /*
  614.          *    Time wait the socket 
  615.          */
  616.         if (sk->state == TCP_FIN_WAIT1 || sk->state == TCP_FIN_WAIT2 || sk->state == TCP_CLOSING ) 
  617.         {
  618.             tcp_set_state(sk,TCP_TIME_WAIT);
  619.             reset_msl_timer (sk, TIME_CLOSE, TCP_TIMEWAIT_LEN);
  620.         }
  621.         else
  622.         {
  623.             /*
  624.              *    Clean up time.
  625.              */
  626.             tcp_set_state(sk, TCP_CLOSE);
  627.             return 0;
  628.         }
  629.     }
  630.     return 1;
  631. }
  632.  
  633. /*
  634.  *    The TCP retransmit timer. This lacks a few small details.
  635.  *
  636.  *    1.     An initial rtt timeout on the probe0 should cause what we can
  637.  *        of the first write queue buffer to be split and sent.
  638.  *    2.    On a 'major timeout' as defined by RFC1122 we shouldn't report
  639.  *        ETIMEDOUT if we know an additional 'soft' error caused this.
  640.  *        tcp_err should save a 'soft error' for us.
  641.  */
  642.  
  643. static void retransmit_timer(unsigned long data)
  644. {
  645.     struct sock *sk = (struct sock*)data;
  646.     int why = sk->ip_xmit_timeout;
  647.  
  648.     /* 
  649.      * only process if socket is not in use
  650.      */
  651.  
  652.     cli();
  653.     if (sk->inuse || in_bh) 
  654.     {
  655.         /* Try again in 1 second */
  656.         sk->retransmit_timer.expires = HZ;
  657.         add_timer(&sk->retransmit_timer);
  658.         sti();
  659.         return;
  660.     }
  661.  
  662.     sk->inuse = 1;
  663.     sti();
  664.  
  665.     /* Always see if we need to send an ack. */
  666.  
  667.     if (sk->ack_backlog && !sk->zapped) 
  668.     {
  669.         sk->prot->read_wakeup (sk);
  670.         if (! sk->dead)
  671.             sk->data_ready(sk,0);
  672.     }
  673.  
  674.     /* Now we need to figure out why the socket was on the timer. */
  675.  
  676.     switch (why) 
  677.     {
  678.         /* Window probing */
  679.         case TIME_PROBE0:
  680.             tcp_send_probe0(sk);
  681.             tcp_write_timeout(sk);
  682.             break;
  683.         /* Retransmitting */
  684.         case TIME_WRITE:
  685.             /* It could be we got here because we needed to send an ack.
  686.              * So we need to check for that.
  687.              */
  688.         {
  689.             struct sk_buff *skb;
  690.             unsigned long flags;
  691.  
  692.             save_flags(flags);
  693.             cli();
  694.             skb = sk->send_head;
  695.             if (!skb) 
  696.             {
  697.                 restore_flags(flags);
  698.             } 
  699.             else 
  700.             {
  701.                 /*
  702.                  *    Kicked by a delayed ack. Reset timer
  703.                  *    correctly now
  704.                  */
  705.                 if (jiffies < skb->when + sk->rto) 
  706.                 {
  707.                     reset_xmit_timer (sk, TIME_WRITE, skb->when + sk->rto - jiffies);
  708.                     restore_flags(flags);
  709.                     break;
  710.                 }
  711.                 restore_flags(flags);
  712.                 /*
  713.                  *    Retransmission
  714.                  */
  715.                 sk->prot->retransmit (sk, 0);
  716.                 tcp_write_timeout(sk);
  717.             }
  718.             break;
  719.         }
  720.         /* Sending Keepalives */
  721.         case TIME_KEEPOPEN:
  722.             /* 
  723.              * this reset_timer() call is a hack, this is not
  724.              * how KEEPOPEN is supposed to work.
  725.              */
  726.             reset_xmit_timer (sk, TIME_KEEPOPEN, TCP_TIMEOUT_LEN);
  727.  
  728.             /* Send something to keep the connection open. */
  729.             if (sk->prot->write_wakeup)
  730.                   sk->prot->write_wakeup (sk);
  731.             sk->retransmits++;
  732.             tcp_write_timeout(sk);
  733.             break;
  734.         default:
  735.             printk ("rexmit_timer: timer expired - reason unknown\n");
  736.             break;
  737.     }
  738.     release_sock(sk);
  739. }
  740.  
  741. /*
  742.  * This routine is called by the ICMP module when it gets some
  743.  * sort of error condition.  If err < 0 then the socket should
  744.  * be closed and the error returned to the user.  If err > 0
  745.  * it's just the icmp type << 8 | icmp code.  After adjustment
  746.  * header points to the first 8 bytes of the tcp header.  We need
  747.  * to find the appropriate port.
  748.  */
  749.  
  750. void tcp_err(int err, unsigned char *header, unsigned long daddr,
  751.     unsigned long saddr, struct inet_protocol *protocol)
  752. {
  753.     struct tcphdr *th;
  754.     struct sock *sk;
  755.     struct iphdr *iph=(struct iphdr *)header;
  756.   
  757.     header+=4*iph->ihl;
  758.    
  759.  
  760.     th =(struct tcphdr *)header;
  761.     sk = get_sock(&tcp_prot, th->source, daddr, th->dest, saddr);
  762.  
  763.     if (sk == NULL) 
  764.         return;
  765.   
  766.     if(err<0)
  767.     {
  768.           sk->err = -err;
  769.           sk->error_report(sk);
  770.           return;
  771.     }
  772.  
  773.     if ((err & 0xff00) == (ICMP_SOURCE_QUENCH << 8)) 
  774.     {
  775.         /*
  776.          * FIXME:
  777.          * For now we will just trigger a linear backoff.
  778.          * The slow start code should cause a real backoff here.
  779.          */
  780.         if (sk->cong_window > 4)
  781.             sk->cong_window--;
  782.         return;
  783.     }
  784.  
  785. /*    sk->err = icmp_err_convert[err & 0xff].errno;  -- moved as TCP should hide non fatals internally (and does) */
  786.  
  787.     /*
  788.      * If we've already connected we will keep trying
  789.      * until we time out, or the user gives up.
  790.      */
  791.  
  792.     if (icmp_err_convert[err & 0xff].fatal || sk->state == TCP_SYN_SENT) 
  793.     {
  794.         if (sk->state == TCP_SYN_SENT) 
  795.         {
  796.             tcp_statistics.TcpAttemptFails++;
  797.             tcp_set_state(sk,TCP_CLOSE);
  798.             sk->error_report(sk);        /* Wake people up to see the error (see connect in sock.c) */
  799.         }
  800.         sk->err = icmp_err_convert[err & 0xff].errno;        
  801.     }
  802.     return;
  803. }
  804.  
  805.  
  806. /*
  807.  *    Walk down the receive queue counting readable data until we hit the end or we find a gap
  808.  *    in the received data queue (ie a frame missing that needs sending to us). Not
  809.  *    sorting using two queues as data arrives makes life so much harder.
  810.  */
  811.  
  812. static int tcp_readable(struct sock *sk)
  813. {
  814.     unsigned long counted;
  815.     unsigned long amount;
  816.     struct sk_buff *skb;
  817.     int sum;
  818.     unsigned long flags;
  819.  
  820.     if(sk && sk->debug)
  821.           printk("tcp_readable: %p - ",sk);
  822.  
  823.     save_flags(flags);
  824.     cli();
  825.     if (sk == NULL || (skb = skb_peek(&sk->receive_queue)) == NULL)
  826.     {
  827.         restore_flags(flags);
  828.           if(sk && sk->debug) 
  829.               printk("empty\n");
  830.           return(0);
  831.     }
  832.   
  833.     counted = sk->copied_seq;    /* Where we are at the moment */
  834.     amount = 0;
  835.   
  836.     /* 
  837.      *    Do until a push or until we are out of data. 
  838.      */
  839.      
  840.     do 
  841.     {
  842.         if (before(counted, skb->h.th->seq))     /* Found a hole so stops here */
  843.             break;
  844.         sum = skb->len -(counted - skb->h.th->seq);    /* Length - header but start from where we are up to (avoid overlaps) */
  845.         if (skb->h.th->syn)
  846.             sum++;
  847.         if (sum > 0) 
  848.         {                    /* Add it up, move on */
  849.             amount += sum;
  850.             if (skb->h.th->syn) 
  851.                 amount--;
  852.             counted += sum;
  853.         }
  854.         /*
  855.          * Don't count urg data ... but do it in the right place!
  856.          * Consider: "old_data (ptr is here) URG PUSH data"
  857.          * The old code would stop at the first push because
  858.          * it counted the urg (amount==1) and then does amount--
  859.          * *after* the loop.  This means tcp_readable() always
  860.          * returned zero if any URG PUSH was in the queue, even
  861.          * though there was normal data available. If we subtract
  862.          * the urg data right here, we even get it to work for more
  863.          * than one URG PUSH skb without normal data.
  864.          * This means that select() finally works now with urg data
  865.          * in the queue.  Note that rlogin was never affected
  866.          * because it doesn't use select(); it uses two processes
  867.          * and a blocking read().  And the queue scan in tcp_read()
  868.          * was correct.  Mike <pall@rz.uni-karlsruhe.de>
  869.          */
  870.         if (skb->h.th->urg)
  871.             amount--;    /* don't count urg data */
  872.         if (amount && skb->h.th->psh) break;
  873.         skb = skb->next;
  874.     }
  875.     while(skb != (struct sk_buff *)&sk->receive_queue);
  876.  
  877.     restore_flags(flags);
  878.     if(sk->debug)
  879.           printk("got %lu bytes.\n",amount);
  880.     return(amount);
  881. }
  882.  
  883. /*
  884.  * LISTEN is a special case for select..
  885.  */
  886. static int tcp_listen_select(struct sock *sk, int sel_type, select_table *wait)
  887. {
  888.     if (sel_type == SEL_IN) {
  889.         int retval;
  890.  
  891.         sk->inuse = 1;
  892.         retval = (tcp_find_established(sk) != NULL);
  893.         release_sock(sk);
  894.         if (!retval)
  895.             select_wait(&master_select_wakeup,wait);
  896.         return retval;
  897.     }
  898.     return 0;
  899. }
  900.  
  901.  
  902. /*
  903.  *    Wait for a TCP event.
  904.  *
  905.  *    Note that we don't need to set "sk->inuse", as the upper select layers
  906.  *    take care of normal races (between the test and the event) and we don't
  907.  *    go look at any of the socket buffers directly.
  908.  */
  909. static int tcp_select(struct sock *sk, int sel_type, select_table *wait)
  910. {
  911.     if (sk->state == TCP_LISTEN)
  912.         return tcp_listen_select(sk, sel_type, wait);
  913.  
  914.     switch(sel_type) {
  915.     case SEL_IN:
  916.         if (sk->err)
  917.             return 1;
  918.         if (sk->state == TCP_SYN_SENT || sk->state == TCP_SYN_RECV)
  919.             break;
  920.  
  921.         if (sk->shutdown & RCV_SHUTDOWN)
  922.             return 1;
  923.             
  924.         if (sk->acked_seq == sk->copied_seq)
  925.             break;
  926.  
  927.         if (sk->urg_seq != sk->copied_seq ||
  928.             sk->acked_seq != sk->copied_seq+1 ||
  929.             sk->urginline || !sk->urg_data)
  930.             return 1;
  931.         break;
  932.  
  933.     case SEL_OUT:
  934.         if (sk->shutdown & SEND_SHUTDOWN) 
  935.             return 0;
  936.         if (sk->state == TCP_SYN_SENT || sk->state == TCP_SYN_RECV)
  937.             break;
  938.         /*
  939.          * This is now right thanks to a small fix
  940.          * by Matt Dillon.
  941.          */
  942.  
  943.         if (sk->prot->wspace(sk) < sk->mtu+128+sk->prot->max_header)
  944.             break;
  945.         return 1;
  946.  
  947.     case SEL_EX:
  948.         if (sk->err || sk->urg_data)
  949.             return 1;
  950.         break;
  951.     }
  952.     select_wait(sk->sleep, wait);
  953.     return 0;
  954. }
  955.  
  956. int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  957. {
  958.     int err;
  959.     switch(cmd) 
  960.     {
  961.  
  962.         case TIOCINQ:
  963. #ifdef FIXME    /* FIXME: */
  964.         case FIONREAD:
  965. #endif
  966.         {
  967.             unsigned long amount;
  968.  
  969.             if (sk->state == TCP_LISTEN) 
  970.                 return(-EINVAL);
  971.  
  972.             sk->inuse = 1;
  973.             amount = tcp_readable(sk);
  974.             release_sock(sk);
  975.             err=verify_area(VERIFY_WRITE,(void *)arg,
  976.                            sizeof(unsigned long));
  977.             if(err)
  978.                 return err;
  979.             put_fs_long(amount,(unsigned long *)arg);
  980.             return(0);
  981.         }
  982.         case SIOCATMARK:
  983.         {
  984.             int answ = sk->urg_data && sk->urg_seq == sk->copied_seq;
  985.  
  986.             err = verify_area(VERIFY_WRITE,(void *) arg,
  987.                           sizeof(unsigned long));
  988.             if (err)
  989.                 return err;
  990.             put_fs_long(answ,(int *) arg);
  991.             return(0);
  992.         }
  993.         case TIOCOUTQ:
  994.         {
  995.             unsigned long amount;
  996.  
  997.             if (sk->state == TCP_LISTEN) return(-EINVAL);
  998.             amount = sk->prot->wspace(sk);
  999.             err=verify_area(VERIFY_WRITE,(void *)arg,
  1000.                            sizeof(unsigned long));
  1001.             if(err)
  1002.                 return err;
  1003.             put_fs_long(amount,(unsigned long *)arg);
  1004.             return(0);
  1005.         }
  1006.         default:
  1007.             return(-EINVAL);
  1008.     }
  1009. }
  1010.  
  1011.  
  1012. /*
  1013.  *    This routine computes a TCP checksum. 
  1014.  */
  1015.  
  1016. unsigned short tcp_check(struct tcphdr *th, int len,
  1017.       unsigned long saddr, unsigned long daddr)
  1018. {     
  1019.     unsigned long sum;
  1020.    
  1021.     if (saddr == 0) saddr = ip_my_addr();
  1022.  
  1023. /*
  1024.  * stupid, gcc complains when I use just one __asm__ block,
  1025.  * something about too many reloads, but this is just two
  1026.  * instructions longer than what I want
  1027.  */
  1028.     __asm__("
  1029.         addl %%ecx, %%ebx
  1030.         adcl %%edx, %%ebx
  1031.         adcl $0, %%ebx
  1032.         "
  1033.     : "=b"(sum)
  1034.     : "0"(daddr), "c"(saddr), "d"((ntohs(len) << 16) + IPPROTO_TCP*256)
  1035.     : "bx", "cx", "dx" );
  1036.     __asm__("
  1037.         movl %%ecx, %%edx
  1038.         cld
  1039.         cmpl $32, %%ecx
  1040.         jb 2f
  1041.         shrl $5, %%ecx
  1042.         clc
  1043. 1:        lodsl
  1044.         adcl %%eax, %%ebx
  1045.         lodsl
  1046.         adcl %%eax, %%ebx
  1047.         lodsl
  1048.         adcl %%eax, %%ebx
  1049.         lodsl
  1050.         adcl %%eax, %%ebx
  1051.         lodsl
  1052.         adcl %%eax, %%ebx
  1053.         lodsl
  1054.         adcl %%eax, %%ebx
  1055.         lodsl
  1056.         adcl %%eax, %%ebx
  1057.         lodsl
  1058.         adcl %%eax, %%ebx
  1059.         loop 1b
  1060.         adcl $0, %%ebx
  1061.         movl %%edx, %%ecx
  1062. 2:        andl $28, %%ecx
  1063.         je 4f
  1064.         shrl $2, %%ecx
  1065.         clc
  1066. 3:        lodsl
  1067.         adcl %%eax, %%ebx
  1068.         loop 3b
  1069.         adcl $0, %%ebx
  1070. 4:        movl $0, %%eax
  1071.         testw $2, %%dx
  1072.         je 5f
  1073.         lodsw
  1074.         addl %%eax, %%ebx
  1075.         adcl $0, %%ebx
  1076.         movw $0, %%ax
  1077. 5:        test $1, %%edx
  1078.         je 6f
  1079.         lodsb
  1080.         addl %%eax, %%ebx
  1081.         adcl $0, %%ebx
  1082. 6:        movl %%ebx, %%eax
  1083.         shrl $16, %%eax
  1084.         addw %%ax, %%bx
  1085.         adcw $0, %%bx
  1086.         "
  1087.     : "=b"(sum)
  1088.     : "0"(sum), "c"(len), "S"(th)
  1089.     : "ax", "bx", "cx", "dx", "si" );
  1090.  
  1091.       /* We only want the bottom 16 bits, but we never cleared the top 16. */
  1092.   
  1093.       return((~sum) & 0xffff);
  1094. }
  1095.  
  1096.  
  1097.  
  1098. void tcp_send_check(struct tcphdr *th, unsigned long saddr, 
  1099.         unsigned long daddr, int len, struct sock *sk)
  1100. {
  1101.     th->check = 0;
  1102.     th->check = tcp_check(th, len, saddr, daddr);
  1103.     return;
  1104. }
  1105.  
  1106. /*
  1107.  *    This is the main buffer sending routine. We queue the buffer
  1108.  *    having checked it is sane seeming.
  1109.  */
  1110.  
  1111. static void tcp_send_skb(struct sock *sk, struct sk_buff *skb)
  1112. {
  1113.     int size;
  1114.     struct tcphdr * th = skb->h.th;
  1115.  
  1116.     /*
  1117.      *    length of packet (not counting length of pre-tcp headers) 
  1118.      */
  1119.      
  1120.     size = skb->len - ((unsigned char *) th - skb->data);
  1121.  
  1122.     /*
  1123.      *    Sanity check it.. 
  1124.      */
  1125.      
  1126.     if (size < sizeof(struct tcphdr) || size > skb->len) 
  1127.     {
  1128.         printk("tcp_send_skb: bad skb (skb = %p, data = %p, th = %p, len = %lu)\n",
  1129.             skb, skb->data, th, skb->len);
  1130.         kfree_skb(skb, FREE_WRITE);
  1131.         return;
  1132.     }
  1133.  
  1134.     /*
  1135.      *    If we have queued a header size packet.. (these crash a few
  1136.      *    tcp stacks if ack is not set)
  1137.      */
  1138.      
  1139.     if (size == sizeof(struct tcphdr)) 
  1140.     {
  1141.         /* If it's got a syn or fin it's notionally included in the size..*/
  1142.         if(!th->syn && !th->fin) 
  1143.         {
  1144.             printk("tcp_send_skb: attempt to queue a bogon.\n");
  1145.             kfree_skb(skb,FREE_WRITE);
  1146.             return;
  1147.         }
  1148.     }
  1149.  
  1150.     /*
  1151.      *    Actual processing.
  1152.      */
  1153.      
  1154.     tcp_statistics.TcpOutSegs++;  
  1155.     skb->h.seq = ntohl(th->seq) + size - 4*th->doff;
  1156.     
  1157.     /*
  1158.      *    We must queue if
  1159.      *
  1160.      *    a) The right edge of this frame exceeds the window
  1161.      *    b) We are retransmitting (Nagle's rule)
  1162.      *    c) We have too many packets 'in flight'
  1163.      */
  1164.      
  1165.     if (after(skb->h.seq, sk->window_seq) ||
  1166.         (sk->retransmits && sk->ip_xmit_timeout == TIME_WRITE) ||
  1167.          sk->packets_out >= sk->cong_window) 
  1168.     {
  1169.         /* checksum will be supplied by tcp_write_xmit.  So
  1170.          * we shouldn't need to set it at all.  I'm being paranoid */
  1171.         th->check = 0;
  1172.         if (skb->next != NULL) 
  1173.         {
  1174.             printk("tcp_send_partial: next != NULL\n");
  1175.             skb_unlink(skb);
  1176.         }
  1177.         skb_queue_tail(&sk->write_queue, skb);
  1178.         
  1179.         /*
  1180.          *    If we don't fit we have to start the zero window
  1181.          *    probes. This is broken - we really need to do a partial
  1182.          *    send _first_ (This is what causes the Cisco and PC/TCP
  1183.          *    grief).
  1184.          */
  1185.          
  1186.         if (before(sk->window_seq, sk->write_queue.next->h.seq) &&
  1187.             sk->send_head == NULL && sk->ack_backlog == 0)
  1188.             reset_xmit_timer(sk, TIME_PROBE0, sk->rto);
  1189.     } 
  1190.     else 
  1191.     {
  1192.         /*
  1193.          *    This is going straight out
  1194.          */
  1195.          
  1196.         th->ack_seq = ntohl(sk->acked_seq);
  1197.         th->window = ntohs(tcp_select_window(sk));
  1198.  
  1199.         tcp_send_check(th, sk->saddr, sk->daddr, size, sk);
  1200.  
  1201.         sk->sent_seq = sk->write_seq;
  1202.         
  1203.         /*
  1204.          *    This is mad. The tcp retransmit queue is put together
  1205.          *    by the ip layer. This causes half the problems with
  1206.          *    unroutable FIN's and other things.
  1207.          */
  1208.          
  1209.         sk->prot->queue_xmit(sk, skb->dev, skb, 0);
  1210.         
  1211.         /*
  1212.          *    Set for next retransmit based on expected ACK time.
  1213.          *    FIXME: We set this every time which means our 
  1214.          *    retransmits are really about a window behind.
  1215.          */
  1216.  
  1217.         reset_xmit_timer(sk, TIME_WRITE, sk->rto);
  1218.     }
  1219. }
  1220.  
  1221. /*
  1222.  *    Locking problems lead us to a messy situation where we can have
  1223.  *    multiple partially complete buffers queued up. This is really bad
  1224.  *    as we don't want to be sending partial buffers. Fix this with
  1225.  *    a semaphore or similar to lock tcp_write per socket.
  1226.  *
  1227.  *    These routines are pretty self descriptive.
  1228.  */
  1229.  
  1230. struct sk_buff * tcp_dequeue_partial(struct sock * sk)
  1231. {
  1232.     struct sk_buff * skb;
  1233.     unsigned long flags;
  1234.  
  1235.     save_flags(flags);
  1236.     cli();
  1237.     skb = sk->partial;
  1238.     if (skb) {
  1239.         sk->partial = NULL;
  1240.         del_timer(&sk->partial_timer);
  1241.     }
  1242.     restore_flags(flags);
  1243.     return skb;
  1244. }
  1245.  
  1246. /*
  1247.  *    Empty the partial queue
  1248.  */
  1249.  
  1250. static void tcp_send_partial(struct sock *sk)
  1251. {
  1252.     struct sk_buff *skb;
  1253.  
  1254.     if (sk == NULL)
  1255.         return;
  1256.     while ((skb = tcp_dequeue_partial(sk)) != NULL)
  1257.         tcp_send_skb(sk, skb);
  1258. }
  1259.  
  1260. /*
  1261.  *    Queue a partial frame
  1262.  */
  1263.  
  1264. void tcp_enqueue_partial(struct sk_buff * skb, struct sock * sk)
  1265. {
  1266.     struct sk_buff * tmp;
  1267.     unsigned long flags;
  1268.  
  1269.     save_flags(flags);
  1270.     cli();
  1271.     tmp = sk->partial;
  1272.     if (tmp)
  1273.         del_timer(&sk->partial_timer);
  1274.     sk->partial = skb;
  1275.     init_timer(&sk->partial_timer);
  1276.     /*
  1277.      *    Wait up to 1 second for the buffer to fill.
  1278.      */
  1279.     sk->partial_timer.expires = HZ;
  1280.     sk->partial_timer.function = (void (*)(unsigned long)) tcp_send_partial;
  1281.     sk->partial_timer.data = (unsigned long) sk;
  1282.     add_timer(&sk->partial_timer);
  1283.     restore_flags(flags);
  1284.     if (tmp)
  1285.         tcp_send_skb(sk, tmp);
  1286. }
  1287.  
  1288.  
  1289. /*
  1290.  *    This routine sends an ack and also updates the window. 
  1291.  */
  1292.  
  1293. static void tcp_send_ack(unsigned long sequence, unsigned long ack,
  1294.          struct sock *sk,
  1295.          struct tcphdr *th, unsigned long daddr)
  1296. {
  1297.     struct sk_buff *buff;
  1298.     struct tcphdr *t1;
  1299.     struct device *dev = NULL;
  1300.     int tmp;
  1301.  
  1302.     if(sk->zapped)
  1303.         return;        /* We have been reset, we may not send again */
  1304.         
  1305.     /*
  1306.      * We need to grab some memory, and put together an ack,
  1307.      * and then put it into the queue to be sent.
  1308.      */
  1309.  
  1310.     buff = sk->prot->wmalloc(sk, MAX_ACK_SIZE, 1, GFP_ATOMIC);
  1311.     if (buff == NULL) 
  1312.     {
  1313.         /* 
  1314.          *    Force it to send an ack. We don't have to do this
  1315.          *    (ACK is unreliable) but it's much better use of 
  1316.          *    bandwidth on slow links to send a spare ack than
  1317.          *    resend packets. 
  1318.          */
  1319.          
  1320.         sk->ack_backlog++;
  1321.         if (sk->ip_xmit_timeout != TIME_WRITE && tcp_connected(sk->state)) 
  1322.         {
  1323.             reset_xmit_timer(sk, TIME_WRITE, HZ);
  1324.         }
  1325.         return;
  1326.     }
  1327.  
  1328.     /*
  1329.      *    Assemble a suitable TCP frame
  1330.      */
  1331.      
  1332.     buff->len = sizeof(struct tcphdr);
  1333.     buff->sk = sk;
  1334.     buff->localroute = sk->localroute;
  1335.     t1 =(struct tcphdr *) buff->data;
  1336.  
  1337.     /* 
  1338.      *    Put in the IP header and routing stuff. 
  1339.      */
  1340.      
  1341.     tmp = sk->prot->build_header(buff, sk->saddr, daddr, &dev,
  1342.                 IPPROTO_TCP, sk->opt, MAX_ACK_SIZE,sk->ip_tos,sk->ip_ttl);
  1343.     if (tmp < 0) 
  1344.     {
  1345.           buff->free = 1;
  1346.         sk->prot->wfree(sk, buff->mem_addr, buff->mem_len);
  1347.         return;
  1348.     }
  1349.     buff->len += tmp;
  1350.     t1 =(struct tcphdr *)((char *)t1 +tmp);
  1351.  
  1352.     memcpy(t1, th, sizeof(*t1));
  1353.  
  1354.     /*
  1355.      *    Swap the send and the receive. 
  1356.      */
  1357.      
  1358.     t1->dest = th->source;
  1359.     t1->source = th->dest;
  1360.     t1->seq = ntohl(sequence);
  1361.     t1->ack = 1;
  1362.     sk->window = tcp_select_window(sk);
  1363.     t1->window = ntohs(sk->window);
  1364.     t1->res1 = 0;
  1365.     t1->res2 = 0;
  1366.     t1->rst = 0;
  1367.     t1->urg = 0;
  1368.     t1->syn = 0;
  1369.     t1->psh = 0;
  1370.     t1->fin = 0;
  1371.     
  1372.     /*
  1373.      *    If we have nothing queued for transmit and the transmit timer
  1374.      *    is on we are just doing an ACK timeout and need to switch
  1375.      *    to a keepalive.
  1376.      */
  1377.      
  1378.     if (ack == sk->acked_seq) 
  1379.     {
  1380.         sk->ack_backlog = 0;
  1381.         sk->bytes_rcv = 0;
  1382.         sk->ack_timed = 0;
  1383.         if (sk->send_head == NULL && skb_peek(&sk->write_queue) == NULL
  1384.                   && sk->ip_xmit_timeout == TIME_WRITE) 
  1385.         {
  1386.             if(sk->keepopen) {
  1387.                 reset_xmit_timer(sk,TIME_KEEPOPEN,TCP_TIMEOUT_LEN);
  1388.             } else {
  1389.                 delete_timer(sk);
  1390.             }
  1391.         }
  1392.       }
  1393.       
  1394.       /*
  1395.        *    Fill in the packet and send it
  1396.        */
  1397.        
  1398.       t1->ack_seq = ntohl(ack);
  1399.       t1->doff = sizeof(*t1)/4;
  1400.       tcp_send_check(t1, sk->saddr, daddr, sizeof(*t1), sk);
  1401.       if (sk->debug)
  1402.            printk("\rtcp_ack: seq %lx ack %lx\n", sequence, ack);
  1403.       tcp_statistics.TcpOutSegs++;
  1404.       sk->prot->queue_xmit(sk, dev, buff, 1);
  1405. }
  1406.  
  1407.  
  1408. /* 
  1409.  *    This routine builds a generic TCP header. 
  1410.  */
  1411.  
  1412. extern __inline int tcp_build_header(struct tcphdr *th, struct sock *sk, int push)
  1413. {
  1414.  
  1415.     memcpy(th,(void *) &(sk->dummy_th), sizeof(*th));
  1416.     th->seq = htonl(sk->write_seq);
  1417.     th->psh =(push == 0) ? 1 : 0;
  1418.     th->doff = sizeof(*th)/4;
  1419.     th->ack = 1;
  1420.     th->fin = 0;
  1421.     sk->ack_backlog = 0;
  1422.     sk->bytes_rcv = 0;
  1423.     sk->ack_timed = 0;
  1424.     th->ack_seq = htonl(sk->acked_seq);
  1425.     sk->window = tcp_select_window(sk);
  1426.     th->window = htons(sk->window);
  1427.  
  1428.     return(sizeof(*th));
  1429. }
  1430.  
  1431. /*
  1432.  *    This routine copies from a user buffer into a socket,
  1433.  *    and starts the transmit system.
  1434.  */
  1435.  
  1436. static int tcp_write(struct sock *sk, unsigned char *from,
  1437.       int len, int nonblock, unsigned flags)
  1438. {
  1439.     int copied = 0;
  1440.     int copy;
  1441.     int tmp;
  1442.     struct sk_buff *skb;
  1443.     struct sk_buff *send_tmp;
  1444.     unsigned char *buff;
  1445.     struct proto *prot;
  1446.     struct device *dev = NULL;
  1447.  
  1448.     sk->inuse=1;
  1449.     prot = sk->prot;
  1450.     while(len > 0) 
  1451.     {
  1452.         if (sk->err) 
  1453.         {            /* Stop on an error */
  1454.             release_sock(sk);
  1455.             if (copied) 
  1456.                 return(copied);
  1457.             tmp = -sk->err;
  1458.             sk->err = 0;
  1459.             return(tmp);
  1460.         }
  1461.  
  1462.         /*
  1463.          *    First thing we do is make sure that we are established. 
  1464.          */
  1465.     
  1466.         if (sk->shutdown & SEND_SHUTDOWN) 
  1467.         {
  1468.             release_sock(sk);
  1469.             sk->err = EPIPE;
  1470.             if (copied) 
  1471.                 return(copied);
  1472.             sk->err = 0;
  1473.             return(-EPIPE);
  1474.         }
  1475.  
  1476.         /* 
  1477.          *    Wait for a connection to finish.
  1478.          */
  1479.     
  1480.         while(sk->state != TCP_ESTABLISHED && sk->state != TCP_CLOSE_WAIT) 
  1481.         {
  1482.             if (sk->err) 
  1483.             {
  1484.                 release_sock(sk);
  1485.                 if (copied) 
  1486.                     return(copied);
  1487.                 tmp = -sk->err;
  1488.                 sk->err = 0;
  1489.                 return(tmp);
  1490.             }
  1491.  
  1492.             if (sk->state != TCP_SYN_SENT && sk->state != TCP_SYN_RECV) 
  1493.             {
  1494.                 release_sock(sk);
  1495.                 if (copied) 
  1496.                     return(copied);
  1497.  
  1498.                 if (sk->err) 
  1499.                 {
  1500.                     tmp = -sk->err;
  1501.                     sk->err = 0;
  1502.                     return(tmp);
  1503.                 }
  1504.  
  1505.                 if (sk->keepopen) 
  1506.                 {
  1507.                     send_sig(SIGPIPE, current, 0);
  1508.                 }
  1509.                 return(-EPIPE);
  1510.             }
  1511.  
  1512.             if (nonblock || copied) 
  1513.             {
  1514.                 release_sock(sk);
  1515.                 if (copied) 
  1516.                     return(copied);
  1517.                 return(-EAGAIN);
  1518.             }
  1519.  
  1520.             release_sock(sk);
  1521.             cli();
  1522.         
  1523.             if (sk->state != TCP_ESTABLISHED &&
  1524.                     sk->state != TCP_CLOSE_WAIT && sk->err == 0) 
  1525.                 {
  1526.                 interruptible_sleep_on(sk->sleep);
  1527.                 if (current->signal & ~current->blocked) 
  1528.                 {
  1529.                     sti();
  1530.                     if (copied) 
  1531.                         return(copied);
  1532.                     return(-ERESTARTSYS);
  1533.                 }
  1534.             }
  1535.             sk->inuse = 1;
  1536.             sti();
  1537.         }
  1538.  
  1539.     /*
  1540.      * The following code can result in copy <= if sk->mss is ever
  1541.      * decreased.  It shouldn't be.  sk->mss is min(sk->mtu, sk->max_window).
  1542.      * sk->mtu is constant once SYN processing is finished.  I.e. we
  1543.      * had better not get here until we've seen his SYN and at least one
  1544.      * valid ack.  (The SYN sets sk->mtu and the ack sets sk->max_window.)
  1545.      * But ESTABLISHED should guarantee that.  sk->max_window is by definition
  1546.      * non-decreasing.  Note that any ioctl to set user_mss must be done
  1547.      * before the exchange of SYN's.  If the initial ack from the other
  1548.      * end has a window of 0, max_window and thus mss will both be 0.
  1549.      */
  1550.  
  1551.     /* 
  1552.      *    Now we need to check if we have a half built packet. 
  1553.      */
  1554.  
  1555.         if ((skb = tcp_dequeue_partial(sk)) != NULL) 
  1556.         {
  1557.                 int hdrlen;
  1558.  
  1559.                  /* IP header + TCP header */
  1560.             hdrlen = ((unsigned long)skb->h.th - (unsigned long)skb->data)
  1561.                      + sizeof(struct tcphdr);
  1562.     
  1563.             /* Add more stuff to the end of skb->len */
  1564.             if (!(flags & MSG_OOB)) 
  1565.             {
  1566.                 copy = min(sk->mss - (skb->len - hdrlen), len);
  1567.                 /* FIXME: this is really a bug. */
  1568.                 if (copy <= 0) 
  1569.                 {
  1570.                       printk("TCP: **bug**: \"copy\" <= 0!!\n");
  1571.                       copy = 0;
  1572.                 }
  1573.       
  1574.                 memcpy_fromfs(skb->data + skb->len, from, copy);
  1575.                 skb->len += copy;
  1576.                 from += copy;
  1577.                 copied += copy;
  1578.                 len -= copy;
  1579.                 sk->write_seq += copy;
  1580.             }
  1581.             if ((skb->len - hdrlen) >= sk->mss ||
  1582.                 (flags & MSG_OOB) || !sk->packets_out)
  1583.                 tcp_send_skb(sk, skb);
  1584.             else
  1585.                 tcp_enqueue_partial(skb, sk);
  1586.             continue;
  1587.         }
  1588.  
  1589.     /*
  1590.      * We also need to worry about the window.
  1591.       * If window < 1/2 the maximum window we've seen from this
  1592.       *   host, don't use it.  This is sender side
  1593.       *   silly window prevention, as specified in RFC1122.
  1594.       *   (Note that this is different than earlier versions of
  1595.       *   SWS prevention, e.g. RFC813.).  What we actually do is 
  1596.      *   use the whole MSS.  Since the results in the right
  1597.      *   edge of the packet being outside the window, it will
  1598.      *   be queued for later rather than sent.
  1599.      */
  1600.  
  1601.         copy = sk->window_seq - sk->write_seq;
  1602.         if (copy <= 0 || copy < (sk->max_window >> 1) || copy > sk->mss)
  1603.             copy = sk->mss;
  1604.         if (copy > len)
  1605.             copy = len;
  1606.  
  1607.     /*
  1608.      *    We should really check the window here also. 
  1609.      */
  1610.      
  1611.         send_tmp = NULL;
  1612.         if (copy < sk->mss && !(flags & MSG_OOB)) 
  1613.         {
  1614.             /*
  1615.              *    We will release the socket in case we sleep here. 
  1616.              */
  1617.             release_sock(sk);
  1618.             /*
  1619.              *    NB: following must be mtu, because mss can be increased.
  1620.              *    mss is always <= mtu 
  1621.              */
  1622.             skb = prot->wmalloc(sk, sk->mtu + 128 + prot->max_header, 0, GFP_KERNEL);
  1623.             sk->inuse = 1;
  1624.             send_tmp = skb;
  1625.         } 
  1626.         else 
  1627.         {
  1628.             /*
  1629.              *    We will release the socket in case we sleep here. 
  1630.              */
  1631.             release_sock(sk);
  1632.             skb = prot->wmalloc(sk, copy + prot->max_header , 0, GFP_KERNEL);
  1633.               sk->inuse = 1;
  1634.         }
  1635.  
  1636.         /*
  1637.          *    If we didn't get any memory, we need to sleep. 
  1638.          */
  1639.  
  1640.         if (skb == NULL) 
  1641.         {
  1642.             sk->socket->flags |= SO_NOSPACE;
  1643.             if (nonblock) 
  1644.             {
  1645.                 release_sock(sk);
  1646.                 if (copied) 
  1647.                     return(copied);
  1648.                 return(-EAGAIN);
  1649.             }
  1650.  
  1651.             /*
  1652.              *    FIXME: here is another race condition. 
  1653.              */
  1654.  
  1655.             tmp = sk->wmem_alloc;
  1656.             release_sock(sk);
  1657.             cli();
  1658.             /*
  1659.              *    Again we will try to avoid it. 
  1660.              */
  1661.             if (tmp <= sk->wmem_alloc &&
  1662.                   (sk->state == TCP_ESTABLISHED||sk->state == TCP_CLOSE_WAIT)
  1663.                 && sk->err == 0) 
  1664.             {
  1665.                 sk->socket->flags &= ~SO_NOSPACE;
  1666.                 interruptible_sleep_on(sk->sleep);
  1667.                 if (current->signal & ~current->blocked) 
  1668.                 {
  1669.                     sti();
  1670.                     if (copied) 
  1671.                         return(copied);
  1672.                     return(-ERESTARTSYS);
  1673.                 }
  1674.             }
  1675.             sk->inuse = 1;
  1676.             sti();
  1677.             continue;
  1678.         }
  1679.  
  1680.         skb->len = 0;
  1681.         skb->sk = sk;
  1682.         skb->free = 0;
  1683.         skb->localroute = sk->localroute|(flags&MSG_DONTROUTE);
  1684.     
  1685.         buff = skb->data;
  1686.     
  1687.         /*
  1688.          * FIXME: we need to optimize this.
  1689.          * Perhaps some hints here would be good.
  1690.          */
  1691.         
  1692.         tmp = prot->build_header(skb, sk->saddr, sk->daddr, &dev,
  1693.                  IPPROTO_TCP, sk->opt, skb->mem_len,sk->ip_tos,sk->ip_ttl);
  1694.         if (tmp < 0 ) 
  1695.         {
  1696.             prot->wfree(sk, skb->mem_addr, skb->mem_len);
  1697.             release_sock(sk);
  1698.             if (copied) 
  1699.                 return(copied);
  1700.             return(tmp);
  1701.         }
  1702.         skb->len += tmp;
  1703.         skb->dev = dev;
  1704.         buff += tmp;
  1705.         skb->h.th =(struct tcphdr *) buff;
  1706.         tmp = tcp_build_header((struct tcphdr *)buff, sk, len-copy);
  1707.         if (tmp < 0) 
  1708.         {
  1709.             prot->wfree(sk, skb->mem_addr, skb->mem_len);
  1710.             release_sock(sk);
  1711.             if (copied) 
  1712.                 return(copied);
  1713.             return(tmp);
  1714.         }
  1715.  
  1716.         if (flags & MSG_OOB) 
  1717.         {
  1718.             ((struct tcphdr *)buff)->urg = 1;
  1719.             ((struct tcphdr *)buff)->urg_ptr = ntohs(copy);
  1720.         }
  1721.         skb->len += tmp;
  1722.         memcpy_fromfs(buff+tmp, from, copy);
  1723.  
  1724.         from += copy;
  1725.         copied += copy;
  1726.         len -= copy;
  1727.         skb->len += copy;
  1728.         skb->free = 0;
  1729.         sk->write_seq += copy;
  1730.     
  1731.         if (send_tmp != NULL && sk->packets_out) 
  1732.         {
  1733.             tcp_enqueue_partial(send_tmp, sk);
  1734.             continue;
  1735.         }
  1736.         tcp_send_skb(sk, skb);
  1737.     }
  1738.     sk->err = 0;
  1739.  
  1740. /*
  1741.  *    Nagle's rule. Turn Nagle off with TCP_NODELAY for highly
  1742.  *    interactive fast network servers. It's meant to be on and
  1743.  *    it really improves the throughput though not the echo time
  1744.  *    on my slow slip link - Alan
  1745.  */
  1746.  
  1747. /*
  1748.  *    Avoid possible race on send_tmp - c/o Johannes Stille 
  1749.  */
  1750.  
  1751.     if(sk->partial && ((!sk->packets_out) 
  1752.      /* If not nagling we can send on the before case too.. */
  1753.           || (sk->nonagle && before(sk->write_seq , sk->window_seq))
  1754.           ))
  1755.           tcp_send_partial(sk);
  1756.  
  1757.     release_sock(sk);
  1758.     return(copied);
  1759. }
  1760.  
  1761. /*
  1762.  *    This is just a wrapper. 
  1763.  */
  1764.  
  1765. static int tcp_sendto(struct sock *sk, unsigned char *from,
  1766.        int len, int nonblock, unsigned flags,
  1767.        struct sockaddr_in *addr, int addr_len)
  1768. {
  1769.     if (flags & ~(MSG_OOB|MSG_DONTROUTE))
  1770.         return -EINVAL;
  1771.     if (sk->state == TCP_CLOSE)
  1772.         return -ENOTCONN;
  1773.     if (addr_len < sizeof(*addr))
  1774.         return -EINVAL;
  1775.     if (addr->sin_family && addr->sin_family != AF_INET) 
  1776.         return -EINVAL;
  1777.     if (addr->sin_port != sk->dummy_th.dest) 
  1778.         return -EISCONN;
  1779.     if (addr->sin_addr.s_addr != sk->daddr) 
  1780.         return -EISCONN;
  1781.     return tcp_write(sk, from, len, nonblock, flags);
  1782. }
  1783.  
  1784.  
  1785. /*
  1786.  *    Send an ack if one is backlogged at this point. Ought to merge
  1787.  *    this with tcp_send_ack().
  1788.  */
  1789.  
  1790. static void tcp_read_wakeup(struct sock *sk)
  1791. {
  1792.     int tmp;
  1793.     struct device *dev = NULL;
  1794.     struct tcphdr *t1;
  1795.     struct sk_buff *buff;
  1796.  
  1797.     if (!sk->ack_backlog) 
  1798.         return;
  1799.  
  1800.     /*
  1801.      * FIXME: we need to put code here to prevent this routine from
  1802.      * being called.  Being called once in a while is ok, so only check
  1803.      * if this is the second time in a row.
  1804.       */
  1805.  
  1806.     /*
  1807.      * We need to grab some memory, and put together an ack,
  1808.      * and then put it into the queue to be sent.
  1809.      */
  1810.  
  1811.     buff = sk->prot->wmalloc(sk,MAX_ACK_SIZE,1, GFP_ATOMIC);
  1812.     if (buff == NULL) 
  1813.     {
  1814.         /* Try again real soon. */
  1815.         reset_xmit_timer(sk, TIME_WRITE, HZ);
  1816.         return;
  1817.      }
  1818.  
  1819.     buff->len = sizeof(struct tcphdr);
  1820.     buff->sk = sk;
  1821.     buff->localroute = sk->localroute;
  1822.     
  1823.     /*
  1824.      *    Put in the IP header and routing stuff. 
  1825.      */
  1826.  
  1827.     tmp = sk->prot->build_header(buff, sk->saddr, sk->daddr, &dev,
  1828.                    IPPROTO_TCP, sk->opt, MAX_ACK_SIZE,sk->ip_tos,sk->ip_ttl);
  1829.     if (tmp < 0) 
  1830.     {
  1831.           buff->free = 1;
  1832.         sk->prot->wfree(sk, buff->mem_addr, buff->mem_len);
  1833.         return;
  1834.     }
  1835.  
  1836.     buff->len += tmp;
  1837.     t1 =(struct tcphdr *)(buff->data +tmp);
  1838.  
  1839.     memcpy(t1,(void *) &sk->dummy_th, sizeof(*t1));
  1840.     t1->seq = htonl(sk->sent_seq);
  1841.     t1->ack = 1;
  1842.     t1->res1 = 0;
  1843.     t1->res2 = 0;
  1844.     t1->rst = 0;
  1845.     t1->urg = 0;
  1846.     t1->syn = 0;
  1847.     t1->psh = 0;
  1848.     sk->ack_backlog = 0;
  1849.     sk->bytes_rcv = 0;
  1850.     sk->window = tcp_select_window(sk);
  1851.     t1->window = ntohs(sk->window);
  1852.     t1->ack_seq = ntohl(sk->acked_seq);
  1853.     t1->doff = sizeof(*t1)/4;
  1854.     tcp_send_check(t1, sk->saddr, sk->daddr, sizeof(*t1), sk);
  1855.     sk->prot->queue_xmit(sk, dev, buff, 1);
  1856.     tcp_statistics.TcpOutSegs++;
  1857. }
  1858.  
  1859.  
  1860. /*
  1861.  *     FIXME:
  1862.  *     This routine frees used buffers.
  1863.  *     It should consider sending an ACK to let the
  1864.  *     other end know we now have a bigger window.
  1865.  */
  1866.  
  1867. static void cleanup_rbuf(struct sock *sk)
  1868. {
  1869.     unsigned long flags;
  1870.     unsigned long left;
  1871.     struct sk_buff *skb;
  1872.     unsigned long rspace;
  1873.  
  1874.     if(sk->debug)
  1875.           printk("cleaning rbuf for sk=%p\n", sk);
  1876.   
  1877.     save_flags(flags);
  1878.     cli();
  1879.   
  1880.     left = sk->prot->rspace(sk);
  1881.  
  1882.     /*
  1883.      *    We have to loop through all the buffer headers,
  1884.      *    and try to free up all the space we can.
  1885.      */
  1886.  
  1887.     while((skb=skb_peek(&sk->receive_queue)) != NULL) 
  1888.     {
  1889.         if (!skb->used || skb->users) 
  1890.             break;
  1891.         skb_unlink(skb);
  1892.         skb->sk = sk;
  1893.         kfree_skb(skb, FREE_READ);
  1894.     }
  1895.  
  1896.     restore_flags(flags);
  1897.  
  1898.     /*
  1899.      *    FIXME:
  1900.      *    At this point we should send an ack if the difference
  1901.      *    in the window, and the amount of space is bigger than
  1902.      *    TCP_WINDOW_DIFF.
  1903.      */
  1904.  
  1905.     if(sk->debug)
  1906.         printk("sk->rspace = %lu, was %lu\n", sk->prot->rspace(sk),
  1907.                           left);
  1908.     if ((rspace=sk->prot->rspace(sk)) != left) 
  1909.     {
  1910.         /*
  1911.          * This area has caused the most trouble.  The current strategy
  1912.          * is to simply do nothing if the other end has room to send at
  1913.          * least 3 full packets, because the ack from those will auto-
  1914.          * matically update the window.  If the other end doesn't think
  1915.          * we have much space left, but we have room for at least 1 more
  1916.          * complete packet than it thinks we do, we will send an ack
  1917.          * immediately.  Otherwise we will wait up to .5 seconds in case
  1918.          * the user reads some more.
  1919.          */
  1920.         sk->ack_backlog++;
  1921.     /*
  1922.      * It's unclear whether to use sk->mtu or sk->mss here.  They differ only
  1923.      * if the other end is offering a window smaller than the agreed on MSS
  1924.      * (called sk->mtu here).  In theory there's no connection between send
  1925.      * and receive, and so no reason to think that they're going to send
  1926.      * small packets.  For the moment I'm using the hack of reducing the mss
  1927.      * only on the send side, so I'm putting mtu here.
  1928.      */
  1929.  
  1930.         if (rspace > (sk->window - sk->bytes_rcv + sk->mtu)) 
  1931.         {
  1932.             /* Send an ack right now. */
  1933.             tcp_read_wakeup(sk);
  1934.         } 
  1935.         else 
  1936.         {
  1937.             /* Force it to send an ack soon. */
  1938.             int was_active = del_timer(&sk->retransmit_timer);
  1939.             if (!was_active || TCP_ACK_TIME < sk->timer.expires) 
  1940.             {
  1941.                 reset_xmit_timer(sk, TIME_WRITE, TCP_ACK_TIME);
  1942.             } 
  1943.             else
  1944.                 add_timer(&sk->retransmit_timer);
  1945.         }
  1946.     }
  1947.  
  1948.  
  1949. /*
  1950.  *    Handle reading urgent data. BSD has very simple semantics for
  1951.  *    this, no blocking and very strange errors 8)
  1952.  */
  1953.  
  1954. static int tcp_read_urg(struct sock * sk, int nonblock,
  1955.          unsigned char *to, int len, unsigned flags)
  1956. {
  1957.     /*
  1958.      *    No URG data to read
  1959.      */
  1960.     if (sk->urginline || !sk->urg_data || sk->urg_data == URG_READ)
  1961.         return -EINVAL;    /* Yes this is right ! */
  1962.         
  1963.     if (sk->err) 
  1964.     {
  1965.         int tmp = -sk->err;
  1966.         sk->err = 0;
  1967.         return tmp;
  1968.     }
  1969.  
  1970.     if (sk->state == TCP_CLOSE || sk->done) 
  1971.     {
  1972.         if (!sk->done) {
  1973.             sk->done = 1;
  1974.             return 0;
  1975.         }
  1976.         return -ENOTCONN;
  1977.     }
  1978.  
  1979.     if (sk->shutdown & RCV_SHUTDOWN) 
  1980.     {
  1981.         sk->done = 1;
  1982.         return 0;
  1983.     }
  1984.     sk->inuse = 1;
  1985.     if (sk->urg_data & URG_VALID) 
  1986.     {
  1987.         char c = sk->urg_data;
  1988.         if (!(flags & MSG_PEEK))
  1989.             sk->urg_data = URG_READ;
  1990.         put_fs_byte(c, to);
  1991.         release_sock(sk);
  1992.         return 1;
  1993.     }
  1994.     release_sock(sk);
  1995.     
  1996.     /*
  1997.      * Fixed the recv(..., MSG_OOB) behaviour.  BSD docs and
  1998.      * the available implementations agree in this case:
  1999.      * this call should never block, independent of the
  2000.      * blocking state of the socket.
  2001.      * Mike <pall@rz.uni-karlsruhe.de>
  2002.      */
  2003.     return -EAGAIN;
  2004. }
  2005.  
  2006.  
  2007. /*
  2008.  *    This routine copies from a sock struct into the user buffer. 
  2009.  */
  2010.  
  2011. static int tcp_read(struct sock *sk, unsigned char *to,
  2012.     int len, int nonblock, unsigned flags)
  2013. {
  2014.     struct wait_queue wait = { current, NULL };
  2015.     int copied = 0;
  2016.     unsigned long peek_seq;
  2017.     volatile unsigned long *seq;    /* So gcc doesn't overoptimise */
  2018.     unsigned long used;
  2019.  
  2020.     /* 
  2021.      *    This error should be checked. 
  2022.      */
  2023.      
  2024.     if (sk->state == TCP_LISTEN)
  2025.         return -ENOTCONN;
  2026.  
  2027.     /*
  2028.      *    Urgent data needs to be handled specially. 
  2029.      */
  2030.      
  2031.     if (flags & MSG_OOB)
  2032.         return tcp_read_urg(sk, nonblock, to, len, flags);
  2033.  
  2034.     /*
  2035.      *    Copying sequence to update. This is volatile to handle
  2036.      *    the multi-reader case neatly (memcpy_to/fromfs might be 
  2037.      *    inline and thus not flush cached variables otherwise).
  2038.      */
  2039.      
  2040.     peek_seq = sk->copied_seq;
  2041.     seq = &sk->copied_seq;
  2042.     if (flags & MSG_PEEK)
  2043.         seq = &peek_seq;
  2044.  
  2045.     add_wait_queue(sk->sleep, &wait);
  2046.     sk->inuse = 1;
  2047.     while (len > 0) 
  2048.     {
  2049.         struct sk_buff * skb;
  2050.         unsigned long offset;
  2051.     
  2052.         /*
  2053.          * Are we at urgent data? Stop if we have read anything.
  2054.          */
  2055.          
  2056.         if (copied && sk->urg_data && sk->urg_seq == *seq)
  2057.             break;
  2058.  
  2059.         /*
  2060.          *    Next get a buffer.
  2061.          */
  2062.          
  2063.         current->state = TASK_INTERRUPTIBLE;
  2064.  
  2065.         skb = skb_peek(&sk->receive_queue);
  2066.         do 
  2067.         {
  2068.             if (!skb)
  2069.                 break;
  2070.             if (before(*seq, skb->h.th->seq))
  2071.                 break;
  2072.             offset = *seq - skb->h.th->seq;
  2073.             if (skb->h.th->syn)
  2074.                 offset--;
  2075.             if (offset < skb->len)
  2076.                 goto found_ok_skb;
  2077.             if (skb->h.th->fin)
  2078.                 goto found_fin_ok;
  2079.             if (!(flags & MSG_PEEK))
  2080.                 skb->used = 1;
  2081.             skb = skb->next;
  2082.         }
  2083.         while (skb != (struct sk_buff *)&sk->receive_queue);
  2084.  
  2085.         if (copied)
  2086.             break;
  2087.  
  2088.         if (sk->err) 
  2089.         {
  2090.             copied = -sk->err;
  2091.             sk->err = 0;
  2092.             break;
  2093.         }
  2094.  
  2095.         if (sk->state == TCP_CLOSE) 
  2096.         {
  2097.             if (!sk->done) 
  2098.             {
  2099.                 sk->done = 1;
  2100.                 break;
  2101.             }
  2102.             copied = -ENOTCONN;
  2103.             break;
  2104.         }
  2105.  
  2106.         if (sk->shutdown & RCV_SHUTDOWN) 
  2107.         {
  2108.             sk->done = 1;
  2109.             break;
  2110.         }
  2111.             
  2112.         if (nonblock) 
  2113.         {
  2114.             copied = -EAGAIN;
  2115.             break;
  2116.         }
  2117.  
  2118.         cleanup_rbuf(sk);
  2119.         release_sock(sk);
  2120.         sk->socket->flags |= SO_WAITDATA;
  2121.         schedule();
  2122.         sk->socket->flags &= ~SO_WAITDATA;
  2123.         sk->inuse = 1;
  2124.  
  2125.         if (current->signal & ~current->blocked) 
  2126.         {
  2127.             copied = -ERESTARTSYS;
  2128.             break;
  2129.         }
  2130.         continue;
  2131.  
  2132.     found_ok_skb:
  2133.         /*
  2134.          *    Lock the buffer. We can be fairly relaxed as
  2135.          *    an interrupt will never steal a buffer we are 
  2136.          *    using unless I've missed something serious in
  2137.          *    tcp_data.
  2138.          */
  2139.         
  2140.         skb->users++;
  2141.         
  2142.         /*
  2143.          *    Ok so how much can we use ? 
  2144.          */
  2145.          
  2146.         used = skb->len - offset;
  2147.         if (len < used)
  2148.             used = len;
  2149.         /*
  2150.          *    Do we have urgent data here? 
  2151.          */
  2152.         
  2153.         if (sk->urg_data) 
  2154.         {
  2155.             unsigned long urg_offset = sk->urg_seq - *seq;
  2156.             if (urg_offset < used) 
  2157.             {
  2158.                 if (!urg_offset) 
  2159.                 {
  2160.                     if (!sk->urginline) 
  2161.                     {
  2162.                         ++*seq;
  2163.                         offset++;
  2164.                         used--;
  2165.                     }
  2166.                 }
  2167.                 else
  2168.                     used = urg_offset;
  2169.             }
  2170.         }
  2171.         
  2172.         /*
  2173.          *    Copy it - We _MUST_ update *seq first so that we
  2174.          *    don't ever double read when we have dual readers
  2175.          */
  2176.          
  2177.         *seq += used;
  2178.  
  2179.         /*
  2180.          *    This memcpy_tofs can sleep. If it sleeps and we
  2181.          *    do a second read it relies on the skb->users to avoid
  2182.          *    a crash when cleanup_rbuf() gets called.
  2183.          */
  2184.          
  2185.         memcpy_tofs(to,((unsigned char *)skb->h.th) +
  2186.             skb->h.th->doff*4 + offset, used);
  2187.         copied += used;
  2188.         len -= used;
  2189.         to += used;
  2190.         
  2191.         /*
  2192.          *    We now will not sleep again until we are finished
  2193.          *    with skb. Sorry if you are doing the SMP port
  2194.          *    but you'll just have to fix it neatly ;)
  2195.          */
  2196.          
  2197.         skb->users --;
  2198.         
  2199.         if (after(sk->copied_seq,sk->urg_seq))
  2200.             sk->urg_data = 0;
  2201.         if (used + offset < skb->len)
  2202.             continue;
  2203.         
  2204.         /*
  2205.          *    Process the FIN.
  2206.          */
  2207.  
  2208.         if (skb->h.th->fin)
  2209.             goto found_fin_ok;
  2210.         if (flags & MSG_PEEK)
  2211.             continue;
  2212.         skb->used = 1;
  2213.         continue;
  2214.  
  2215.     found_fin_ok:
  2216.         ++*seq;
  2217.         if (flags & MSG_PEEK)
  2218.             break;
  2219.             
  2220.         /*
  2221.          *    All is done
  2222.          */
  2223.          
  2224.         skb->used = 1;
  2225.         sk->shutdown |= RCV_SHUTDOWN;
  2226.         break;
  2227.  
  2228.     }
  2229.     remove_wait_queue(sk->sleep, &wait);
  2230.     current->state = TASK_RUNNING;
  2231.  
  2232.     /* Clean up data we have read: This will do ACK frames */
  2233.     cleanup_rbuf(sk);
  2234.     release_sock(sk);
  2235.     return copied;
  2236. }
  2237.  
  2238. /*
  2239.  *    State processing on a close. This implements the state shift for
  2240.  *    sending our FIN frame. Note that we only send a FIN for some 
  2241.  *    states. A shutdown() may have already sent the FIN, or we may be
  2242.  *    closed.
  2243.  */
  2244.  
  2245. static int tcp_close_state(struct sock *sk, int dead)
  2246. {
  2247.     int ns=TCP_CLOSE;
  2248.     int send_fin=0;
  2249.     switch(sk->state)
  2250.     {
  2251.         case TCP_SYN_SENT:    /* No SYN back, no FIN needed */
  2252.             break;
  2253.         case TCP_SYN_RECV:
  2254.         case TCP_ESTABLISHED:    /* Closedown begin */
  2255.             ns=TCP_FIN_WAIT1;
  2256.             send_fin=1;
  2257.             break;
  2258.         case TCP_FIN_WAIT1:    /* Already closing, or FIN sent: no change */
  2259.         case TCP_FIN_WAIT2:
  2260.         case TCP_CLOSING:
  2261.             ns=sk->state;
  2262.             break;
  2263.         case TCP_CLOSE:
  2264.         case TCP_LISTEN:
  2265.             break;
  2266.         case TCP_CLOSE_WAIT:    /* They have FIN'd us. We send our FIN and
  2267.                        wait only for the ACK */
  2268.             ns=TCP_LAST_ACK;
  2269.             send_fin=1;
  2270.     }
  2271.     
  2272.     tcp_set_state(sk,ns);
  2273.         
  2274.     /*
  2275.      *    This is a (useful) BSD violating of the RFC. There is a
  2276.      *    problem with TCP as specified in that the other end could
  2277.      *    keep a socket open forever with no application left this end.
  2278.      *    We use a 3 minute timeout (about the same as BSD) then kill
  2279.      *    our end. If they send after that then tough - BUT: long enough
  2280.      *    that we won't make the old 4*rto = almost no time - whoops
  2281.      *    reset mistake.
  2282.      */
  2283.     if(dead && ns==TCP_FIN_WAIT2)
  2284.     {
  2285.         int timer_active=del_timer(&sk->timer);
  2286.         if(timer_active)
  2287.             add_timer(&sk->timer);
  2288.         else
  2289.             reset_msl_timer(sk, TIME_CLOSE, TCP_FIN_TIMEOUT);
  2290.     }
  2291.     
  2292.     return send_fin;
  2293. }
  2294.  
  2295. /*
  2296.  *    Send a fin.
  2297.  */
  2298.  
  2299. static void tcp_send_fin(struct sock *sk)
  2300. {
  2301.     struct proto *prot =(struct proto *)sk->prot;
  2302.     struct tcphdr *th =(struct tcphdr *)&sk->dummy_th;
  2303.     struct tcphdr *t1;
  2304.     struct sk_buff *buff;
  2305.     struct device *dev=NULL;
  2306.     int tmp;
  2307.         
  2308.     release_sock(sk); /* in case the malloc sleeps. */
  2309.     
  2310.     buff = prot->wmalloc(sk, MAX_RESET_SIZE,1 , GFP_KERNEL);
  2311.     sk->inuse = 1;
  2312.  
  2313.     if (buff == NULL)
  2314.     {
  2315.         /* This is a disaster if it occurs */
  2316.         printk("tcp_send_fin: Impossible malloc failure");
  2317.         return;
  2318.     }
  2319.  
  2320.     /*
  2321.      *    Administrivia
  2322.      */
  2323.      
  2324.     buff->sk = sk;
  2325.     buff->len = sizeof(*t1);
  2326.     buff->localroute = sk->localroute;
  2327.     t1 =(struct tcphdr *) buff->data;
  2328.  
  2329.     /*
  2330.      *    Put in the IP header and routing stuff. 
  2331.      */
  2332.  
  2333.     tmp = prot->build_header(buff,sk->saddr, sk->daddr, &dev,
  2334.                IPPROTO_TCP, sk->opt,
  2335.                sizeof(struct tcphdr),sk->ip_tos,sk->ip_ttl);
  2336.     if (tmp < 0) 
  2337.     {
  2338.         int t;
  2339.           /*
  2340.            *    Finish anyway, treat this as a send that got lost. 
  2341.            *    (Not good).
  2342.            */
  2343.            
  2344.           buff->free = 1;
  2345.         prot->wfree(sk,buff->mem_addr, buff->mem_len);
  2346.         sk->write_seq++;
  2347.         t=del_timer(&sk->timer);
  2348.         if(t)
  2349.             add_timer(&sk->timer);
  2350.         else
  2351.             reset_msl_timer(sk, TIME_CLOSE, TCP_TIMEWAIT_LEN);
  2352.         return;
  2353.     }
  2354.     
  2355.     /*
  2356.      *    We ought to check if the end of the queue is a buffer and
  2357.      *    if so simply add the fin to that buffer, not send it ahead.
  2358.      */
  2359.  
  2360.     t1 =(struct tcphdr *)((char *)t1 +tmp);
  2361.     buff->len += tmp;
  2362.     buff->dev = dev;
  2363.     memcpy(t1, th, sizeof(*t1));
  2364.     t1->seq = ntohl(sk->write_seq);
  2365.     sk->write_seq++;
  2366.     buff->h.seq = sk->write_seq;
  2367.     t1->ack = 1;
  2368.     t1->ack_seq = ntohl(sk->acked_seq);
  2369.     t1->window = ntohs(sk->window=tcp_select_window(sk));
  2370.     t1->fin = 1;
  2371.     t1->rst = 0;
  2372.     t1->doff = sizeof(*t1)/4;
  2373.     tcp_send_check(t1, sk->saddr, sk->daddr, sizeof(*t1), sk);
  2374.  
  2375.     /*
  2376.      * If there is data in the write queue, the fin must be appended to
  2377.      * the write queue.
  2378.       */
  2379.      
  2380.      if (skb_peek(&sk->write_queue) != NULL) 
  2381.      {
  2382.           buff->free = 0;
  2383.         if (buff->next != NULL) 
  2384.         {
  2385.             printk("tcp_send_fin: next != NULL\n");
  2386.             skb_unlink(buff);
  2387.         }
  2388.         skb_queue_tail(&sk->write_queue, buff);
  2389.       } 
  2390.       else 
  2391.       {
  2392.             sk->sent_seq = sk->write_seq;
  2393.         sk->prot->queue_xmit(sk, dev, buff, 0);
  2394.         reset_xmit_timer(sk, TIME_WRITE, sk->rto);
  2395.     }
  2396. }
  2397.  
  2398. /*
  2399.  *    Shutdown the sending side of a connection. Much like close except
  2400.  *    that we don't receive shut down or set sk->dead=1.
  2401.  */
  2402.  
  2403. void tcp_shutdown(struct sock *sk, int how)
  2404. {
  2405.     /*
  2406.      *    We need to grab some memory, and put together a FIN,
  2407.      *    and then put it into the queue to be sent.
  2408.      *        Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
  2409.      */
  2410.  
  2411.     if (!(how & SEND_SHUTDOWN)) 
  2412.         return;
  2413.      
  2414.     /*
  2415.      *    If we've already sent a FIN, or it's a closed state
  2416.      */
  2417.      
  2418.     if (sk->state == TCP_FIN_WAIT1 ||
  2419.         sk->state == TCP_FIN_WAIT2 ||
  2420.         sk->state == TCP_CLOSING ||
  2421.         sk->state == TCP_LAST_ACK ||
  2422.         sk->state == TCP_TIME_WAIT || 
  2423.         sk->state == TCP_CLOSE ||
  2424.         sk->state == TCP_LISTEN
  2425.       )
  2426.     {
  2427.         return;
  2428.     }
  2429.     sk->inuse = 1;
  2430.  
  2431.     /*
  2432.      * flag that the sender has shutdown
  2433.      */
  2434.  
  2435.     sk->shutdown |= SEND_SHUTDOWN;
  2436.  
  2437.     /*
  2438.      *  Clear out any half completed packets. 
  2439.      */
  2440.  
  2441.     if (sk->partial)
  2442.         tcp_send_partial(sk);
  2443.         
  2444.     /*
  2445.      *    FIN if needed
  2446.      */
  2447.      
  2448.     if(tcp_close_state(sk,0))
  2449.         tcp_send_fin(sk);
  2450.         
  2451.     release_sock(sk);
  2452. }
  2453.  
  2454.  
  2455. static int
  2456. tcp_recvfrom(struct sock *sk, unsigned char *to,
  2457.          int to_len, int nonblock, unsigned flags,
  2458.          struct sockaddr_in *addr, int *addr_len)
  2459. {
  2460.     int result;
  2461.   
  2462.     /* 
  2463.      *    Have to check these first unlike the old code. If 
  2464.      *    we check them after we lose data on an error
  2465.      *    which is wrong 
  2466.      */
  2467.  
  2468.     if(addr_len)
  2469.         *addr_len = sizeof(*addr);
  2470.     result=tcp_read(sk, to, to_len, nonblock, flags);
  2471.  
  2472.     if (result < 0) 
  2473.         return(result);
  2474.   
  2475.       if(addr)
  2476.       {
  2477.         addr->sin_family = AF_INET;
  2478.          addr->sin_port = sk->dummy_th.dest;
  2479.         addr->sin_addr.s_addr = sk->daddr;
  2480.     }
  2481.     return(result);
  2482. }
  2483.  
  2484.  
  2485. /*
  2486.  *    This routine will send an RST to the other tcp. 
  2487.  */
  2488.  
  2489. static void tcp_reset(unsigned long saddr, unsigned long daddr, struct tcphdr *th,
  2490.       struct proto *prot, struct options *opt, struct device *dev, int tos, int ttl)
  2491. {
  2492.     struct sk_buff *buff;
  2493.     struct tcphdr *t1;
  2494.     int tmp;
  2495.     struct device *ndev=NULL;
  2496.  
  2497.     /*
  2498.      *    Cannot reset a reset (Think about it).
  2499.      */
  2500.      
  2501.     if(th->rst)
  2502.         return;
  2503.   
  2504.     /*
  2505.      * We need to grab some memory, and put together an RST,
  2506.      * and then put it into the queue to be sent.
  2507.      */
  2508.  
  2509.     buff = prot->wmalloc(NULL, MAX_RESET_SIZE, 1, GFP_ATOMIC);
  2510.     if (buff == NULL) 
  2511.           return;
  2512.  
  2513.     buff->len = sizeof(*t1);
  2514.     buff->sk = NULL;
  2515.     buff->dev = dev;
  2516.     buff->localroute = 0;
  2517.  
  2518.     t1 =(struct tcphdr *) buff->data;
  2519.  
  2520.     /*
  2521.      *    Put in the IP header and routing stuff. 
  2522.      */
  2523.  
  2524.     tmp = prot->build_header(buff, saddr, daddr, &ndev, IPPROTO_TCP, opt,
  2525.                sizeof(struct tcphdr),tos,ttl);
  2526.     if (tmp < 0) 
  2527.     {
  2528.           buff->free = 1;
  2529.         prot->wfree(NULL, buff->mem_addr, buff->mem_len);
  2530.         return;
  2531.     }
  2532.  
  2533.     t1 =(struct tcphdr *)((char *)t1 +tmp);
  2534.     buff->len += tmp;
  2535.     memcpy(t1, th, sizeof(*t1));
  2536.  
  2537.     /*
  2538.      *    Swap the send and the receive. 
  2539.      */
  2540.  
  2541.     t1->dest = th->source;
  2542.     t1->source = th->dest;
  2543.     t1->rst = 1;  
  2544.     t1->window = 0;
  2545.   
  2546.     if(th->ack)
  2547.     {
  2548.         t1->ack = 0;
  2549.           t1->seq = th->ack_seq;
  2550.           t1->ack_seq = 0;
  2551.     }
  2552.     else
  2553.     {
  2554.           t1->ack = 1;
  2555.           if(!th->syn)
  2556.               t1->ack_seq=htonl(th->seq);
  2557.           else
  2558.               t1->ack_seq=htonl(th->seq+1);
  2559.           t1->seq=0;
  2560.     }
  2561.  
  2562.     t1->syn = 0;
  2563.     t1->urg = 0;
  2564.     t1->fin = 0;
  2565.     t1->psh = 0;
  2566.     t1->doff = sizeof(*t1)/4;
  2567.     tcp_send_check(t1, saddr, daddr, sizeof(*t1), NULL);
  2568.     prot->queue_xmit(NULL, ndev, buff, 1);
  2569.     tcp_statistics.TcpOutSegs++;
  2570. }
  2571.  
  2572.  
  2573. /*
  2574.  *    Look for tcp options. Parses everything but only knows about MSS.
  2575.  *      This routine is always called with the packet containing the SYN.
  2576.  *      However it may also be called with the ack to the SYN.  So you
  2577.  *      can't assume this is always the SYN.  It's always called after
  2578.  *      we have set up sk->mtu to our own MTU.
  2579.  *
  2580.  *    We need at minimum to add PAWS support here. Possibly large windows
  2581.  *    as Linux gets deployed on 100Mb/sec networks.
  2582.  */
  2583.  
  2584. static void tcp_options(struct sock *sk, struct tcphdr *th)
  2585. {
  2586.     unsigned char *ptr;
  2587.     int length=(th->doff*4)-sizeof(struct tcphdr);
  2588.     int mss_seen = 0;
  2589.     
  2590.     ptr = (unsigned char *)(th + 1);
  2591.   
  2592.     while(length>0)
  2593.     {
  2594.           int opcode=*ptr++;
  2595.           int opsize=*ptr++;
  2596.           switch(opcode)
  2597.           {
  2598.               case TCPOPT_EOL:
  2599.                   return;
  2600.               case TCPOPT_NOP:    /* Ref: RFC 793 section 3.1 */
  2601.                   length--;
  2602.                   ptr--;        /* the opsize=*ptr++ above was a mistake */
  2603.                   continue;
  2604.               
  2605.               default:
  2606.                   if(opsize<=2)    /* Avoid silly options looping forever */
  2607.                       return;
  2608.                   switch(opcode)
  2609.                   {
  2610.                       case TCPOPT_MSS:
  2611.                           if(opsize==4 && th->syn)
  2612.                           {
  2613.                               sk->mtu=min(sk->mtu,ntohs(*(unsigned short *)ptr));
  2614.                             mss_seen = 1;
  2615.                           }
  2616.                           break;
  2617.                           /* Add other options here as people feel the urge to implement stuff like large windows */
  2618.                   }
  2619.                   ptr+=opsize-2;
  2620.                   length-=opsize;
  2621.           }
  2622.     }
  2623.     if (th->syn) 
  2624.     {
  2625.         if (! mss_seen)
  2626.               sk->mtu=min(sk->mtu, 536);  /* default MSS if none sent */
  2627.     }
  2628. #ifdef CONFIG_INET_PCTCP
  2629.     sk->mss = min(sk->max_window >> 1, sk->mtu);
  2630. #else    
  2631.     sk->mss = min(sk->max_window, sk->mtu);
  2632. #endif  
  2633. }
  2634.  
  2635. static inline unsigned long default_mask(unsigned long dst)
  2636. {
  2637.     dst = ntohl(dst);
  2638.     if (IN_CLASSA(dst))
  2639.         return htonl(IN_CLASSA_NET);
  2640.     if (IN_CLASSB(dst))
  2641.         return htonl(IN_CLASSB_NET);
  2642.     return htonl(IN_CLASSC_NET);
  2643. }
  2644.  
  2645. /*
  2646.  *    Default sequence number picking algorithm.
  2647.  *    As close as possible to RFC 793, which
  2648.  *    suggests using a 250kHz clock.
  2649.  *    Further reading shows this assumes 2MB/s networks.
  2650.  *    For 10MB/s ethernet, a 1MHz clock is appropriate.
  2651.  *    That's funny, Linux has one built in!  Use it!
  2652.  */
  2653.  
  2654. extern inline unsigned long tcp_init_seq(void)
  2655. {
  2656.     struct timeval tv;
  2657.     do_gettimeofday(&tv);
  2658.     return tv.tv_usec+tv.tv_sec*1000000;
  2659. }
  2660.  
  2661. /*
  2662.  *    This routine handles a connection request.
  2663.  *    It should make sure we haven't already responded.
  2664.  *    Because of the way BSD works, we have to send a syn/ack now.
  2665.  *    This also means it will be harder to close a socket which is
  2666.  *    listening.
  2667.  */
  2668.  
  2669. static void tcp_conn_request(struct sock *sk, struct sk_buff *skb,
  2670.          unsigned long daddr, unsigned long saddr,
  2671.          struct options *opt, struct device *dev, unsigned long seq)
  2672. {
  2673.     struct sk_buff *buff;
  2674.     struct tcphdr *t1;
  2675.     unsigned char *ptr;
  2676.     struct sock *newsk;
  2677.     struct tcphdr *th;
  2678.     struct device *ndev=NULL;
  2679.     int tmp;
  2680.     struct rtable *rt;
  2681.   
  2682.     th = skb->h.th;
  2683.  
  2684.     /* If the socket is dead, don't accept the connection. */
  2685.     if (!sk->dead) 
  2686.     {
  2687.           sk->data_ready(sk,0);
  2688.     }
  2689.     else 
  2690.     {
  2691.         if(sk->debug)
  2692.             printk("Reset on %p: Connect on dead socket.\n",sk);
  2693.         tcp_reset(daddr, saddr, th, sk->prot, opt, dev, sk->ip_tos,sk->ip_ttl);
  2694.         tcp_statistics.TcpAttemptFails++;
  2695.         kfree_skb(skb, FREE_READ);
  2696.         return;
  2697.     }
  2698.  
  2699.     /*
  2700.      * Make sure we can accept more.  This will prevent a
  2701.      * flurry of syns from eating up all our memory.
  2702.      */
  2703.  
  2704.     if (sk->ack_backlog >= sk->max_ack_backlog) 
  2705.     {
  2706.         tcp_statistics.TcpAttemptFails++;
  2707.         kfree_skb(skb, FREE_READ);
  2708.         return;
  2709.     }
  2710.  
  2711.     /*
  2712.      * We need to build a new sock struct.
  2713.      * It is sort of bad to have a socket without an inode attached
  2714.      * to it, but the wake_up's will just wake up the listening socket,
  2715.      * and if the listening socket is destroyed before this is taken
  2716.      * off of the queue, this will take care of it.
  2717.      */
  2718.  
  2719.     newsk = (struct sock *) kmalloc(sizeof(struct sock), GFP_ATOMIC);
  2720.     if (newsk == NULL) 
  2721.     {
  2722.         /* just ignore the syn.  It will get retransmitted. */
  2723.         tcp_statistics.TcpAttemptFails++;
  2724.         kfree_skb(skb, FREE_READ);
  2725.         return;
  2726.     }
  2727.  
  2728.     memcpy(newsk, sk, sizeof(*newsk));
  2729.     skb_queue_head_init(&newsk->write_queue);
  2730.     skb_queue_head_init(&newsk->receive_queue);
  2731.     newsk->send_head = NULL;
  2732.     newsk->send_tail = NULL;
  2733.     skb_queue_head_init(&newsk->back_log);
  2734.     newsk->rtt = 0;        /*TCP_CONNECT_TIME<<3*/
  2735.     newsk->rto = TCP_TIMEOUT_INIT;
  2736.     newsk->mdev = 0;
  2737.     newsk->max_window = 0;
  2738.     newsk->cong_window = 1;
  2739.     newsk->cong_count = 0;
  2740.     newsk->ssthresh = 0;
  2741.     newsk->backoff = 0;
  2742.     newsk->blog = 0;
  2743.     newsk->intr = 0;
  2744.     newsk->proc = 0;
  2745.     newsk->done = 0;
  2746.     newsk->partial = NULL;
  2747.     newsk->pair = NULL;
  2748.     newsk->wmem_alloc = 0;
  2749.     newsk->rmem_alloc = 0;
  2750.     newsk->localroute = sk->localroute;
  2751.  
  2752.     newsk->max_unacked = MAX_WINDOW - TCP_WINDOW_DIFF;
  2753.  
  2754.     newsk->err = 0;
  2755.     newsk->shutdown = 0;
  2756.     newsk->ack_backlog = 0;
  2757.     newsk->acked_seq = skb->h.th->seq+1;
  2758.     newsk->copied_seq = skb->h.th->seq+1;
  2759.     newsk->fin_seq = skb->h.th->seq;
  2760.     newsk->state = TCP_SYN_RECV;
  2761.     newsk->timeout = 0;
  2762.     newsk->ip_xmit_timeout = 0;
  2763.     newsk->write_seq = seq; 
  2764.     newsk->window_seq = newsk->write_seq;
  2765.     newsk->rcv_ack_seq = newsk->write_seq;
  2766.     newsk->urg_data = 0;
  2767.     newsk->retransmits = 0;
  2768.     newsk->linger=0;
  2769.     newsk->destroy = 0;
  2770.     init_timer(&newsk->timer);
  2771.     newsk->timer.data = (unsigned long)newsk;
  2772.     newsk->timer.function = &net_timer;
  2773.     init_timer(&newsk->retransmit_timer);
  2774.     newsk->retransmit_timer.data = (unsigned long)newsk;
  2775.     newsk->retransmit_timer.function=&retransmit_timer;
  2776.     newsk->dummy_th.source = skb->h.th->dest;
  2777.     newsk->dummy_th.dest = skb->h.th->source;
  2778.     
  2779.     /*
  2780.      *    Swap these two, they are from our point of view. 
  2781.      */
  2782.      
  2783.     newsk->daddr = saddr;
  2784.     newsk->saddr = daddr;
  2785.  
  2786.     put_sock(newsk->num,newsk);
  2787.     newsk->dummy_th.res1 = 0;
  2788.     newsk->dummy_th.doff = 6;
  2789.     newsk->dummy_th.fin = 0;
  2790.     newsk->dummy_th.syn = 0;
  2791.     newsk->dummy_th.rst = 0;    
  2792.     newsk->dummy_th.psh = 0;
  2793.     newsk->dummy_th.ack = 0;
  2794.     newsk->dummy_th.urg = 0;
  2795.     newsk->dummy_th.res2 = 0;
  2796.     newsk->acked_seq = skb->h.th->seq + 1;
  2797.     newsk->copied_seq = skb->h.th->seq + 1;
  2798.     newsk->socket = NULL;
  2799.  
  2800.     /*
  2801.      *    Grab the ttl and tos values and use them 
  2802.      */
  2803.  
  2804.     newsk->ip_ttl=sk->ip_ttl;
  2805.     newsk->ip_tos=skb->ip_hdr->tos;
  2806.  
  2807.     /*
  2808.      *    Use 512 or whatever user asked for 
  2809.      */
  2810.  
  2811.     /*
  2812.      *     Note use of sk->user_mss, since user has no direct access to newsk 
  2813.      */
  2814.  
  2815.     rt=ip_rt_route(saddr, NULL,NULL);
  2816.     
  2817.     if(rt!=NULL && (rt->rt_flags&RTF_WINDOW))
  2818.         newsk->window_clamp = rt->rt_window;
  2819.     else
  2820.         newsk->window_clamp = 0;
  2821.         
  2822.     if (sk->user_mss)
  2823.         newsk->mtu = sk->user_mss;
  2824.     else if(rt!=NULL && (rt->rt_flags&RTF_MSS))
  2825.         newsk->mtu = rt->rt_mss - HEADER_SIZE;
  2826.     else 
  2827.     {
  2828. #ifdef CONFIG_INET_SNARL    /* Sub Nets Are Local */
  2829.         if ((saddr ^ daddr) & default_mask(saddr))
  2830. #else
  2831.         if ((saddr ^ daddr) & dev->pa_mask)
  2832. #endif
  2833.             newsk->mtu = 576 - HEADER_SIZE;
  2834.         else
  2835.             newsk->mtu = MAX_WINDOW;
  2836.     }
  2837.  
  2838.     /*
  2839.      *    But not bigger than device MTU 
  2840.      */
  2841.  
  2842.     newsk->mtu = min(newsk->mtu, dev->mtu - HEADER_SIZE);
  2843.  
  2844.     /*
  2845.      *    This will min with what arrived in the packet 
  2846.      */
  2847.  
  2848.     tcp_options(newsk,skb->h.th);
  2849.  
  2850.     buff = newsk->prot->wmalloc(newsk, MAX_SYN_SIZE, 1, GFP_ATOMIC);
  2851.     if (buff == NULL) 
  2852.     {
  2853.         sk->err = -ENOMEM;
  2854.         newsk->dead = 1;
  2855.         newsk->state = TCP_CLOSE;
  2856.         /* And this will destroy it */
  2857.         release_sock(newsk);
  2858.         kfree_skb(skb, FREE_READ);
  2859.         tcp_statistics.TcpAttemptFails++;
  2860.         return;
  2861.     }
  2862.   
  2863.     buff->len = sizeof(struct tcphdr)+4;
  2864.     buff->sk = newsk;
  2865.     buff->localroute = newsk->localroute;
  2866.  
  2867.     t1 =(struct tcphdr *) buff->data;
  2868.  
  2869.     /*
  2870.      *    Put in the IP header and routing stuff. 
  2871.      */
  2872.  
  2873.     tmp = sk->prot->build_header(buff, newsk->saddr, newsk->daddr, &ndev,
  2874.                    IPPROTO_TCP, NULL, MAX_SYN_SIZE,sk->ip_tos,sk->ip_ttl);
  2875.  
  2876.     /*
  2877.      *    Something went wrong. 
  2878.      */
  2879.  
  2880.     if (tmp < 0) 
  2881.     {
  2882.         sk->err = tmp;
  2883.         buff->free = 1;
  2884.         kfree_skb(buff,FREE_WRITE);
  2885.         newsk->dead = 1;
  2886.         newsk->state = TCP_CLOSE;
  2887.         release_sock(newsk);
  2888.         skb->sk = sk;
  2889.         kfree_skb(skb, FREE_READ);
  2890.         tcp_statistics.TcpAttemptFails++;
  2891.         return;
  2892.     }
  2893.  
  2894.     buff->len += tmp;
  2895.     t1 =(struct tcphdr *)((char *)t1 +tmp);
  2896.   
  2897.     memcpy(t1, skb->h.th, sizeof(*t1));
  2898.     buff->h.seq = newsk->write_seq;
  2899.     /*
  2900.      *    Swap the send and the receive. 
  2901.      */
  2902.     t1->dest = skb->h.th->source;
  2903.     t1->source = newsk->dummy_th.source;
  2904.     t1->seq = ntohl(newsk->write_seq++);
  2905.     t1->ack = 1;
  2906.     newsk->window = tcp_select_window(newsk);
  2907.     newsk->sent_seq = newsk->write_seq;
  2908.     t1->window = ntohs(newsk->window);
  2909.     t1->res1 = 0;
  2910.     t1->res2 = 0;
  2911.     t1->rst = 0;
  2912.     t1->urg = 0;
  2913.     t1->psh = 0;
  2914.     t1->syn = 1;
  2915.     t1->ack_seq = ntohl(skb->h.th->seq+1);
  2916.     t1->doff = sizeof(*t1)/4+1;
  2917.     ptr =(unsigned char *)(t1+1);
  2918.     ptr[0] = 2;
  2919.     ptr[1] = 4;
  2920.     ptr[2] = ((newsk->mtu) >> 8) & 0xff;
  2921.     ptr[3] =(newsk->mtu) & 0xff;
  2922.  
  2923.     tcp_send_check(t1, daddr, saddr, sizeof(*t1)+4, newsk);
  2924.     newsk->prot->queue_xmit(newsk, ndev, buff, 0);
  2925.     reset_xmit_timer(newsk, TIME_WRITE , TCP_TIMEOUT_INIT);
  2926.     skb->sk = newsk;
  2927.  
  2928.     /*
  2929.      *    Charge the sock_buff to newsk. 
  2930.      */
  2931.      
  2932.     sk->rmem_alloc -= skb->mem_len;
  2933.     newsk->rmem_alloc += skb->mem_len;
  2934.     
  2935.     skb_queue_tail(&sk->receive_queue,skb);
  2936.     sk->ack_backlog++;
  2937.     release_sock(newsk);
  2938.     tcp_statistics.TcpOutSegs++;
  2939. }
  2940.  
  2941.  
  2942. static void tcp_close(struct sock *sk, int timeout)
  2943. {
  2944.     /*
  2945.      * We need to grab some memory, and put together a FIN,    
  2946.      * and then put it into the queue to be sent.
  2947.      */
  2948.     
  2949.     sk->inuse = 1;
  2950.     
  2951.     if(sk->state == TCP_LISTEN)
  2952.     {
  2953.         /* Special case */
  2954.         tcp_set_state(sk, TCP_CLOSE);
  2955.         tcp_close_pending(sk);
  2956.         release_sock(sk);
  2957.         return;
  2958.     }
  2959.     
  2960.     sk->keepopen = 1;
  2961.     sk->shutdown = SHUTDOWN_MASK;
  2962.  
  2963.     if (!sk->dead) 
  2964.           sk->state_change(sk);
  2965.  
  2966.     if (timeout == 0) 
  2967.     {
  2968.         struct sk_buff *skb;
  2969.         
  2970.         /*
  2971.          *  We need to flush the recv. buffs.  We do this only on the
  2972.          *  descriptor close, not protocol-sourced closes, because the
  2973.          *  reader process may not have drained the data yet!
  2974.          */
  2975.          
  2976.         while((skb=skb_dequeue(&sk->receive_queue))!=NULL)
  2977.             kfree_skb(skb, FREE_READ);
  2978.         /*
  2979.          *    Get rid off any half-completed packets. 
  2980.          */
  2981.  
  2982.         if (sk->partial) 
  2983.             tcp_send_partial(sk);
  2984.     }
  2985.  
  2986.         
  2987.     /*
  2988.      *    Timeout is not the same thing - however the code likes
  2989.      *    to send both the same way (sigh).
  2990.      */
  2991.      
  2992.     if(timeout)
  2993.     {
  2994.         tcp_set_state(sk, TCP_CLOSE);    /* Dead */
  2995.     }
  2996.     else
  2997.     {
  2998.         if(tcp_close_state(sk,1)==1)
  2999.         {
  3000.             tcp_send_fin(sk);
  3001.         }
  3002.     }
  3003.     release_sock(sk);
  3004. }
  3005.  
  3006.  
  3007. /*
  3008.  *     This routine takes stuff off of the write queue,
  3009.  *    and puts it in the xmit queue. This happens as incoming acks
  3010.  *    open up the remote window for us.
  3011.  */
  3012.  
  3013. static void tcp_write_xmit(struct sock *sk)
  3014. {
  3015.     struct sk_buff *skb;
  3016.  
  3017.     /*
  3018.      *    The bytes will have to remain here. In time closedown will
  3019.      *    empty the write queue and all will be happy 
  3020.      */
  3021.  
  3022.     if(sk->zapped)
  3023.         return;
  3024.  
  3025.     /*
  3026.      *    Anything on the transmit queue that fits the window can
  3027.      *    be added providing we are not
  3028.      *
  3029.      *    a) retransmitting (Nagle's rule)
  3030.      *    b) exceeding our congestion window.
  3031.      */
  3032.      
  3033.     while((skb = skb_peek(&sk->write_queue)) != NULL &&
  3034.         before(skb->h.seq, sk->window_seq + 1) &&
  3035.         (sk->retransmits == 0 ||
  3036.          sk->ip_xmit_timeout != TIME_WRITE ||
  3037.          before(skb->h.seq, sk->rcv_ack_seq + 1))
  3038.         && sk->packets_out < sk->cong_window) 
  3039.     {
  3040.         IS_SKB(skb);
  3041.         skb_unlink(skb);
  3042.         
  3043.         /*
  3044.          *    See if we really need to send the packet. 
  3045.          */
  3046.          
  3047.         if (before(skb->h.seq, sk->rcv_ack_seq +1)) 
  3048.         {
  3049.             /*
  3050.              *    This is acked data. We can discard it. This 
  3051.              *    cannot currently occur.
  3052.              */
  3053.              
  3054.             sk->retransmits = 0;
  3055.             kfree_skb(skb, FREE_WRITE);
  3056.             if (!sk->dead) 
  3057.                 sk->write_space(sk);
  3058.         } 
  3059.         else
  3060.         {
  3061.             struct tcphdr *th;
  3062.             struct iphdr *iph;
  3063.             int size;
  3064. /*
  3065.  * put in the ack seq and window at this point rather than earlier,
  3066.  * in order to keep them monotonic.  We really want to avoid taking
  3067.  * back window allocations.  That's legal, but RFC1122 says it's frowned on.
  3068.  * Ack and window will in general have changed since this packet was put
  3069.  * on the write queue.
  3070.  */
  3071.             iph = (struct iphdr *)(skb->data +
  3072.                            skb->dev->hard_header_len);
  3073.             th = (struct tcphdr *)(((char *)iph) +(iph->ihl << 2));
  3074.             size = skb->len - (((unsigned char *) th) - skb->data);
  3075.             
  3076.             th->ack_seq = ntohl(sk->acked_seq);
  3077.             th->window = ntohs(tcp_select_window(sk));
  3078.  
  3079.             tcp_send_check(th, sk->saddr, sk->daddr, size, sk);
  3080.  
  3081.             sk->sent_seq = skb->h.seq;
  3082.             
  3083.             /*
  3084.              *    IP manages our queue for some crazy reason
  3085.              */
  3086.              
  3087.             sk->prot->queue_xmit(sk, skb->dev, skb, skb->free);
  3088.             
  3089.             /*
  3090.              *    Again we slide the timer wrongly
  3091.              */
  3092.              
  3093.             reset_xmit_timer(sk, TIME_WRITE, sk->rto);
  3094.         }
  3095.     }
  3096. }
  3097.  
  3098.  
  3099. /*
  3100.  *    This routine deals with incoming acks, but not outgoing ones.
  3101.  */
  3102.  
  3103. extern __inline__ int tcp_ack(struct sock *sk, struct tcphdr *th, unsigned long saddr, int len)
  3104. {
  3105.     unsigned long ack;
  3106.     int flag = 0;
  3107.  
  3108.     /* 
  3109.      * 1 - there was data in packet as well as ack or new data is sent or 
  3110.      *     in shutdown state
  3111.      * 2 - data from retransmit queue was acked and removed
  3112.      * 4 - window shrunk or data from retransmit queue was acked and removed
  3113.      */
  3114.  
  3115.     if(sk->zapped)
  3116.         return(1);    /* Dead, cant ack any more so why bother */
  3117.  
  3118.     /*
  3119.      *    Have we discovered a larger window
  3120.      */
  3121.      
  3122.     ack = ntohl(th->ack_seq);
  3123.  
  3124.     if (ntohs(th->window) > sk->max_window) 
  3125.     {
  3126.           sk->max_window = ntohs(th->window);
  3127. #ifdef CONFIG_INET_PCTCP
  3128.         /* Hack because we don't send partial packets to non SWS
  3129.            handling hosts */
  3130.         sk->mss = min(sk->max_window>>1, sk->mtu);
  3131. #else
  3132.         sk->mss = min(sk->max_window, sk->mtu);
  3133. #endif    
  3134.     }
  3135.  
  3136.     /*
  3137.      *    We have dropped back to keepalive timeouts. Thus we have
  3138.      *    no retransmits pending.
  3139.      */
  3140.      
  3141.     if (sk->retransmits && sk->ip_xmit_timeout == TIME_KEEPOPEN)
  3142.           sk->retransmits = 0;
  3143.  
  3144.     /*
  3145.      *    If the ack is newer than sent or older than previous acks
  3146.      *    then we can probably ignore it.
  3147.      */
  3148.      
  3149.     if (after(ack, sk->sent_seq) || before(ack, sk->rcv_ack_seq)) 
  3150.     {
  3151.         if(sk->debug)
  3152.             printk("Ack ignored %lu %lu\n",ack,sk->sent_seq);
  3153.             
  3154.         /*
  3155.          *    Keepalive processing.
  3156.          */
  3157.          
  3158.         if (after(ack, sk->sent_seq)) 
  3159.         {
  3160.             return(0);
  3161.         }
  3162.         
  3163.         /*
  3164.          *    Restart the keepalive timer.
  3165.          */
  3166.          
  3167.         if (sk->keepopen) 
  3168.         {
  3169.             if(sk->ip_xmit_timeout==TIME_KEEPOPEN)
  3170.                 reset_xmit_timer(sk, TIME_KEEPOPEN, TCP_TIMEOUT_LEN);
  3171.         }
  3172.         return(1);
  3173.     }
  3174.  
  3175.     /*
  3176.      *    If there is data set flag 1
  3177.      */
  3178.      
  3179.     if (len != th->doff*4) 
  3180.         flag |= 1;
  3181.  
  3182.     /*
  3183.      *    See if our window has been shrunk. 
  3184.      */
  3185.  
  3186.     if (after(sk->window_seq, ack+ntohs(th->window))) 
  3187.     {
  3188.         /*
  3189.          * We may need to move packets from the send queue
  3190.          * to the write queue, if the window has been shrunk on us.
  3191.          * The RFC says you are not allowed to shrink your window
  3192.          * like this, but if the other end does, you must be able
  3193.          * to deal with it.
  3194.          */
  3195.         struct sk_buff *skb;
  3196.         struct sk_buff *skb2;
  3197.         struct sk_buff *wskb = NULL;
  3198.       
  3199.         skb2 = sk->send_head;
  3200.         sk->send_head = NULL;
  3201.         sk->send_tail = NULL;
  3202.     
  3203.         /*
  3204.          *    This is an artifact of a flawed concept. We want one
  3205.          *    queue and a smarter send routine when we send all.
  3206.          */
  3207.     
  3208.         flag |= 4;    /* Window changed */
  3209.     
  3210.         sk->window_seq = ack + ntohs(th->window);
  3211.         cli();
  3212.         while (skb2 != NULL) 
  3213.         {
  3214.             skb = skb2;
  3215.             skb2 = skb->link3;
  3216.             skb->link3 = NULL;
  3217.             if (after(skb->h.seq, sk->window_seq)) 
  3218.             {
  3219.                 if (sk->packets_out > 0) 
  3220.                     sk->packets_out--;
  3221.                 /* We may need to remove this from the dev send list. */
  3222.                 if (skb->next != NULL) 
  3223.                 {
  3224.                     skb_unlink(skb);                
  3225.                 }
  3226.                 /* Now add it to the write_queue. */
  3227.                 if (wskb == NULL)
  3228.                     skb_queue_head(&sk->write_queue,skb);
  3229.                 else
  3230.                     skb_append(wskb,skb);
  3231.                 wskb = skb;
  3232.             } 
  3233.             else 
  3234.             {
  3235.                 if (sk->send_head == NULL) 
  3236.                 {
  3237.                     sk->send_head = skb;
  3238.                     sk->send_tail = skb;
  3239.                 }
  3240.                 else
  3241.                 {
  3242.                     sk->send_tail->link3 = skb;
  3243.                     sk->send_tail = skb;
  3244.                 }
  3245.                 skb->link3 = NULL;
  3246.             }
  3247.         }
  3248.         sti();
  3249.     }
  3250.  
  3251.     /*
  3252.      *    Pipe has emptied
  3253.      */
  3254.      
  3255.     if (sk->send_tail == NULL || sk->send_head == NULL) 
  3256.     {
  3257.         sk->send_head = NULL;
  3258.         sk->send_tail = NULL;
  3259.         sk->packets_out= 0;
  3260.     }
  3261.  
  3262.     /*
  3263.      *    Update the right hand window edge of the host
  3264.      */
  3265.      
  3266.     sk->window_seq = ack + ntohs(th->window);
  3267.  
  3268.     /*
  3269.      *    We don't want too many packets out there. 
  3270.      */
  3271.      
  3272.     if (sk->ip_xmit_timeout == TIME_WRITE && 
  3273.         sk->cong_window < 2048 && after(ack, sk->rcv_ack_seq)) 
  3274.     {
  3275.         /* 
  3276.          * This is Jacobson's slow start and congestion avoidance. 
  3277.          * SIGCOMM '88, p. 328.  Because we keep cong_window in integral
  3278.          * mss's, we can't do cwnd += 1 / cwnd.  Instead, maintain a 
  3279.          * counter and increment it once every cwnd times.  It's possible
  3280.          * that this should be done only if sk->retransmits == 0.  I'm
  3281.          * interpreting "new data is acked" as including data that has
  3282.          * been retransmitted but is just now being acked.
  3283.          */
  3284.         if (sk->cong_window < sk->ssthresh)  
  3285.             /* 
  3286.              *    In "safe" area, increase
  3287.              */
  3288.             sk->cong_window++;
  3289.         else 
  3290.         {
  3291.             /*
  3292.              *    In dangerous area, increase slowly.  In theory this is
  3293.              *      sk->cong_window += 1 / sk->cong_window
  3294.              */
  3295.             if (sk->cong_count >= sk->cong_window) 
  3296.             {
  3297.                 sk->cong_window++;
  3298.                 sk->cong_count = 0;
  3299.             }
  3300.             else 
  3301.                 sk->cong_count++;
  3302.         }
  3303.     }
  3304.  
  3305.     /*
  3306.      *    Remember the highest ack received.
  3307.      */
  3308.      
  3309.     sk->rcv_ack_seq = ack;
  3310.  
  3311.     /*
  3312.      *    If this ack opens up a zero window, clear backoff.  It was
  3313.      *    being used to time the probes, and is probably far higher than
  3314.      *    it needs to be for normal retransmission.
  3315.      */
  3316.  
  3317.     if (sk->ip_xmit_timeout == TIME_PROBE0) 
  3318.     {
  3319.         sk->retransmits = 0;    /* Our probe was answered */
  3320.         
  3321.         /*
  3322.          *    Was it a usable window open ?
  3323.          */
  3324.          
  3325.           if (skb_peek(&sk->write_queue) != NULL &&   /* should always be non-null */
  3326.             ! before (sk->window_seq, sk->write_queue.next->h.seq)) 
  3327.         {
  3328.             sk->backoff = 0;
  3329.             
  3330.             /*
  3331.              *    Recompute rto from rtt.  this eliminates any backoff.
  3332.              */
  3333.  
  3334.             sk->rto = ((sk->rtt >> 2) + sk->mdev) >> 1;
  3335.             if (sk->rto > 120*HZ)
  3336.                 sk->rto = 120*HZ;
  3337.             if (sk->rto < 20)    /* Was 1*HZ, then 1 - turns out we must allow about
  3338.                            .2 of a second because of BSD delayed acks - on a 100Mb/sec link
  3339.                            .2 of a second is going to need huge windows (SIGH) */
  3340.             sk->rto = 20;
  3341.         }
  3342.     }
  3343.  
  3344.     /* 
  3345.      *    See if we can take anything off of the retransmit queue.
  3346.      */
  3347.    
  3348.     while(sk->send_head != NULL) 
  3349.     {
  3350.         /* Check for a bug. */
  3351.         if (sk->send_head->link3 &&
  3352.             after(sk->send_head->h.seq, sk->send_head->link3->h.seq)) 
  3353.             printk("INET: tcp.c: *** bug send_list out of order.\n");
  3354.             
  3355.         /*
  3356.          *    If our packet is before the ack sequence we can
  3357.          *    discard it as it's confirmed to have arrived the other end.
  3358.          */
  3359.          
  3360.         if (before(sk->send_head->h.seq, ack+1)) 
  3361.         {
  3362.             struct sk_buff *oskb;    
  3363.             if (sk->retransmits) 
  3364.             {    
  3365.                 /*
  3366.                  *    We were retransmitting.  don't count this in RTT est 
  3367.                  */
  3368.                 flag |= 2;
  3369.  
  3370.                 /*
  3371.                  * even though we've gotten an ack, we're still
  3372.                  * retransmitting as long as we're sending from
  3373.                  * the retransmit queue.  Keeping retransmits non-zero
  3374.                  * prevents us from getting new data interspersed with
  3375.                  * retransmissions.
  3376.                  */
  3377.  
  3378.                 if (sk->send_head->link3)    /* Any more queued retransmits? */
  3379.                     sk->retransmits = 1;
  3380.                 else
  3381.                     sk->retransmits = 0;
  3382.             }
  3383.               /*
  3384.              * Note that we only reset backoff and rto in the
  3385.              * rtt recomputation code.  And that doesn't happen
  3386.              * if there were retransmissions in effect.  So the
  3387.              * first new packet after the retransmissions is
  3388.              * sent with the backoff still in effect.  Not until
  3389.              * we get an ack from a non-retransmitted packet do
  3390.              * we reset the backoff and rto.  This allows us to deal
  3391.              * with a situation where the network delay has increased
  3392.              * suddenly.  I.e. Karn's algorithm. (SIGCOMM '87, p5.)
  3393.              */
  3394.  
  3395.             /*
  3396.              *    We have one less packet out there. 
  3397.              */
  3398.              
  3399.             if (sk->packets_out > 0) 
  3400.                 sk->packets_out --;
  3401.             /* 
  3402.              *    Wake up the process, it can probably write more. 
  3403.              */
  3404.             if (!sk->dead) 
  3405.                 sk->write_space(sk);
  3406.             oskb = sk->send_head;
  3407.  
  3408.             if (!(flag&2))     /* Not retransmitting */
  3409.             {
  3410.                 long m;
  3411.     
  3412.                 /*
  3413.                  *    The following amusing code comes from Jacobson's
  3414.                  *    article in SIGCOMM '88.  Note that rtt and mdev
  3415.                  *    are scaled versions of rtt and mean deviation.
  3416.                  *    This is designed to be as fast as possible 
  3417.                  *    m stands for "measurement".
  3418.                  */
  3419.     
  3420.                 m = jiffies - oskb->when;  /* RTT */
  3421.                 if(m<=0)
  3422.                     m=1;        /* IS THIS RIGHT FOR <0 ??? */
  3423.                 m -= (sk->rtt >> 3);    /* m is now error in rtt est */
  3424.                 sk->rtt += m;           /* rtt = 7/8 rtt + 1/8 new */
  3425.                 if (m < 0)
  3426.                     m = -m;        /* m is now abs(error) */
  3427.                 m -= (sk->mdev >> 2);   /* similar update on mdev */
  3428.                 sk->mdev += m;            /* mdev = 3/4 mdev + 1/4 new */
  3429.     
  3430.                 /*
  3431.                  *    Now update timeout.  Note that this removes any backoff.
  3432.                  */
  3433.              
  3434.                 sk->rto = ((sk->rtt >> 2) + sk->mdev) >> 1;
  3435.                 if (sk->rto > 120*HZ)
  3436.                     sk->rto = 120*HZ;
  3437.                 if (sk->rto < 20)    /* Was 1*HZ - keep .2 as minimum cos of the BSD delayed acks */
  3438.                     sk->rto = 20;
  3439.                 sk->backoff = 0;
  3440.             }
  3441.             flag |= (2|4);    /* 2 is really more like 'don't adjust the rtt 
  3442.                                In this case as we just set it up */
  3443.             cli();
  3444.             oskb = sk->send_head;
  3445.             IS_SKB(oskb);
  3446.             sk->send_head = oskb->link3;
  3447.             if (sk->send_head == NULL) 
  3448.             {
  3449.                 sk->send_tail = NULL;
  3450.             }
  3451.  
  3452.         /*
  3453.          *    We may need to remove this from the dev send list. 
  3454.          */
  3455.  
  3456.             if (oskb->next)
  3457.                 skb_unlink(oskb);
  3458.             sti();
  3459.             kfree_skb(oskb, FREE_WRITE); /* write. */
  3460.             if (!sk->dead) 
  3461.                 sk->write_space(sk);
  3462.         }
  3463.         else
  3464.         {
  3465.             break;
  3466.         }
  3467.     }
  3468.  
  3469.     /*
  3470.      * XXX someone ought to look at this too.. at the moment, if skb_peek()
  3471.      * returns non-NULL, we complete ignore the timer stuff in the else
  3472.      * clause.  We ought to organize the code so that else clause can
  3473.      * (should) be executed regardless, possibly moving the PROBE timer
  3474.      * reset over.  The skb_peek() thing should only move stuff to the
  3475.      * write queue, NOT also manage the timer functions.
  3476.      */
  3477.  
  3478.     /*
  3479.      * Maybe we can take some stuff off of the write queue,
  3480.      * and put it onto the xmit queue.
  3481.      */
  3482.     if (skb_peek(&sk->write_queue) != NULL) 
  3483.     {
  3484.         if (after (sk->window_seq+1, sk->write_queue.next->h.seq) &&
  3485.                 (sk->retransmits == 0 || 
  3486.              sk->ip_xmit_timeout != TIME_WRITE ||
  3487.              before(sk->write_queue.next->h.seq, sk->rcv_ack_seq + 1))
  3488.             && sk->packets_out < sk->cong_window) 
  3489.         {
  3490.             /*
  3491.              *    Add more data to the send queue.
  3492.              */
  3493.             flag |= 1;
  3494.             tcp_write_xmit(sk);
  3495.         }
  3496.         else if (before(sk->window_seq, sk->write_queue.next->h.seq) &&
  3497.              sk->send_head == NULL &&
  3498.              sk->ack_backlog == 0 &&
  3499.              sk->state != TCP_TIME_WAIT) 
  3500.          {
  3501.              /*
  3502.               *    Data to queue but no room.
  3503.               */
  3504.                  reset_xmit_timer(sk, TIME_PROBE0, sk->rto);
  3505.          }        
  3506.     }
  3507.     else
  3508.     {
  3509.         /*
  3510.          * from TIME_WAIT we stay in TIME_WAIT as long as we rx packets
  3511.          * from TCP_CLOSE we don't do anything
  3512.          *
  3513.          * from anything else, if there is write data (or fin) pending,
  3514.          * we use a TIME_WRITE timeout, else if keepalive we reset to
  3515.          * a KEEPALIVE timeout, else we delete the timer.
  3516.          *
  3517.          * We do not set flag for nominal write data, otherwise we may
  3518.          * force a state where we start to write itsy bitsy tidbits
  3519.          * of data.
  3520.          */
  3521.  
  3522.         switch(sk->state) {
  3523.         case TCP_TIME_WAIT:
  3524.             /*
  3525.              * keep us in TIME_WAIT until we stop getting packets,
  3526.              * reset the timeout.
  3527.              */
  3528.             reset_msl_timer(sk, TIME_CLOSE, TCP_TIMEWAIT_LEN);
  3529.             break;
  3530.         case TCP_CLOSE:
  3531.             /*
  3532.              * don't touch the timer.
  3533.              */
  3534.             break;
  3535.         default:
  3536.             /*
  3537.              *     Must check send_head, write_queue, and ack_backlog
  3538.              *     to determine which timeout to use.
  3539.              */
  3540.             if (sk->send_head || skb_peek(&sk->write_queue) != NULL || sk->ack_backlog) {
  3541.                 reset_xmit_timer(sk, TIME_WRITE, sk->rto);
  3542.             } else if (sk->keepopen) {
  3543.                 reset_xmit_timer(sk, TIME_KEEPOPEN, TCP_TIMEOUT_LEN);
  3544.             } else {
  3545.                 del_timer(&sk->retransmit_timer);
  3546.                 sk->ip_xmit_timeout = 0;
  3547.             }
  3548.             break;
  3549.         }
  3550.     }
  3551.  
  3552.     /*
  3553.      *    We have nothing queued but space to send. Send any partial
  3554.      *    packets immediately (end of Nagle rule application).
  3555.      */
  3556.      
  3557.     if (sk->packets_out == 0 && sk->partial != NULL &&
  3558.         skb_peek(&sk->write_queue) == NULL && sk->send_head == NULL) 
  3559.     {
  3560.         flag |= 1;
  3561.         tcp_send_partial(sk);
  3562.     }
  3563.  
  3564.     /*
  3565.      * In the LAST_ACK case, the other end FIN'd us.  We then FIN'd them, and
  3566.      * we are now waiting for an acknowledge to our FIN.  The other end is
  3567.      * already in TIME_WAIT.
  3568.      *
  3569.      * Move to TCP_CLOSE on success.
  3570.      */
  3571.  
  3572.     if (sk->state == TCP_LAST_ACK) 
  3573.     {
  3574.         if (!sk->dead)
  3575.             sk->state_change(sk);
  3576.         if(sk->debug)
  3577.             printk("rcv_ack_seq: %lX==%lX, acked_seq: %lX==%lX\n",
  3578.                 sk->rcv_ack_seq,sk->write_seq,sk->acked_seq,sk->fin_seq);
  3579.         if (sk->rcv_ack_seq == sk->write_seq /*&& sk->acked_seq == sk->fin_seq*/) 
  3580.         {
  3581.             flag |= 1;
  3582.             tcp_set_state(sk,TCP_CLOSE);
  3583.             sk->shutdown = SHUTDOWN_MASK;
  3584.         }
  3585.     }
  3586.  
  3587.     /*
  3588.      *    Incoming ACK to a FIN we sent in the case of our initiating the close.
  3589.      *
  3590.      *    Move to FIN_WAIT2 to await a FIN from the other end. Set
  3591.      *    SEND_SHUTDOWN but not RCV_SHUTDOWN as data can still be coming in.
  3592.      */
  3593.  
  3594.     if (sk->state == TCP_FIN_WAIT1) 
  3595.     {
  3596.  
  3597.         if (!sk->dead) 
  3598.             sk->state_change(sk);
  3599.         if (sk->rcv_ack_seq == sk->write_seq) 
  3600.         {
  3601.             flag |= 1;
  3602.             sk->shutdown |= SEND_SHUTDOWN;
  3603.             tcp_set_state(sk, TCP_FIN_WAIT2);
  3604.         }
  3605.     }
  3606.  
  3607.     /*
  3608.      *    Incoming ACK to a FIN we sent in the case of a simultaneous close.
  3609.      *
  3610.      *    Move to TIME_WAIT
  3611.      */
  3612.  
  3613.     if (sk->state == TCP_CLOSING) 
  3614.     {
  3615.  
  3616.         if (!sk->dead) 
  3617.             sk->state_change(sk);
  3618.         if (sk->rcv_ack_seq == sk->write_seq) 
  3619.         {
  3620.             flag |= 1;
  3621.             tcp_time_wait(sk);
  3622.         }
  3623.     }
  3624.     
  3625.     /*
  3626.      *    Final ack of a three way shake 
  3627.      */
  3628.      
  3629.     if(sk->state==TCP_SYN_RECV)
  3630.     {
  3631.         tcp_set_state(sk, TCP_ESTABLISHED);
  3632.         tcp_options(sk,th);
  3633.         sk->dummy_th.dest=th->source;
  3634.         sk->copied_seq = sk->acked_seq;
  3635.         if(!sk->dead)
  3636.             sk->state_change(sk);
  3637.         if(sk->max_window==0)
  3638.         {
  3639.             sk->max_window=32;    /* Sanity check */
  3640.             sk->mss=min(sk->max_window,sk->mtu);
  3641.         }
  3642.     }
  3643.     
  3644.     /*
  3645.      * I make no guarantees about the first clause in the following
  3646.      * test, i.e. "(!flag) || (flag&4)".  I'm not entirely sure under
  3647.      * what conditions "!flag" would be true.  However I think the rest
  3648.      * of the conditions would prevent that from causing any
  3649.      * unnecessary retransmission. 
  3650.      *   Clearly if the first packet has expired it should be 
  3651.      * retransmitted.  The other alternative, "flag&2 && retransmits", is
  3652.      * harder to explain:  You have to look carefully at how and when the
  3653.      * timer is set and with what timeout.  The most recent transmission always
  3654.      * sets the timer.  So in general if the most recent thing has timed
  3655.      * out, everything before it has as well.  So we want to go ahead and
  3656.      * retransmit some more.  If we didn't explicitly test for this
  3657.      * condition with "flag&2 && retransmits", chances are "when + rto < jiffies"
  3658.      * would not be true.  If you look at the pattern of timing, you can
  3659.      * show that rto is increased fast enough that the next packet would
  3660.      * almost never be retransmitted immediately.  Then you'd end up
  3661.      * waiting for a timeout to send each packet on the retransmission
  3662.      * queue.  With my implementation of the Karn sampling algorithm,
  3663.      * the timeout would double each time.  The net result is that it would
  3664.      * take a hideous amount of time to recover from a single dropped packet.
  3665.      * It's possible that there should also be a test for TIME_WRITE, but
  3666.      * I think as long as "send_head != NULL" and "retransmit" is on, we've
  3667.      * got to be in real retransmission mode.
  3668.      *   Note that tcp_do_retransmit is called with all==1.  Setting cong_window
  3669.      * back to 1 at the timeout will cause us to send 1, then 2, etc. packets.
  3670.      * As long as no further losses occur, this seems reasonable.
  3671.      */
  3672.     
  3673.     if (((!flag) || (flag&4)) && sk->send_head != NULL &&
  3674.            (((flag&2) && sk->retransmits) ||
  3675.            (sk->send_head->when + sk->rto < jiffies))) 
  3676.     {
  3677.         if(sk->send_head->when + sk->rto < jiffies)
  3678.             tcp_retransmit(sk,0);    
  3679.         else
  3680.         {
  3681.             tcp_do_retransmit(sk, 1);
  3682.             reset_xmit_timer(sk, TIME_WRITE, sk->rto);
  3683.         }
  3684.     }
  3685.  
  3686.     return(1);
  3687. }
  3688.  
  3689.  
  3690. /*
  3691.  *     Process the FIN bit. This now behaves as it is supposed to work
  3692.  *    and the FIN takes effect when it is validly part of sequence
  3693.  *    space. Not before when we get holes.
  3694.  *
  3695.  *    If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
  3696.  *    (and thence onto LAST-ACK and finally, CLOSE, we never enter
  3697.  *    TIME-WAIT)
  3698.  *
  3699.  *    If we are in FINWAIT-1, a received FIN indicates simultaneous
  3700.  *    close and we go into CLOSING (and later onto TIME-WAIT)
  3701.  *
  3702.  *    If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
  3703.  *
  3704.  */
  3705.  
  3706. static int tcp_fin(struct sk_buff *skb, struct sock *sk, struct tcphdr *th)
  3707. {
  3708.     sk->fin_seq = th->seq + skb->len + th->syn + th->fin;
  3709.  
  3710.     if (!sk->dead) 
  3711.     {
  3712.         sk->state_change(sk);
  3713.         sock_wake_async(sk->socket, 1);
  3714.     }
  3715.  
  3716.     switch(sk->state) 
  3717.     {
  3718.         case TCP_SYN_RECV:
  3719.         case TCP_SYN_SENT:
  3720.         case TCP_ESTABLISHED:
  3721.             /*
  3722.              * move to CLOSE_WAIT, tcp_data() already handled
  3723.              * sending the ack.
  3724.              */
  3725.             tcp_set_state(sk,TCP_CLOSE_WAIT);
  3726.             if (th->rst)
  3727.                 sk->shutdown = SHUTDOWN_MASK;
  3728.             break;
  3729.  
  3730.         case TCP_CLOSE_WAIT:
  3731.         case TCP_CLOSING:
  3732.             /*
  3733.              * received a retransmission of the FIN, do
  3734.              * nothing.
  3735.              */
  3736.             break;
  3737.         case TCP_TIME_WAIT:
  3738.             /*
  3739.              * received a retransmission of the FIN,
  3740.              * restart the TIME_WAIT timer.
  3741.              */
  3742.             reset_msl_timer(sk, TIME_CLOSE, TCP_TIMEWAIT_LEN);
  3743.             return(0);
  3744.         case TCP_FIN_WAIT1:
  3745.             /*
  3746.              * This case occurs when a simultaneous close
  3747.              * happens, we must ack the received FIN and
  3748.              * enter the CLOSING state.
  3749.              *
  3750.              * This causes a WRITE timeout, which will either
  3751.              * move on to TIME_WAIT when we timeout, or resend
  3752.              * the FIN properly (maybe we get rid of that annoying
  3753.              * FIN lost hang). The TIME_WRITE code is already correct
  3754.              * for handling this timeout.
  3755.              */
  3756.  
  3757.             if(sk->ip_xmit_timeout != TIME_WRITE)
  3758.                 reset_xmit_timer(sk, TIME_WRITE, sk->rto);
  3759.             tcp_set_state(sk,TCP_CLOSING);
  3760.             break;
  3761.         case TCP_FIN_WAIT2:
  3762.             /*
  3763.              * received a FIN -- send ACK and enter TIME_WAIT
  3764.              */
  3765.             reset_msl_timer(sk, TIME_CLOSE, TCP_TIMEWAIT_LEN);
  3766.             sk->shutdown|=SHUTDOWN_MASK;
  3767.             tcp_set_state(sk,TCP_TIME_WAIT);
  3768.             break;
  3769.         case TCP_CLOSE:
  3770.             /*
  3771.              * already in CLOSE
  3772.              */
  3773.             break;
  3774.         default:
  3775.             tcp_set_state(sk,TCP_LAST_ACK);
  3776.     
  3777.             /* Start the timers. */
  3778.             reset_msl_timer(sk, TIME_CLOSE, TCP_TIMEWAIT_LEN);
  3779.             return(0);
  3780.     }
  3781.  
  3782.     return(0);
  3783. }
  3784.  
  3785.  
  3786.  
  3787. /*
  3788.  *    This routine handles the data.  If there is room in the buffer,
  3789.  *    it will be have already been moved into it.  If there is no
  3790.  *    room, then we will just have to discard the packet.
  3791.  */
  3792.  
  3793. extern __inline__ int tcp_data(struct sk_buff *skb, struct sock *sk, 
  3794.      unsigned long saddr, unsigned short len)
  3795. {
  3796.     struct sk_buff *skb1, *skb2;
  3797.     struct tcphdr *th;
  3798.     int dup_dumped=0;
  3799.     unsigned long new_seq;
  3800.     unsigned long shut_seq;
  3801.  
  3802.     th = skb->h.th;
  3803.     skb->len = len -(th->doff*4);
  3804.  
  3805.     /*
  3806.      *    The bytes in the receive read/assembly queue has increased. Needed for the
  3807.      *    low memory discard algorithm 
  3808.      */
  3809.        
  3810.     sk->bytes_rcv += skb->len;
  3811.     
  3812.     if (skb->len == 0 && !th->fin && !th->urg && !th->psh) 
  3813.     {
  3814.         /* 
  3815.          *    Don't want to keep passing ack's back and forth. 
  3816.          *    (someone sent us dataless, boring frame)
  3817.          */
  3818.         if (!th->ack)
  3819.             tcp_send_ack(sk->sent_seq, sk->acked_seq,sk, th, saddr);
  3820.         kfree_skb(skb, FREE_READ);
  3821.         return(0);
  3822.     }
  3823.     
  3824.     /*
  3825.      *    We no longer have anyone receiving data on this connection.
  3826.      */
  3827.  
  3828. #ifndef TCP_DONT_RST_SHUTDOWN         
  3829.  
  3830.     if(sk->shutdown & RCV_SHUTDOWN)
  3831.     {
  3832.         /*
  3833.          *    FIXME: BSD has some magic to avoid sending resets to
  3834.          *    broken 4.2 BSD keepalives. Much to my surprise a few non
  3835.          *    BSD stacks still have broken keepalives so we want to
  3836.          *    cope with it.
  3837.          */
  3838.  
  3839.         if(skb->len)    /* We don't care if it's just an ack or
  3840.                    a keepalive/window probe */
  3841.         {
  3842.             new_seq= th->seq + skb->len + th->syn;    /* Right edge of _data_ part of frame */
  3843.             
  3844.             /* Do this the way 4.4BSD treats it. Not what I'd
  3845.                regard as the meaning of the spec but it's what BSD
  3846.                does and clearly they know everything 8) */
  3847.  
  3848.             /*
  3849.              *    This is valid because of two things
  3850.              *
  3851.              *    a) The way tcp_data behaves at the bottom.
  3852.              *    b) A fin takes effect when read not when received.
  3853.              */
  3854.              
  3855.             shut_seq=sk->acked_seq+1;    /* Last byte */
  3856.             
  3857.             if(after(new_seq,shut_seq))
  3858.             {
  3859.                 if(sk->debug)
  3860.                     printk("Data arrived on %p after close [Data right edge %lX, Socket shut on %lX] %d\n",
  3861.                         sk, new_seq, shut_seq, sk->blog);
  3862.                 if(sk->dead)
  3863.                 {
  3864.                     sk->acked_seq = new_seq + th->fin;
  3865.                     tcp_reset(sk->saddr, sk->daddr, skb->h.th,
  3866.                         sk->prot, NULL, skb->dev, sk->ip_tos, sk->ip_ttl);
  3867.                     tcp_statistics.TcpEstabResets++;
  3868.                     tcp_set_state(sk,TCP_CLOSE);
  3869.                     sk->err = EPIPE;
  3870.                     sk->shutdown = SHUTDOWN_MASK;
  3871.                     kfree_skb(skb, FREE_READ);
  3872.                     return 0;
  3873.                 }
  3874.             }
  3875.         }
  3876.     }
  3877.  
  3878. #endif
  3879.  
  3880.     /*
  3881.      *     Now we have to walk the chain, and figure out where this one
  3882.      *     goes into it.  This is set up so that the last packet we received
  3883.      *     will be the first one we look at, that way if everything comes
  3884.      *     in order, there will be no performance loss, and if they come
  3885.      *     out of order we will be able to fit things in nicely.
  3886.      *
  3887.      *    [AC: This is wrong. We should assume in order first and then walk
  3888.      *     forwards from the first hole based upon real traffic patterns.]
  3889.      *    
  3890.      */
  3891.  
  3892.     if (skb_peek(&sk->receive_queue) == NULL)     /* Empty queue is easy case */
  3893.     {
  3894.         skb_queue_head(&sk->receive_queue,skb);
  3895.         skb1= NULL;
  3896.     } 
  3897.     else
  3898.     {
  3899.         for(skb1=sk->receive_queue.prev; ; skb1 = skb1->prev) 
  3900.         {
  3901.             if(sk->debug)
  3902.             {
  3903.                 printk("skb1=%p :", skb1);
  3904.                 printk("skb1->h.th->seq = %ld: ", skb1->h.th->seq);
  3905.                 printk("skb->h.th->seq = %ld\n",skb->h.th->seq);
  3906.                 printk("copied_seq = %ld acked_seq = %ld\n", sk->copied_seq,
  3907.                         sk->acked_seq);
  3908.             }
  3909.             
  3910.             /*
  3911.              *    Optimisation: Duplicate frame or extension of previous frame from
  3912.              *    same sequence point (lost ack case).
  3913.              *    The frame contains duplicate data or replaces a previous frame
  3914.              *    discard the previous frame (safe as sk->inuse is set) and put
  3915.              *    the new one in its place.
  3916.              */
  3917.              
  3918.             if (th->seq==skb1->h.th->seq && skb->len>= skb1->len)
  3919.             {
  3920.                 skb_append(skb1,skb);
  3921.                 skb_unlink(skb1);
  3922.                 kfree_skb(skb1,FREE_READ);
  3923.                 dup_dumped=1;
  3924.                 skb1=NULL;
  3925.                 break;
  3926.             }
  3927.             
  3928.             /*
  3929.              *    Found where it fits
  3930.              */
  3931.              
  3932.             if (after(th->seq+1, skb1->h.th->seq))
  3933.             {
  3934.                 skb_append(skb1,skb);
  3935.                 break;
  3936.             }
  3937.             
  3938.             /*
  3939.              *    See if we've hit the start. If so insert.
  3940.              */
  3941.             if (skb1 == skb_peek(&sk->receive_queue))
  3942.             {
  3943.                 skb_queue_head(&sk->receive_queue, skb);
  3944.                 break;
  3945.             }
  3946.         }
  3947.       }
  3948.  
  3949.     /*
  3950.      *    Figure out what the ack value for this frame is
  3951.      */
  3952.      
  3953.      th->ack_seq = th->seq + skb->len;
  3954.      if (th->syn) 
  3955.          th->ack_seq++;
  3956.      if (th->fin)
  3957.          th->ack_seq++;
  3958.  
  3959.     if (before(sk->acked_seq, sk->copied_seq)) 
  3960.     {
  3961.         printk("*** tcp.c:tcp_data bug acked < copied\n");
  3962.         sk->acked_seq = sk->copied_seq;
  3963.     }
  3964.  
  3965.     /*
  3966.      *    Now figure out if we can ack anything. This is very messy because we really want two
  3967.      *    receive queues, a completed and an assembly queue. We also want only one transmit
  3968.      *    queue.
  3969.      */
  3970.  
  3971.     if ((!dup_dumped && (skb1 == NULL || skb1->acked)) || before(th->seq, sk->acked_seq+1)) 
  3972.     {
  3973.         if (before(th->seq, sk->acked_seq+1)) 
  3974.         {
  3975.             int newwindow;
  3976.  
  3977.             if (after(th->ack_seq, sk->acked_seq)) 
  3978.             {
  3979.                 newwindow = sk->window-(th->ack_seq - sk->acked_seq);
  3980.                 if (newwindow < 0)
  3981.                     newwindow = 0;    
  3982.                 sk->window = newwindow;
  3983.                 sk->acked_seq = th->ack_seq;
  3984.             }
  3985.             skb->acked = 1;
  3986.  
  3987.             /*
  3988.              *    When we ack the fin, we do the FIN 
  3989.              *    processing.
  3990.              */
  3991.  
  3992.             if (skb->h.th->fin) 
  3993.             {
  3994.                 tcp_fin(skb,sk,skb->h.th);
  3995.             }
  3996.       
  3997.             for(skb2 = skb->next;
  3998.                 skb2 != (struct sk_buff *)&sk->receive_queue;
  3999.                 skb2 = skb2->next) 
  4000.             {
  4001.                 if (before(skb2->h.th->seq, sk->acked_seq+1)) 
  4002.                 {
  4003.                     if (after(skb2->h.th->ack_seq, sk->acked_seq))
  4004.                     {
  4005.                         newwindow = sk->window -
  4006.                          (skb2->h.th->ack_seq - sk->acked_seq);
  4007.                         if (newwindow < 0)
  4008.                             newwindow = 0;    
  4009.                         sk->window = newwindow;
  4010.                         sk->acked_seq = skb2->h.th->ack_seq;
  4011.                     }
  4012.                     skb2->acked = 1;
  4013.                     /*
  4014.                      *     When we ack the fin, we do
  4015.                      *     the fin handling.
  4016.                      */
  4017.                     if (skb2->h.th->fin) 
  4018.                     {
  4019.                         tcp_fin(skb,sk,skb->h.th);
  4020.                     }
  4021.  
  4022.                     /*
  4023.                      *    Force an immediate ack.
  4024.                      */
  4025.                      
  4026.                     sk->ack_backlog = sk->max_ack_backlog;
  4027.                 }
  4028.                 else
  4029.                 {
  4030.                     break;
  4031.                 }
  4032.             }
  4033.  
  4034.             /*
  4035.              *    This also takes care of updating the window.
  4036.              *    This if statement needs to be simplified.
  4037.              */
  4038.             if (!sk->delay_acks ||
  4039.                 sk->ack_backlog >= sk->max_ack_backlog || 
  4040.                 sk->bytes_rcv > sk->max_unacked || th->fin) {
  4041.     /*            tcp_send_ack(sk->sent_seq, sk->acked_seq,sk,th, saddr); */
  4042.             }
  4043.             else 
  4044.             {
  4045.                 sk->ack_backlog++;
  4046.                 if(sk->debug)
  4047.                     printk("Ack queued.\n");
  4048.                 reset_xmit_timer(sk, TIME_WRITE, TCP_ACK_TIME);
  4049.             }
  4050.         }
  4051.     }
  4052.  
  4053.     /*
  4054.      *    If we've missed a packet, send an ack.
  4055.      *    Also start a timer to send another.
  4056.      */
  4057.      
  4058.     if (!skb->acked) 
  4059.     {
  4060.     
  4061.     /*
  4062.      *    This is important.  If we don't have much room left,
  4063.      *    we need to throw out a few packets so we have a good
  4064.      *    window.  Note that mtu is used, not mss, because mss is really
  4065.      *    for the send side.  He could be sending us stuff as large as mtu.
  4066.      */
  4067.          
  4068.         while (sk->prot->rspace(sk) < sk->mtu) 
  4069.         {
  4070.             skb1 = skb_peek(&sk->receive_queue);
  4071.             if (skb1 == NULL) 
  4072.             {
  4073.                 printk("INET: tcp.c:tcp_data memory leak detected.\n");
  4074.                 break;
  4075.             }
  4076.  
  4077.             /*
  4078.              *    Don't throw out something that has been acked. 
  4079.              */
  4080.          
  4081.             if (skb1->acked) 
  4082.             {
  4083.                 break;
  4084.             }
  4085.         
  4086.             skb_unlink(skb1);
  4087.             kfree_skb(skb1, FREE_READ);
  4088.         }
  4089.         tcp_send_ack(sk->sent_seq, sk->acked_seq, sk, th, saddr);
  4090.         sk->ack_backlog++;
  4091.         reset_xmit_timer(sk, TIME_WRITE, TCP_ACK_TIME);
  4092.     }
  4093.     else
  4094.     {
  4095.         tcp_send_ack(sk->sent_seq, sk->acked_seq, sk, th, saddr);
  4096.     }
  4097.  
  4098.     /*
  4099.      *    Now tell the user we may have some data. 
  4100.      */
  4101.      
  4102.     if (!sk->dead) 
  4103.     {
  4104.             if(sk->debug)
  4105.                 printk("Data wakeup.\n");
  4106.         sk->data_ready(sk,0);
  4107.     } 
  4108.     return(0);
  4109. }
  4110.  
  4111.  
  4112. /*
  4113.  *    This routine is only called when we have urgent data
  4114.  *    signalled. Its the 'slow' part of tcp_urg. It could be
  4115.  *    moved inline now as tcp_urg is only called from one
  4116.  *    place. We handle URGent data wrong. We have to - as
  4117.  *    BSD still doesn't use the correction from RFC961.
  4118.  */
  4119.  
  4120. static void tcp_check_urg(struct sock * sk, struct tcphdr * th)
  4121. {
  4122.     unsigned long ptr = ntohs(th->urg_ptr);
  4123.  
  4124.     if (ptr)
  4125.         ptr--;
  4126.     ptr += th->seq;
  4127.  
  4128.     /* ignore urgent data that we've already seen and read */
  4129.     if (after(sk->copied_seq, ptr))
  4130.         return;
  4131.  
  4132.     /* do we already have a newer (or duplicate) urgent pointer? */
  4133.     if (sk->urg_data && !after(ptr, sk->urg_seq))
  4134.         return;
  4135.  
  4136.     /* tell the world about our new urgent pointer */
  4137.     if (sk->proc != 0) {
  4138.         if (sk->proc > 0) {
  4139.             kill_proc(sk->proc, SIGURG, 1);
  4140.         } else {
  4141.             kill_pg(-sk->proc, SIGURG, 1);
  4142.         }
  4143.     }
  4144.     sk->urg_data = URG_NOTYET;
  4145.     sk->urg_seq = ptr;
  4146. }
  4147.  
  4148. /*
  4149.  *    This is the 'fast' part of urgent handling.
  4150.  */
  4151.  
  4152. extern __inline__ int tcp_urg(struct sock *sk, struct tcphdr *th,
  4153.     unsigned long saddr, unsigned long len)
  4154. {
  4155.     unsigned long ptr;
  4156.  
  4157.     /*
  4158.      *    Check if we get a new urgent pointer - normally not 
  4159.      */
  4160.      
  4161.     if (th->urg)
  4162.         tcp_check_urg(sk,th);
  4163.  
  4164.     /*
  4165.      *    Do we wait for any urgent data? - normally not
  4166.      */
  4167.      
  4168.     if (sk->urg_data != URG_NOTYET)
  4169.         return 0;
  4170.  
  4171.     /*
  4172.      *    Is the urgent pointer pointing into this packet? 
  4173.      */
  4174.      
  4175.     ptr = sk->urg_seq - th->seq + th->doff*4;
  4176.     if (ptr >= len)
  4177.         return 0;
  4178.  
  4179.     /*
  4180.      *    Ok, got the correct packet, update info 
  4181.      */
  4182.      
  4183.     sk->urg_data = URG_VALID | *(ptr + (unsigned char *) th);
  4184.     if (!sk->dead)
  4185.         sk->data_ready(sk,0);
  4186.     return 0;
  4187. }
  4188.  
  4189. /*
  4190.  *    This will accept the next outstanding connection. 
  4191.  */
  4192.  
  4193. static struct sock *tcp_accept(struct sock *sk, int flags)
  4194. {
  4195.     struct sock *newsk;
  4196.     struct sk_buff *skb;
  4197.   
  4198.   /*
  4199.    * We need to make sure that this socket is listening,
  4200.    * and that it has something pending.
  4201.    */
  4202.  
  4203.     if (sk->state != TCP_LISTEN) 
  4204.     {
  4205.         sk->err = EINVAL;
  4206.         return(NULL); 
  4207.     }
  4208.  
  4209.     /* Avoid the race. */
  4210.     cli();
  4211.     sk->inuse = 1;
  4212.  
  4213.     while((skb = tcp_dequeue_established(sk)) == NULL) 
  4214.     {
  4215.         if (flags & O_NONBLOCK) 
  4216.         {
  4217.             sti();
  4218.             release_sock(sk);
  4219.             sk->err = EAGAIN;
  4220.             return(NULL);
  4221.         }
  4222.  
  4223.         release_sock(sk);
  4224.         interruptible_sleep_on(sk->sleep);
  4225.         if (current->signal & ~current->blocked) 
  4226.         {
  4227.             sti();
  4228.             sk->err = ERESTARTSYS;
  4229.             return(NULL);
  4230.         }
  4231.         sk->inuse = 1;
  4232.       }
  4233.     sti();
  4234.  
  4235.     /*
  4236.      *    Now all we need to do is return skb->sk. 
  4237.      */
  4238.  
  4239.     newsk = skb->sk;
  4240.  
  4241.     kfree_skb(skb, FREE_READ);
  4242.     sk->ack_backlog--;
  4243.     release_sock(sk);
  4244.     return(newsk);
  4245. }
  4246.  
  4247.  
  4248. /*
  4249.  *    This will initiate an outgoing connection. 
  4250.  */
  4251.  
  4252. static int tcp_connect(struct sock *sk, struct sockaddr_in *usin, int addr_len)
  4253. {
  4254.     struct sk_buff *buff;
  4255.     struct device *dev=NULL;
  4256.     unsigned char *ptr;
  4257.     int tmp;
  4258.     int atype;
  4259.     struct tcphdr *t1;
  4260.     struct rtable *rt;
  4261.  
  4262.     if (sk->state != TCP_CLOSE) 
  4263.     {
  4264.         return(-EISCONN);
  4265.     }
  4266.     
  4267.     if (addr_len < 8) 
  4268.         return(-EINVAL);
  4269.  
  4270.     if (usin->sin_family && usin->sin_family != AF_INET) 
  4271.         return(-EAFNOSUPPORT);
  4272.  
  4273.       /*
  4274.        *    connect() to INADDR_ANY means loopback (BSD'ism).
  4275.        */
  4276.       
  4277.       if(usin->sin_addr.s_addr==INADDR_ANY)
  4278.         usin->sin_addr.s_addr=ip_my_addr();
  4279.           
  4280.     /*
  4281.      *    Don't want a TCP connection going to a broadcast address 
  4282.      */
  4283.  
  4284.     if ((atype=ip_chk_addr(usin->sin_addr.s_addr)) == IS_BROADCAST || atype==IS_MULTICAST) 
  4285.         return -ENETUNREACH;
  4286.   
  4287.     sk->inuse = 1;
  4288.     sk->daddr = usin->sin_addr.s_addr;
  4289.     sk->write_seq = tcp_init_seq();
  4290.     sk->window_seq = sk->write_seq;
  4291.     sk->rcv_ack_seq = sk->write_seq -1;
  4292.     sk->err = 0;
  4293.     sk->dummy_th.dest = usin->sin_port;
  4294.     release_sock(sk);
  4295.  
  4296.     buff = sk->prot->wmalloc(sk,MAX_SYN_SIZE,0, GFP_KERNEL);
  4297.     if (buff == NULL) 
  4298.     {
  4299.         return(-ENOMEM);
  4300.     }
  4301.     sk->inuse = 1;
  4302.     buff->len = 24;
  4303.     buff->sk = sk;
  4304.     buff->free = 0;
  4305.     buff->localroute = sk->localroute;
  4306.     
  4307.     t1 = (struct tcphdr *) buff->data;
  4308.  
  4309.     /*
  4310.      *    Put in the IP header and routing stuff. 
  4311.      */
  4312.      
  4313.     rt=ip_rt_route(sk->daddr, NULL, NULL);
  4314.     
  4315.  
  4316.     /*
  4317.      *    We need to build the routing stuff from the things saved in skb. 
  4318.      */
  4319.  
  4320.     tmp = sk->prot->build_header(buff, sk->saddr, sk->daddr, &dev,
  4321.                     IPPROTO_TCP, NULL, MAX_SYN_SIZE,sk->ip_tos,sk->ip_ttl);
  4322.     if (tmp < 0) 
  4323.     {
  4324.         sk->prot->wfree(sk, buff->mem_addr, buff->mem_len);
  4325.         release_sock(sk);
  4326.         return(-ENETUNREACH);
  4327.     }
  4328.  
  4329.     buff->len += tmp;
  4330.     t1 = (struct tcphdr *)((char *)t1 +tmp);
  4331.  
  4332.     memcpy(t1,(void *)&(sk->dummy_th), sizeof(*t1));
  4333.     t1->seq = ntohl(sk->write_seq++);
  4334.     sk->sent_seq = sk->write_seq;
  4335.     buff->h.seq = sk->write_seq;
  4336.     t1->ack = 0;
  4337.     t1->window = 2;
  4338.     t1->res1=0;
  4339.     t1->res2=0;
  4340.     t1->rst = 0;
  4341.     t1->urg = 0;
  4342.     t1->psh = 0;
  4343.     t1->syn = 1;
  4344.     t1->urg_ptr = 0;
  4345.     t1->doff = 6;
  4346.     /* use 512 or whatever user asked for */
  4347.     
  4348.     if(rt!=NULL && (rt->rt_flags&RTF_WINDOW))
  4349.         sk->window_clamp=rt->rt_window;
  4350.     else
  4351.         sk->window_clamp=0;
  4352.  
  4353.     if (sk->user_mss)
  4354.         sk->mtu = sk->user_mss;
  4355.     else if(rt!=NULL && (rt->rt_flags&RTF_MTU))
  4356.         sk->mtu = rt->rt_mss;
  4357.     else 
  4358.     {
  4359. #ifdef CONFIG_INET_SNARL
  4360.         if ((sk->saddr ^ sk->daddr) & default_mask(sk->saddr))
  4361. #else
  4362.         if ((sk->saddr ^ sk->daddr) & dev->pa_mask)
  4363. #endif
  4364.             sk->mtu = 576 - HEADER_SIZE;
  4365.         else
  4366.             sk->mtu = MAX_WINDOW;
  4367.     }
  4368.     /*
  4369.      *    but not bigger than device MTU 
  4370.      */
  4371.  
  4372.     if(sk->mtu <32)
  4373.         sk->mtu = 32;    /* Sanity limit */
  4374.         
  4375.     sk->mtu = min(sk->mtu, dev->mtu - HEADER_SIZE);
  4376.     
  4377.     /*
  4378.      *    Put in the TCP options to say MTU. 
  4379.      */
  4380.  
  4381.     ptr = (unsigned char *)(t1+1);
  4382.     ptr[0] = 2;
  4383.     ptr[1] = 4;
  4384.     ptr[2] = (sk->mtu) >> 8;
  4385.     ptr[3] = (sk->mtu) & 0xff;
  4386.     tcp_send_check(t1, sk->saddr, sk->daddr,
  4387.           sizeof(struct tcphdr) + 4, sk);
  4388.  
  4389.     /*
  4390.      *    This must go first otherwise a really quick response will get reset. 
  4391.      */
  4392.  
  4393.     tcp_set_state(sk,TCP_SYN_SENT);
  4394.     sk->rto = TCP_TIMEOUT_INIT;
  4395. #if 0 /* we already did this */
  4396.     init_timer(&sk->retransmit_timer); 
  4397. #endif
  4398.     sk->retransmit_timer.function=&retransmit_timer;
  4399.     sk->retransmit_timer.data = (unsigned long)sk;
  4400.     reset_xmit_timer(sk, TIME_WRITE, sk->rto);    /* Timer for repeating the SYN until an answer */
  4401.     sk->retransmits = TCP_SYN_RETRIES;
  4402.  
  4403.     sk->prot->queue_xmit(sk, dev, buff, 0);  
  4404.     reset_xmit_timer(sk, TIME_WRITE, sk->rto);
  4405.     tcp_statistics.TcpActiveOpens++;
  4406.     tcp_statistics.TcpOutSegs++;
  4407.   
  4408.     release_sock(sk);
  4409.     return(0);
  4410. }
  4411.  
  4412.  
  4413. /* This functions checks to see if the tcp header is actually acceptable. */
  4414. extern __inline__ int tcp_sequence(struct sock *sk, struct tcphdr *th, short len,
  4415.          struct options *opt, unsigned long saddr, struct device *dev)
  4416. {
  4417.     unsigned long next_seq;
  4418.  
  4419.     next_seq = len - 4*th->doff;
  4420.     if (th->fin)
  4421.         next_seq++;
  4422.     /* if we have a zero window, we can't have any data in the packet.. */
  4423.     if (next_seq && !sk->window)
  4424.         goto ignore_it;
  4425.     next_seq += th->seq;
  4426.  
  4427.     /*
  4428.      * This isn't quite right.  sk->acked_seq could be more recent
  4429.      * than sk->window.  This is however close enough.  We will accept
  4430.      * slightly more packets than we should, but it should not cause
  4431.      * problems unless someone is trying to forge packets.
  4432.      */
  4433.  
  4434.     /* have we already seen all of this packet? */
  4435.     if (!after(next_seq+1, sk->acked_seq))
  4436.         goto ignore_it;
  4437.     /* or does it start beyond the window? */
  4438.     if (!before(th->seq, sk->acked_seq + sk->window + 1))
  4439.         goto ignore_it;
  4440.  
  4441.     /* ok, at least part of this packet would seem interesting.. */
  4442.     return 1;
  4443.  
  4444. ignore_it:
  4445.     if (th->rst)
  4446.         return 0;
  4447.  
  4448.     /*
  4449.      *    Send a reset if we get something not ours and we are
  4450.      *    unsynchronized. Note: We don't do anything to our end. We
  4451.      *    are just killing the bogus remote connection then we will
  4452.      *    connect again and it will work (with luck).
  4453.      */
  4454.        
  4455.     if (sk->state==TCP_SYN_SENT || sk->state==TCP_SYN_RECV) 
  4456.     {
  4457.         tcp_reset(sk->saddr,sk->daddr,th,sk->prot,NULL,dev, sk->ip_tos,sk->ip_ttl);
  4458.         return 1;
  4459.     }
  4460.  
  4461.     /* Try to resync things. */
  4462.     tcp_send_ack(sk->sent_seq, sk->acked_seq, sk, th, saddr);
  4463.     return 0;
  4464. }
  4465.  
  4466. /*
  4467.  *    When we get a reset we do this.
  4468.  */
  4469.  
  4470. static int tcp_std_reset(struct sock *sk, struct sk_buff *skb)
  4471. {
  4472.     sk->zapped = 1;
  4473.     sk->err = ECONNRESET;
  4474.     if (sk->state == TCP_SYN_SENT)
  4475.         sk->err = ECONNREFUSED;
  4476.     if (sk->state == TCP_CLOSE_WAIT)
  4477.         sk->err = EPIPE;
  4478. #ifdef TCP_DO_RFC1337        
  4479.     /*
  4480.      *    Time wait assassination protection [RFC1337]
  4481.      */
  4482.     if(sk->state!=TCP_TIME_WAIT)
  4483.     {    
  4484.         tcp_set_state(sk,TCP_CLOSE);
  4485.         sk->shutdown = SHUTDOWN_MASK;
  4486.     }
  4487. #else    
  4488.     tcp_set_state(sk,TCP_CLOSE);
  4489.     sk->shutdown = SHUTDOWN_MASK;
  4490. #endif    
  4491.     if (!sk->dead) 
  4492.         sk->state_change(sk);
  4493.     kfree_skb(skb, FREE_READ);
  4494.     release_sock(sk);
  4495.     return(0);
  4496. }
  4497.  
  4498. /*
  4499.  *    A TCP packet has arrived.
  4500.  */
  4501.  
  4502. int tcp_rcv(struct sk_buff *skb, struct device *dev, struct options *opt,
  4503.     unsigned long daddr, unsigned short len,
  4504.     unsigned long saddr, int redo, struct inet_protocol * protocol)
  4505. {
  4506.     struct tcphdr *th;
  4507.     struct sock *sk;
  4508.     int syn_ok=0;
  4509.     
  4510.     if (!skb) 
  4511.     {
  4512.         printk("IMPOSSIBLE 1\n");
  4513.         return(0);
  4514.     }
  4515.  
  4516.     if (!dev) 
  4517.     {
  4518.         printk("IMPOSSIBLE 2\n");
  4519.         return(0);
  4520.     }
  4521.   
  4522.     tcp_statistics.TcpInSegs++;
  4523.   
  4524.     if(skb->pkt_type!=PACKET_HOST)
  4525.     {
  4526.           kfree_skb(skb,FREE_READ);
  4527.           return(0);
  4528.     }
  4529.   
  4530.     th = skb->h.th;
  4531.  
  4532.     /*
  4533.      *    Find the socket.
  4534.      */
  4535.  
  4536.     sk = get_sock(&tcp_prot, th->dest, saddr, th->source, daddr);
  4537.  
  4538.     /*
  4539.      *    If this socket has got a reset it's to all intents and purposes 
  4540.        *    really dead. Count closed sockets as dead.
  4541.        *
  4542.        *    Note: BSD appears to have a bug here. A 'closed' TCP in BSD
  4543.        *    simply drops data. This seems incorrect as a 'closed' TCP doesn't
  4544.        *    exist so should cause resets as if the port was unreachable.
  4545.        */
  4546.        
  4547.     if (sk!=NULL && (sk->zapped || sk->state==TCP_CLOSE))
  4548.         sk=NULL;
  4549.  
  4550.     if (!redo) 
  4551.     {
  4552.         if (tcp_check(th, len, saddr, daddr )) 
  4553.         {
  4554.             skb->sk = NULL;
  4555.             kfree_skb(skb,FREE_READ);
  4556.             /*
  4557.              *    We don't release the socket because it was
  4558.              *    never marked in use.
  4559.              */
  4560.             return(0);
  4561.         }
  4562.         th->seq = ntohl(th->seq);
  4563.  
  4564.         /* See if we know about the socket. */
  4565.         if (sk == NULL) 
  4566.         {
  4567.             /*
  4568.              *    No such TCB. If th->rst is 0 send a reset (checked in tcp_reset)
  4569.              */
  4570.             tcp_reset(daddr, saddr, th, &tcp_prot, opt,dev,skb->ip_hdr->tos,255);
  4571.             skb->sk = NULL;
  4572.             /*
  4573.              *    Discard frame
  4574.              */
  4575.             kfree_skb(skb, FREE_READ);
  4576.             return(0);
  4577.         }
  4578.  
  4579.         skb->len = len;
  4580.         skb->acked = 0;
  4581.         skb->used = 0;
  4582.         skb->free = 0;
  4583.         skb->saddr = daddr;
  4584.         skb->daddr = saddr;
  4585.     
  4586.         /* We may need to add it to the backlog here. */
  4587.         cli();
  4588.         if (sk->inuse) 
  4589.         {
  4590.             skb_queue_tail(&sk->back_log, skb);
  4591.             sti();
  4592.             return(0);
  4593.         }
  4594.         sk->inuse = 1;
  4595.         sti();
  4596.     }
  4597.     else
  4598.     {
  4599.         if (sk==NULL) 
  4600.         {
  4601.             tcp_reset(daddr, saddr, th, &tcp_prot, opt,dev,skb->ip_hdr->tos,255);
  4602.             skb->sk = NULL;
  4603.             kfree_skb(skb, FREE_READ);
  4604.             return(0);
  4605.         }
  4606.     }
  4607.  
  4608.  
  4609.     if (!sk->prot) 
  4610.     {
  4611.         printk("IMPOSSIBLE 3\n");
  4612.         return(0);
  4613.     }
  4614.  
  4615.  
  4616.     /*
  4617.      *    Charge the memory to the socket. 
  4618.      */
  4619.      
  4620.     if (sk->rmem_alloc + skb->mem_len >= sk->rcvbuf) 
  4621.     {
  4622.         kfree_skb(skb, FREE_READ);
  4623.         release_sock(sk);
  4624.         return(0);
  4625.     }
  4626.  
  4627.     skb->sk=sk;
  4628.     sk->rmem_alloc += skb->mem_len;
  4629.  
  4630.     /*
  4631.      *    This basically follows the flow suggested by RFC793, with the corrections in RFC1122. We
  4632.      *    don't implement precedence and we process URG incorrectly (deliberately so) for BSD bug
  4633.      *    compatibility. We also set up variables more thoroughly [Karn notes in the
  4634.      *    KA9Q code the RFC793 incoming segment rules don't initialise the variables for all paths].
  4635.      */
  4636.  
  4637.     if(sk->state!=TCP_ESTABLISHED)        /* Skip this lot for normal flow */
  4638.     {
  4639.     
  4640.         /*
  4641.          *    Now deal with unusual cases.
  4642.          */
  4643.      
  4644.         if(sk->state==TCP_LISTEN)
  4645.         {
  4646.             if(th->ack)    /* These use the socket TOS.. might want to be the received TOS */
  4647.                 tcp_reset(daddr,saddr,th,sk->prot,opt,dev,sk->ip_tos, sk->ip_ttl);
  4648.  
  4649.             /*
  4650.              *    We don't care for RST, and non SYN are absorbed (old segments)
  4651.              *    Broadcast/multicast SYN isn't allowed. Note - bug if you change the
  4652.              *    netmask on a running connection it can go broadcast. Even Sun's have
  4653.              *    this problem so I'm ignoring it 
  4654.              */
  4655.                
  4656.             if(th->rst || !th->syn || th->ack || ip_chk_addr(daddr)!=IS_MYADDR)
  4657.             {
  4658.                 kfree_skb(skb, FREE_READ);
  4659.                 release_sock(sk);
  4660.                 return 0;
  4661.             }
  4662.         
  4663.             /*    
  4664.              *    Guess we need to make a new socket up 
  4665.              */
  4666.         
  4667.             tcp_conn_request(sk, skb, daddr, saddr, opt, dev, tcp_init_seq());
  4668.         
  4669.             /*
  4670.              *    Now we have several options: In theory there is nothing else
  4671.              *    in the frame. KA9Q has an option to send data with the syn,
  4672.              *    BSD accepts data with the syn up to the [to be] advertised window
  4673.              *    and Solaris 2.1 gives you a protocol error. For now we just ignore
  4674.              *    it, that fits the spec precisely and avoids incompatibilities. It
  4675.              *    would be nice in future to drop through and process the data.
  4676.              */
  4677.              
  4678.             release_sock(sk);
  4679.             return 0;
  4680.         }
  4681.     
  4682.         /* retransmitted SYN? */
  4683.         if (sk->state == TCP_SYN_RECV && th->syn && th->seq+1 == sk->acked_seq)
  4684.         {
  4685.             kfree_skb(skb, FREE_READ);
  4686.             release_sock(sk);
  4687.             return 0;
  4688.         }
  4689.         
  4690.         /*
  4691.          *    SYN sent means we have to look for a suitable ack and either reset
  4692.          *    for bad matches or go to connected 
  4693.          */
  4694.        
  4695.         if(sk->state==TCP_SYN_SENT)
  4696.         {
  4697.             /* Crossed SYN or previous junk segment */
  4698.             if(th->ack)
  4699.             {
  4700.                 /* We got an ack, but it's not a good ack */
  4701.                 if(!tcp_ack(sk,th,saddr,len))
  4702.                 {
  4703.                     /* Reset the ack - its an ack from a 
  4704.                        different connection  [ th->rst is checked in tcp_reset()] */
  4705.                     tcp_statistics.TcpAttemptFails++;
  4706.                     tcp_reset(daddr, saddr, th,
  4707.                         sk->prot, opt,dev,sk->ip_tos,sk->ip_ttl);
  4708.                     kfree_skb(skb, FREE_READ);
  4709.                     release_sock(sk);
  4710.                     return(0);
  4711.                 }
  4712.                 if(th->rst)
  4713.                     return tcp_std_reset(sk,skb);
  4714.                 if(!th->syn)
  4715.                 {
  4716.                     /* A valid ack from a different connection
  4717.                        start. Shouldn't happen but cover it */
  4718.                     kfree_skb(skb, FREE_READ);
  4719.                     release_sock(sk);
  4720.                     return 0;
  4721.                 }
  4722.                 /*
  4723.                  *    Ok.. it's good. Set up sequence numbers and
  4724.                  *    move to established.
  4725.                  */
  4726.                 syn_ok=1;    /* Don't reset this connection for the syn */
  4727.                 sk->acked_seq=th->seq+1;
  4728.                 sk->fin_seq=th->seq;
  4729.                 tcp_send_ack(sk->sent_seq,sk->acked_seq,sk,th,sk->daddr);
  4730.                 tcp_set_state(sk, TCP_ESTABLISHED);
  4731.                 tcp_options(sk,th);
  4732.                 sk->dummy_th.dest=th->source;
  4733.                 sk->copied_seq = sk->acked_seq;
  4734.                 if(!sk->dead)
  4735.                 {
  4736.                     sk->state_change(sk);
  4737.                     sock_wake_async(sk->socket, 0);
  4738.                 }
  4739.                 if(sk->max_window==0)
  4740.                 {
  4741.                     sk->max_window = 32;
  4742.                     sk->mss = min(sk->max_window, sk->mtu);
  4743.                 }
  4744.             }
  4745.             else
  4746.             {
  4747.                 /* See if SYN's cross. Drop if boring */
  4748.                 if(th->syn && !th->rst)
  4749.                 {
  4750.                     /* Crossed SYN's are fine - but talking to
  4751.                        yourself is right out... */
  4752.                     if(sk->saddr==saddr && sk->daddr==daddr &&
  4753.                         sk->dummy_th.source==th->source &&
  4754.                         sk->dummy_th.dest==th->dest)
  4755.                     {
  4756.                         tcp_statistics.TcpAttemptFails++;
  4757.                         return tcp_std_reset(sk,skb);
  4758.                     }
  4759.                     tcp_set_state(sk,TCP_SYN_RECV);
  4760.                     
  4761.                     /*
  4762.                      *    FIXME:
  4763.                      *    Must send SYN|ACK here
  4764.                      */
  4765.                 }        
  4766.                 /* Discard junk segment */
  4767.                 kfree_skb(skb, FREE_READ);
  4768.                 release_sock(sk);
  4769.                 return 0;
  4770.             }
  4771.             /*
  4772.              *    SYN_RECV with data maybe.. drop through
  4773.              */
  4774.             goto rfc_step6;
  4775.         }
  4776.  
  4777.     /*
  4778.      *    BSD has a funny hack with TIME_WAIT and fast reuse of a port. There is
  4779.      *    a more complex suggestion for fixing these reuse issues in RFC1644
  4780.      *    but not yet ready for general use. Also see RFC1379.
  4781.      */
  4782.     
  4783. #define BSD_TIME_WAIT
  4784. #ifdef BSD_TIME_WAIT
  4785.         if (sk->state == TCP_TIME_WAIT && th->syn && sk->dead && 
  4786.             after(th->seq, sk->acked_seq) && !th->rst)
  4787.         {
  4788.             long seq=sk->write_seq;
  4789.             if(sk->debug)
  4790.                 printk("Doing a BSD time wait\n");
  4791.             tcp_statistics.TcpEstabResets++;       
  4792.             sk->rmem_alloc -= skb->mem_len;
  4793.             skb->sk = NULL;
  4794.             sk->err=ECONNRESET;
  4795.             tcp_set_state(sk, TCP_CLOSE);
  4796.             sk->shutdown = SHUTDOWN_MASK;
  4797.             release_sock(sk);
  4798.             sk=get_sock(&tcp_prot, th->dest, saddr, th->source, daddr);
  4799.             if (sk && sk->state==TCP_LISTEN)
  4800.             {
  4801.                 sk->inuse=1;
  4802.                 skb->sk = sk;
  4803.                 sk->rmem_alloc += skb->mem_len;
  4804.                 tcp_conn_request(sk, skb, daddr, saddr,opt, dev,seq+128000);
  4805.                 release_sock(sk);
  4806.                 return 0;
  4807.             }
  4808.             kfree_skb(skb, FREE_READ);
  4809.             return 0;
  4810.         }
  4811. #endif    
  4812.     }
  4813.  
  4814.     /*
  4815.      *    We are now in normal data flow (see the step list in the RFC)
  4816.      *    Note most of these are inline now. I'll inline the lot when
  4817.      *    I have time to test it hard and look at what gcc outputs 
  4818.      */
  4819.     
  4820.     if(!tcp_sequence(sk,th,len,opt,saddr,dev))
  4821.     {
  4822.         kfree_skb(skb, FREE_READ);
  4823.         release_sock(sk);
  4824.         return 0;
  4825.     }
  4826.  
  4827.     if(th->rst)
  4828.         return tcp_std_reset(sk,skb);
  4829.     
  4830.     /*
  4831.      *    !syn_ok is effectively the state test in RFC793.
  4832.      */
  4833.      
  4834.     if(th->syn && !syn_ok)
  4835.     {
  4836.         tcp_reset(daddr,saddr,th, &tcp_prot, opt, dev, skb->ip_hdr->tos, 255);
  4837.         return tcp_std_reset(sk,skb);    
  4838.     }
  4839.  
  4840.     /*
  4841.      *    Process the ACK
  4842.      */
  4843.      
  4844.  
  4845.     if(th->ack && !tcp_ack(sk,th,saddr,len))
  4846.     {
  4847.         /*
  4848.          *    Our three way handshake failed.
  4849.          */
  4850.          
  4851.         if(sk->state==TCP_SYN_RECV)
  4852.         {
  4853.             tcp_reset(daddr, saddr, th,sk->prot, opt, dev,sk->ip_tos,sk->ip_ttl);
  4854.         }
  4855.         kfree_skb(skb, FREE_READ);
  4856.         release_sock(sk);
  4857.         return 0;
  4858.     }
  4859.     
  4860. rfc_step6:        /* I'll clean this up later */
  4861.  
  4862.     /*
  4863.      *    Process urgent data
  4864.      */
  4865.          
  4866.     if(tcp_urg(sk, th, saddr, len))
  4867.     {
  4868.         kfree_skb(skb, FREE_READ);
  4869.         release_sock(sk);
  4870.         return 0;
  4871.     }
  4872.     
  4873.     
  4874.     /*
  4875.      *    Process the encapsulated data
  4876.      */
  4877.     
  4878.     if(tcp_data(skb,sk, saddr, len))
  4879.     {
  4880.         kfree_skb(skb, FREE_READ);
  4881.         release_sock(sk);
  4882.         return 0;
  4883.     }
  4884.  
  4885.     /*
  4886.      *    And done
  4887.      */    
  4888.     
  4889.     release_sock(sk);
  4890.     return 0;
  4891. }
  4892.  
  4893. /*
  4894.  *    This routine sends a packet with an out of date sequence
  4895.  *    number. It assumes the other end will try to ack it.
  4896.  */
  4897.  
  4898. static void tcp_write_wakeup(struct sock *sk)
  4899. {
  4900.     struct sk_buff *buff;
  4901.     struct tcphdr *t1;
  4902.     struct device *dev=NULL;
  4903.     int tmp;
  4904.  
  4905.     if (sk->zapped)
  4906.         return;    /* After a valid reset we can send no more */
  4907.  
  4908.     /*
  4909.      *    Write data can still be transmitted/retransmitted in the
  4910.      *    following states.  If any other state is encountered, return.
  4911.      *    [listen/close will never occur here anyway]
  4912.      */
  4913.  
  4914.     if (sk->state != TCP_ESTABLISHED && 
  4915.         sk->state != TCP_CLOSE_WAIT &&
  4916.         sk->state != TCP_FIN_WAIT1 && 
  4917.         sk->state != TCP_LAST_ACK &&
  4918.         sk->state != TCP_CLOSING
  4919.     ) 
  4920.     {
  4921.         return;
  4922.     }
  4923.  
  4924.     buff = sk->prot->wmalloc(sk,MAX_ACK_SIZE,1, GFP_ATOMIC);
  4925.     if (buff == NULL) 
  4926.         return;
  4927.  
  4928.     buff->len = sizeof(struct tcphdr);
  4929.     buff->free = 1;
  4930.     buff->sk = sk;
  4931.     buff->localroute = sk->localroute;
  4932.  
  4933.     t1 = (struct tcphdr *) buff->data;
  4934.  
  4935.     /* Put in the IP header and routing stuff. */
  4936.     tmp = sk->prot->build_header(buff, sk->saddr, sk->daddr, &dev,
  4937.                 IPPROTO_TCP, sk->opt, MAX_ACK_SIZE,sk->ip_tos,sk->ip_ttl);
  4938.     if (tmp < 0) 
  4939.     {
  4940.         sk->prot->wfree(sk, buff->mem_addr, buff->mem_len);
  4941.         return;
  4942.     }
  4943.  
  4944.     buff->len += tmp;
  4945.     t1 = (struct tcphdr *)((char *)t1 +tmp);
  4946.  
  4947.     memcpy(t1,(void *) &sk->dummy_th, sizeof(*t1));
  4948.  
  4949.     /*
  4950.      *    Use a previous sequence.
  4951.      *    This should cause the other end to send an ack.
  4952.      */
  4953.      
  4954.     t1->seq = htonl(sk->sent_seq-1);
  4955.     t1->ack = 1; 
  4956.     t1->res1= 0;
  4957.     t1->res2= 0;
  4958.     t1->rst = 0;
  4959.     t1->urg = 0;
  4960.     t1->psh = 0;
  4961.     t1->fin = 0;    /* We are sending a 'previous' sequence, and 0 bytes of data - thus no FIN bit */
  4962.     t1->syn = 0;
  4963.     t1->ack_seq = ntohl(sk->acked_seq);
  4964.     t1->window = ntohs(tcp_select_window(sk));
  4965.     t1->doff = sizeof(*t1)/4;
  4966.     tcp_send_check(t1, sk->saddr, sk->daddr, sizeof(*t1), sk);
  4967.      /*
  4968.       *    Send it and free it.
  4969.          *    This will prevent the timer from automatically being restarted.
  4970.       */
  4971.     sk->prot->queue_xmit(sk, dev, buff, 1);
  4972.     tcp_statistics.TcpOutSegs++;
  4973. }
  4974.  
  4975. /*
  4976.  *    A window probe timeout has occurred.
  4977.  */
  4978.  
  4979. void tcp_send_probe0(struct sock *sk)
  4980. {
  4981.     if (sk->zapped)
  4982.         return;        /* After a valid reset we can send no more */
  4983.  
  4984.     tcp_write_wakeup(sk);
  4985.  
  4986.     sk->backoff++;
  4987.     sk->rto = min(sk->rto << 1, 120*HZ);
  4988.     reset_xmit_timer (sk, TIME_PROBE0, sk->rto);
  4989.     sk->retransmits++;
  4990.     sk->prot->retransmits ++;
  4991. }
  4992.  
  4993. /*
  4994.  *    Socket option code for TCP. 
  4995.  */
  4996.   
  4997. int tcp_setsockopt(struct sock *sk, int level, int optname, char *optval, int optlen)
  4998. {
  4999.     int val,err;
  5000.  
  5001.     if(level!=SOL_TCP)
  5002.         return ip_setsockopt(sk,level,optname,optval,optlen);
  5003.  
  5004.       if (optval == NULL) 
  5005.           return(-EINVAL);
  5006.  
  5007.       err=verify_area(VERIFY_READ, optval, sizeof(int));
  5008.       if(err)
  5009.           return err;
  5010.       
  5011.       val = get_fs_long((unsigned long *)optval);
  5012.  
  5013.     switch(optname)
  5014.     {
  5015.         case TCP_MAXSEG:
  5016. /*
  5017.  * values greater than interface MTU won't take effect.  however at
  5018.  * the point when this call is done we typically don't yet know
  5019.  * which interface is going to be used
  5020.  */
  5021.               if(val<1||val>MAX_WINDOW)
  5022.                 return -EINVAL;
  5023.             sk->user_mss=val;
  5024.             return 0;
  5025.         case TCP_NODELAY:
  5026.             sk->nonagle=(val==0)?0:1;
  5027.             return 0;
  5028.         default:
  5029.             return(-ENOPROTOOPT);
  5030.     }
  5031. }
  5032.  
  5033. int tcp_getsockopt(struct sock *sk, int level, int optname, char *optval, int *optlen)
  5034. {
  5035.     int val,err;
  5036.  
  5037.     if(level!=SOL_TCP)
  5038.         return ip_getsockopt(sk,level,optname,optval,optlen);
  5039.             
  5040.     switch(optname)
  5041.     {
  5042.         case TCP_MAXSEG:
  5043.             val=sk->user_mss;
  5044.             break;
  5045.         case TCP_NODELAY:
  5046.             val=sk->nonagle;
  5047.             break;
  5048.         default:
  5049.             return(-ENOPROTOOPT);
  5050.     }
  5051.     err=verify_area(VERIFY_WRITE, optlen, sizeof(int));
  5052.     if(err)
  5053.           return err;
  5054.       put_fs_long(sizeof(int),(unsigned long *) optlen);
  5055.  
  5056.       err=verify_area(VERIFY_WRITE, optval, sizeof(int));
  5057.       if(err)
  5058.           return err;
  5059.       put_fs_long(val,(unsigned long *)optval);
  5060.  
  5061.       return(0);
  5062. }    
  5063.  
  5064.  
  5065. struct proto tcp_prot = {
  5066.     sock_wmalloc,
  5067.     sock_rmalloc,
  5068.     sock_wfree,
  5069.     sock_rfree,
  5070.     sock_rspace,
  5071.     sock_wspace,
  5072.     tcp_close,
  5073.     tcp_read,
  5074.     tcp_write,
  5075.     tcp_sendto,
  5076.     tcp_recvfrom,
  5077.     ip_build_header,
  5078.     tcp_connect,
  5079.     tcp_accept,
  5080.     ip_queue_xmit,
  5081.     tcp_retransmit,
  5082.     tcp_write_wakeup,
  5083.     tcp_read_wakeup,
  5084.     tcp_rcv,
  5085.     tcp_select,
  5086.     tcp_ioctl,
  5087.     NULL,
  5088.     tcp_shutdown,
  5089.     tcp_setsockopt,
  5090.     tcp_getsockopt,
  5091.     128,
  5092.     0,
  5093.     {NULL,},
  5094.     "TCP",
  5095.     0, 0
  5096. };
  5097.