【Linux 内核网络协议栈源码剖析】数据包接收(含TCP协议状态变换)


http://blog.csdn.net/wenqian1991/article/details/46731357


接前文connect 函数剖析(一)

接收数据包函数,release_sock 函数是在 sock.c中,该函数是在 inet socket 层,其内部的数据结构为 sock 结构

值得说明的是:虽然该函数放在connect篇幅里介绍,但是这个函数是一个通用的数据包接收函数,即数据通信阶段都要用的函数,不是单一属于connect,connect函数因为涉及到数据包的传输,所以连带在这里介绍了

该release_sock 函数被 tcp_connect 函数最后调用,用于接收数据包

  1. //如果对应的套接字正忙或被中断,则将数据包暂存到sock结构back_log队列中,这不能算被接收  
  2. //数据包要插入receive_queue中才能算真正完成接收  
  3. //release_sock函数则是从back_log中取数据包重新调用tcp_rcv函数对数据包进行接收,另外该函数也有释放套接字功能,如果设置了sk->dead标志位  
  4. void release_sock(struct sock *sk)  
  5. {  
  6.     unsigned long flags;  
  7. #ifdef CONFIG_INET  
  8.     struct sk_buff *skb;  
  9. #endif  
  10.   
  11.     if (!sk->prot)  
  12.         return;  
  13.     /* 
  14.      *  Make the backlog atomic. If we don't do this there is a tiny 
  15.      *  window where a packet may arrive between the sk->blog being  
  16.      *  tested and then set with sk->inuse still 0 causing an extra  
  17.      *  unwanted re-entry into release_sock(). 
  18.      */  
  19.   
  20.     save_flags(flags);//保存状态  
  21.     cli();  
  22.     if (sk->blog)   
  23.     {  
  24.         restore_flags(flags);  
  25.         return;  
  26.     }  
  27.     sk->blog=1;  
  28.     sk->inuse = 1;//加锁  
  29.     restore_flags(flags);//恢复状态  
  30. #ifdef CONFIG_INET  
  31.     /* See if we have any packets built up. */  
  32.   
  33. //从back_log中取数据包重新调用tcp_rcv函数对数据包进行接收  
  34.     while((skb = skb_dequeue(&sk->back_log)) != NULL)   
  35.     {  
  36.         sk->blog = 1;//置标识字段  
  37.         if (sk->prot->rcv)   
  38.             //调用tcp_rcv函数  
  39.             sk->prot->rcv(skb, skb->dev, sk->opt,  
  40.                  skb->saddr, skb->len, skb->daddr, 1,  
  41.                 /* Only used for/by raw sockets. */  
  42.                 (struct inet_protocol *)sk->pair);   
  43.     }  
  44. #endif    
  45.     sk->blog = 0;  
  46.     sk->inuse = 0;  
  47. #ifdef CONFIG_INET    
  48.     if (sk->dead && sk->state == TCP_CLOSE) //如果sk->dead置位,则该函数是执行释放套接字操作  
  49.     {  
  50.         /* Should be about 2 rtt's */  
  51.         //通过设置定时器来操作,定时器到时间了就释放,  
  52.         reset_timer(sk, TIME_DONE, min(sk->rtt * 2, TCP_DONE_TIME));  
  53.     }  
  54. #endif    
  55. }  

该函数内部的数据包重新接收是通过传输层的函数 tcp_rcv 实现的(tcp协议)。

传输层——tcp_rcv函数

tcp_rcv 函数是一个很重要的函数,是tcp协议数据包处理的总中心,其内部涉及到tcp状态转换,建议结合tcp状态转换图理解该函数。

                                               

  1. /* 
  2.  *  A TCP packet has arrived. 
  3.  */  
  4.  //PS:这个函数虽然放在connect函数篇幅里面介绍,但实际上这个函数是一个单纯的接收数据包函数  
  5.  //可用于一切tcp数据传输中的数据接收状态,不是单属于connect下层函数  
  6.  //该函数是tcp协议数据包接收的总入口函数,网络层协议在判断数据包使用的是tcp协议后,  
  7.  //将调用tcp_rcv函数对该数据包进行传输层的相关处理  
  8.  /* 
  9.  参数说明: 
  10.  skb:被接收的数据包;dev:接收该数据包的网络设备;opt:被接收数据包可能的ip选项 
  11.  daddr:ip首部中的远端地址字段值,对于本地接收,指的是本地ip地址 
  12.  len:ip数据负载的长度,包括tcp首部和tcp数据负载 
  13.  saddr:ip首部中源端ip地址,发送端ip地址;redo:标志位,判断数据包是新的还是原先缓存在back_log队列中的 
  14.  protocol:表示该套接字使用的协议以及协议对应的接收函数 
  15.  */  
  16. int tcp_rcv(struct sk_buff *skb, struct device *dev, struct options *opt,  
  17.     unsigned long daddr, unsigned short len,  
  18.     unsigned long saddr, int redo, struct inet_protocol * protocol)  
  19. {  
  20.     struct tcphdr *th;  
  21.     struct sock *sk;  
  22.     int syn_ok=0;  
  23.   
  24.     //参数有效性检查  
  25.     if (!skb)   
  26.     {  
  27.         printk("IMPOSSIBLE 1 ");  
  28.         return(0);  
  29.     }  
  30.     //数据包必须通过网口设备才能被接收  
  31.     if (!dev)   
  32.     {  
  33.         printk("IMPOSSIBLE 2 ");  
  34.         return(0);  
  35.     }  
  36.     
  37.     tcp_statistics.TcpInSegs++;  
  38.  //如果不是发送给本地的数据包,在网络层就已经被处理,不会传送到传输层来   
  39.     if(skb->pkt_type!=PACKET_HOST)  
  40.     {  
  41.         kfree_skb(skb,FREE_READ);  
  42.         return(0);  
  43.     }  
  44.     
  45.     th = skb->h.th;//获取数据包对应tcp首部  
  46.   
  47.     /* 
  48.      *  Find the socket. 
  49.      */  
  50. //根据tcp首部找到对应的套接字,主要是根据首部里的tcp 四要素,这里是查找最佳匹配的套接字  
  51. //这个套接字既可以是客户端,也可以是服务器端,这个套接字是本地套接字,是该数据包目的接收的套接字,通过目的端口号定位的  
  52.     sk = get_sock(&tcp_prot, th->dest, saddr, th->source, daddr);  
  53.   
  54.     /* 
  55.      *  If this socket has got a reset it's to all intents and purposes  
  56.      *  really dead. Count closed sockets as dead. 
  57.      * 
  58.      *  Note: BSD appears to have a bug here. A 'closed' TCP in BSD 
  59.      *  simply drops data. This seems incorrect as a 'closed' TCP doesn't 
  60.      *  exist so should cause resets as if the port was unreachable. 
  61.      */  
  62.     //本地套接字已经被复位或者已经处于关闭状态,则不可接收该数据包   
  63.     if (sk!=NULL && (sk->zapped || sk->state==TCP_CLOSE))  
  64.         sk=NULL;//用作下面的if判断  
  65.   
  66.     if (!redo) //redo=0,表示这是一个新的数据包,所以需要进行检查其合法性  
  67.     {  
  68.     //计算tcp校验和  
  69.         if (tcp_check(th, len, saddr, daddr ))   
  70.         {  
  71.             skb->sk = NULL;  
  72.             kfree_skb(skb,FREE_READ);  
  73.             /* 
  74.              *  We don't release the socket because it was 
  75.              *  never marked in use. 
  76.              */  
  77.             return(0);  
  78.         }  
  79.         th->seq = ntohl(th->seq);//序列号字节序转换  
  80.   
  81.         /* See if we know about the socket. */  
  82. //检查套接字是否有效,即是否存在,存在又是否已经被复位或关闭  
  83.         if (sk == NULL)//如果上述某种情况是肯定的   
  84.         {  
  85.             /* 
  86.              *  No such TCB. If th->rst is 0 send a reset (checked in tcp_reset) 
  87.              */  
  88.         //本地不提供相关服务,此时回送一个RST数据包,复位对方请求  
  89.         //防止其一再进行数据包的发送,浪费彼此资源  
  90.             tcp_reset(daddr, saddr, th, &tcp_prot, opt,dev,skb->ip_hdr->tos,255);  
  91.             skb->sk = NULL;  
  92.             /* 
  93.              *  Discard frame 
  94.              */  
  95.             kfree_skb(skb, FREE_READ);  
  96.             return(0);  
  97.         }  
  98.     //进入这里表示本地套接字可进行数据包接收  
  99.        //数据包字段设置  
  100.         skb->len = len;//数据部分长度  
  101.         skb->acked = 0;  
  102.         skb->used = 0;  
  103.         skb->free = 0;  
  104.         skb->saddr = daddr;//ip地址设置  
  105.         skb->daddr = saddr;  
  106.       
  107.         /* We may need to add it to the backlog here. */  
  108.         cli();  
  109.         if (sk->inuse) //当前该套接字正在被使用,即当前套接字正忙,无暇处理这里的任务  
  110.         {  
  111.             skb_queue_tail(&sk->back_log, skb);//就将数据包暂存在back_log队列中,稍候由release_sock函数重新接收  
  112.             sti();  
  113.             return(0);  
  114.         }  
  115.         sk->inuse = 1;//否则,加锁,表示该套接字正在这里被使用  
  116.         sti();  
  117.     }  
  118.     else//redo=1,表示该数据包来源于back_log缓存队列  
  119.     {  
  120.         if (sk==NULL) //同样进行检查判断  
  121.         {//回送RST  
  122.             tcp_reset(daddr, saddr, th, &tcp_prot, opt,dev,skb->ip_hdr->tos,255);  
  123.             skb->sk = NULL;  
  124.             kfree_skb(skb, FREE_READ);  
  125.             return(0);  
  126.         }  
  127.     }  
  128.   
  129.  //prot字段是一个proto类型结构变量,表示所使用的传输层协议处理函数集合  
  130.  //在创建套接字时,会根据所使用流类型进行该字段的相应初始化(见socket函数源码,以及UNP V1)  
  131.     if (!sk->prot)   
  132.     {  
  133.         printk("IMPOSSIBLE 3 ");  
  134.         return(0);  
  135.     }  
  136.   
  137.   
  138.     /* 
  139.      *  Charge the memory to the socket.  
  140.      */  
  141. //检查接收缓冲区空余空间,查看剩余空间是否足够接收当前数据包  
  142. //sk->rcvbuf - sk->rmem_alloc =< skb->mem_len  
  143. //最大接收队列的大小 - 已经接收到的 = 还可以接收的大小  
  144.   
  145.     if (sk->rmem_alloc + skb->mem_len >= sk->rcvbuf)   
  146.     {  
  147.     //如果空间不够,则丢弃该数据包,将造成远端超时重发,这正是本地想要的  
  148.     //到时或许就有足够空间接收了  
  149.         kfree_skb(skb, FREE_READ);  
  150.         release_sock(sk);//重新接收  
  151.         return(0);  
  152.     }  
  153.     //如果接收缓冲区空间足够,那么更新已接收缓冲区值  
  154.     skb->sk=sk;  
  155.     sk->rmem_alloc += skb->mem_len;//缓冲区中已经存放的大小  
  156.   
  157.     /* 
  158.      *  This basically follows the flow suggested by RFC793, with the corrections in RFC1122. We 
  159.      *  don't implement precedence and we process URG incorrectly (deliberately so) for BSD bug 
  160.      *  compatibility. We also set up variables more thoroughly [Karn notes in the 
  161.      *  KA9Q code the RFC793 incoming segment rules don't initialise the variables for all paths]. 
  162.      */  
  163.   //不是处于已连接状态,那么该数据包则不是数据传送数据包,是进行三次握手或四次挥手中的某个数据包  
  164.     //下面的操作严格符合TCP三次握手状态转换,对照TCP状态转换图理解  
  165.    
  166.     if(sk->state!=TCP_ESTABLISHED)       /* Skip this lot for normal flow */  
  167.     {  
  168.       
  169.         /* 
  170.          *  Now deal with unusual cases. 
  171.          */  
  172. //如果是处于监听状态,该套接字为服务器端,且等待的是请求连接数据包,而非数据传送数据包  
  173.         if(sk->state==TCP_LISTEN)  
  174.         {  
  175.         //监听套接字只响应连接请求(SYN 数据包),对于其余类型数据包不做负责,  
  176.         //处于TCP_LISTEN 状态的套接字只指示内核应接受指向该套接字的连接请求  
  177. //如果收到的是一个ACK应答数据包,表示这个数据包发错了地方,则回送RST数据包  
  178.             if(th->ack)  /* These use the socket TOS.. might want to be the received TOS */  
  179.                 tcp_reset(daddr,saddr,th,sk->prot,opt,dev,sk->ip_tos, sk->ip_ttl);  
  180.   
  181.             /* 
  182.              *  We don't care for RST, and non SYN are absorbed (old segments) 
  183.              *  Broadcast/multicast SYN isn't allowed. Note - bug if you change the 
  184.              *  netmask on a running connection it can go broadcast. Even Sun's have 
  185.              *  this problem so I'm ignoring it  
  186.              */  
  187.             //同样进行检查数据包类型,以及请求对象地址情况     
  188.             if(th->rst || !th->syn || th->ack || ip_chk_addr(daddr)!=IS_MYADDR)  
  189.             {  
  190.                 kfree_skb(skb, FREE_READ);  
  191.                 release_sock(sk);  
  192.                 return 0;  
  193.             }  
  194.           
  195.             /*   
  196.              *  Guess we need to make a new socket up  
  197.              */  
  198.            //到了这一步,可认定这是一个SYN数据包,表示该数据包是客户端发过来的连接请求   
  199.            //则调用tcp_conn_request 函数对连接请求做出响应  
  200.              
  201. //该函数处理连接请求,主要完成新通信套接字的创建和初始化工作,并且这个请求数据包此后进行的所有工作将由这个新套接字负责  
  202. //具体看下一个函数剖析  
  203.             tcp_conn_request(sk, skb, daddr, saddr, opt, dev, tcp_init_seq());  
  204.           
  205.             /* 
  206.              *  Now we have several options: In theory there is nothing else 
  207.              *  in the frame. KA9Q has an option to send data with the syn, 
  208.              *  BSD accepts data with the syn up to the [to be] advertised window 
  209.              *  and Solaris 2.1 gives you a protocol error. For now we just ignore 
  210.              *  it, that fits the spec precisely and avoids incompatibilities. It 
  211.              *  would be nice in future to drop through and process the data. 
  212.              */  
  213.     //处理back_log队列中先前被缓存的其他连接请求,并做出响应          
  214.             release_sock(sk);  
  215.             return 0;  
  216.         }  
  217.       
  218.         /* retransmitted SYN? */  
  219.         //重发的SYN数据包处理,直接丢弃  
  220.         /*怎么知道这个数据包是重发的呢? 看最后一个判断条件,th->seq+1 == sk->acked_seq; 
  221.     sk->acked_seq,表示本地希望从远端接收的下一个数据的序列号,这是根据上一个数据包的最后一个数据字节的序列号来的, 
  222.         它等于接收到上一个数据包的最后一个数据字节的序列号+1,如果不是重发,那么应该是该数据包的seq == acked_seq 
  223.         现在是 seq+1 == acked_seq,则恰好是已经发送的一个数据包,同一个数据包序列号是一样的 
  224.         */  
  225.         if (sk->state == TCP_SYN_RECV && th->syn && th->seq+1 == sk->acked_seq)  
  226.         {  
  227.             kfree_skb(skb, FREE_READ);  
  228.             release_sock(sk);  
  229.             return 0;  
  230.         }  
  231.           
  232.         /* 
  233.          *  SYN sent means we have to look for a suitable ack and either reset 
  234.          *  for bad matches or go to connected  
  235.          */  
  236. //如果状态是SYN_SENT,处于这种状态的一般是客户端,针对本函数,客户端下一个可能状态为RECV和ESTABLISHED  
  237.     //什么情况下进入某种状态,参见TCP状态转换图  
  238.         if(sk->state==TCP_SYN_SENT)  
  239.         {  
  240.             /* Crossed SYN or previous junk segment */  
  241.             //如果ack置位(前提也要syn置位),那么正常情况下是进入ESTABLISHED状态  
  242.             if(th->ack)//检查确认字段,第二个数据包(第二次握手),syn和ack确认字段都得置位  
  243.             {  
  244.                 /* We got an ack, but it's not a good ack */  
  245.     //调用ack函数处理,这类情况下,如果一切正常,套接字(客户端)状态将置为ESTABLISHED  
  246.     //tcp协议中,三次握手,数据传输,四次挥手,都会有ACK确认数据包来往,  
  247. //这个ack函数处理接收到的ack数据包,整个tcp协议涉及到的ack数据包阶段中的状态转换都会在这个函数中体现  
  248.                 if(!tcp_ack(sk,th,saddr,len))//返回0,表示不正常,下面是非正常情况处理  
  249.                 {  
  250.                     /* Reset the ack - its an ack from a  
  251.                        different connection  [ th->rst is checked in tcp_reset()] */  
  252.                     tcp_statistics.TcpAttemptFails++;  
  253.                     tcp_reset(daddr, saddr, th,  
  254.                         sk->prot, opt,dev,sk->ip_tos,sk->ip_ttl);//回送RST数据包  
  255.                     kfree_skb(skb, FREE_READ);  
  256.                     release_sock(sk);  
  257.                     return(0);  
  258.                 }  
  259.                 if(th->rst)//重置控制位rst置位  
  260.                     return tcp_std_reset(sk,skb);//释放一个传输连接  
  261.                 if(!th->syn)//syn没置位,肯定不行  
  262.                 {  
  263.                     /* A valid ack from a different connection 
  264.                        start. Shouldn't happen but cover it */  
  265.                     kfree_skb(skb, FREE_READ);  
  266.                     release_sock(sk);  
  267.                     return 0;  
  268.                 }  
  269.                 /* 
  270.                  *  Ok.. it's good. Set up sequence numbers and 
  271.                  *  move to established. 
  272.                  */  
  273.                 syn_ok=1;//不要重置(释放)这个连接 /* Don't reset this connection for the syn */  
  274.   
  275.     //客户端接收到服务器端的数据包(SYN+ACK),然后做出确认应答,回送确认数据包  
  276. //这里是三次握手的第二次握手阶段,客户端收到数据包,回送确认数据包让对端建立连接为第三次握手  
  277. //这里sk是套接字,th为数据包的tcp首部,数据包的序列号则是位于tcp首部中,tcp协议提供的是可靠协议  
  278. //其中之一就是序列号,接收是否正确,要看sk的对应序列号与th的序列号是否匹配  
  279.                 sk->acked_seq=th->seq+1;//套接字下一个要接收的数据包的序列号,置为该数据包最后一个序列号+1  
  280.                                         //其实就是该数据包的下一个数据包数据的第一个字节  
  281.                 sk->fin_seq=th->seq;//应答序列号为接收到的该数据包的序列号  
  282.             //发送确认数据包,帮助远端套接字完成连接,内部调用了_queue_xmit函数  
  283.             //下面函数会创建一个确认数据包,且序列号对应  
  284.                 tcp_send_ack(sk->sent_seq,sk->acked_seq,sk,th,sk->daddr);  
  285.                 tcp_set_state(sk, TCP_ESTABLISHED);//然后客户端套接字进入ESTABLISHED状态  
  286.                 tcp_options(sk,th);//更新本地MSS值,告诉对方自己可接收的数据包最大长度  
  287.                 sk->dummy_th.dest=th->source;//获取对方的地址  
  288.                 sk->copied_seq = sk->acked_seq;//本地程序有待读取数据的第一个序列号  
  289.                 if(!sk->dead)  
  290.                 {  
  291.                     sk->state_change(sk);  
  292.                     sock_wake_async(sk->socket, 0);  
  293.                 }  
  294.                 if(sk->max_window==0)//重置最大窗口大小  
  295.                 {  
  296.                     sk->max_window = 32;  
  297.                     sk->mss = min(sk->max_window, sk->mtu);  
  298.                 }  
  299.             }  
  300.             else//ACK标志位没有被设置  
  301.             //即只收到SYN,木有ACK,那就是第二种可能,进入RECV状态(省略了前面的SYN_)  
  302.             {  
  303.     //当客户端在发送 SYN 的同时也收到服务器端的 SYN请求,即两个同时发起连接请求  
  304.                 /* See if SYN's cross. Drop if boring */  
  305.               //首先检查syn标志位  
  306.                 if(th->syn && !th->rst)  
  307.                 {  
  308.                     /* Crossed SYN's are fine - but talking to 
  309.                        yourself is right out... */  
  310.                      //检查是否是自己发送的,不允许自己与自己通信  
  311.                     if(sk->saddr==saddr && sk->daddr==daddr &&  
  312.                         sk->dummy_th.source==th->source &&  
  313.                         sk->dummy_th.dest==th->dest)  
  314.                     {  
  315.                         tcp_statistics.TcpAttemptFails++;  
  316.                         return tcp_std_reset(sk,skb);  
  317.                     }  
  318.             //如果通过了以上检查,表明是合法的,那么客户端就会从 SYN_SENT 转换到 SYN_RECV 状态  
  319.                     tcp_set_state(sk,TCP_SYN_RECV);//这是两者同时打开连接的情况下  
  320.                       
  321.                     /* 
  322.                      *  FIXME: 
  323.                      *  Must send SYN|ACK here 
  324.                      应该在这里发送一个ACK+SYN数据包 
  325.                      */  
  326.                 }         
  327.                 /* Discard junk segment */  
  328.                 kfree_skb(skb, FREE_READ);  
  329.                 release_sock(sk);  
  330.                 return 0;  
  331.             }  
  332.             /* 
  333.              *  SYN_RECV with data maybe.. drop through 
  334.              */  
  335.             goto rfc_step6;  
  336.         }  
  337.   
  338.     /* 
  339.      *  BSD has a funny hack with TIME_WAIT and fast reuse of a port. There is 
  340.      *  a more complex suggestion for fixing these reuse issues in RFC1644 
  341.      *  but not yet ready for general use. Also see RFC1379. 
  342.      */  
  343.       
  344. #define BSD_TIME_WAIT  
  345. #ifdef BSD_TIME_WAIT  
  346. //判断处于2MSL状态的套接字是否接收到一个连接请求,如果条件满足,表示接收到一个具有相同  
  347. //远端地址,远端端口号的连接请求,在处理上是将原来的这个通信套接字释放,而将请求转移给监听套接字  
  348.   
  349.         if (sk->state == TCP_TIME_WAIT && th->syn && sk->dead &&   
  350.             after(th->seq, sk->acked_seq) && !th->rst)  
  351.         {  
  352.             long seq=sk->write_seq;//保存原套接字本地发送序列号最后值  
  353.             if(sk->debug)  
  354.                 printk("Doing a BSD time wait ");  
  355.             tcp_statistics.TcpEstabResets++;         
  356.             sk->rmem_alloc -= skb->mem_len;//接收缓冲区-数据包大小,要关闭连接了,回到解放前  
  357.             skb->sk = NULL;  
  358.             sk->err=ECONNRESET;//被对端释放连接,即对端发送关闭数据包  
  359.             tcp_set_state(sk, TCP_CLOSE);//设置为CLOSE状态  
  360.             sk->shutdown = SHUTDOWN_MASK;//本地关闭,但对端未关闭,所以连接处于半关闭状态  
  361.             release_sock(sk);//如果sk->dead=1,那么该函数执行释放操作,这里是释放套接字  
  362. //经过上面的操作,原先的通信套接字已被搁浅,这里重新得到对应的套接字,  
  363. //由于原先的套接字被设置为CLOSE,所以在get_sock查找时会忽略该套接字,所以这里查找的为监听套接字  
  364. //PS:对于这部分操作不是很理解,就不强行误解了...  
  365.   
  366.             sk=get_sock(&tcp_prot, th->dest, saddr, th->source, daddr);  
  367.             if (sk && sk->state==TCP_LISTEN)//如果是监听套接字  
  368.             {  
  369.                 sk->inuse=1;  
  370.                 skb->sk = sk;  
  371.                 sk->rmem_alloc += skb->mem_len;  
  372.                 //调用conn_request函数创建一个新的通信套接字  
  373.                 tcp_conn_request(sk, skb, daddr, saddr,opt, dev,seq+128000);  
  374.                 release_sock(sk);  
  375.                 return 0;  
  376.             }  
  377.             kfree_skb(skb, FREE_READ);  
  378.             return 0;  
  379.         }  
  380. #endif    
  381.     }  
  382.   
  383.     /* 
  384.      *  We are now in normal data flow (see the step list in the RFC) 
  385.      *  Note most of these are inline now. I'll inline the lot when 
  386.      *  I have time to test it hard and look at what gcc outputs  
  387.      */  
  388.     //检查数据包中数据序列号的合法性  
  389.     if(!tcp_sequence(sk,th,len,opt,saddr,dev))  
  390.     {  
  391.         kfree_skb(skb, FREE_READ);  
  392.         release_sock(sk);  
  393.         return 0;  
  394.     }  
  395.     //这是一个RST数据包  
  396.     if(th->rst)  
  397.         return tcp_std_reset(sk,skb);  
  398.       
  399.     /* 
  400.      *  !syn_ok is effectively the state test in RFC793. 
  401.      */  
  402.     //重置连接  
  403.     if(th->syn && !syn_ok)  
  404.     {  
  405.         tcp_reset(daddr,saddr,th, &tcp_prot, opt, dev, skb->ip_hdr->tos, 255);  
  406.         return tcp_std_reset(sk,skb);     
  407.     }  
  408.   
  409.     /* 
  410.      *  Process the ACK 
  411.      */  
  412.        
  413.     //应答数据包,但应答序列号不合法  
  414.     if(th->ack && !tcp_ack(sk,th,saddr,len))  
  415.     {  
  416.         /* 
  417.          *  Our three way handshake failed. 
  418.          */  
  419.          //如果正处于三次握手连接阶段,则连接建立失败  
  420.         if(sk->state==TCP_SYN_RECV)  
  421.         {  
  422.             tcp_reset(daddr, saddr, th,sk->prot, opt, dev,sk->ip_tos,sk->ip_ttl);  
  423.         }  
  424.         kfree_skb(skb, FREE_READ);  
  425.         release_sock(sk);  
  426.         return 0;  
  427.     }  
  428.       
  429. rfc_step6:  //后面就是数据包中可能的数据处理了  /* I'll clean this up later */  
  430.   
  431.     /* 
  432.      *  Process urgent data 
  433.      */  
  434.     //紧急数据处理      
  435.     if(tcp_urg(sk, th, saddr, len))  
  436.     {  
  437.         kfree_skb(skb, FREE_READ);  
  438.         release_sock(sk);  
  439.         return 0;  
  440.     }  
  441.       
  442.       
  443.     /* 
  444.      *  Process the encapsulated data 
  445.      */  
  446.     //普通数据处理  
  447.     if(tcp_data(skb,sk, saddr, len))  
  448.     {  
  449.         kfree_skb(skb, FREE_READ);  
  450.         release_sock(sk);//这里调用release_sock()函数,然后其内部又调用rcv函数,这样实现数据传输  
  451.         return 0;  
  452.     }  
  453.   
  454.     /* 
  455.      *  And done 
  456.      */   
  457.       
  458.     release_sock(sk);  
  459.     return 0;  
  460. }  

上面函数调用了 tcp_conn_request 用来处理客户端的连接请求。该函数的调用需要满足两个前提条件,一是套接字处于监听状态,二是该数据包是一个SYN数据包,这就相当于是客户端向服务器端发出连接请求,等待服务器端处理。具体实现参见下篇博文accpet 剖析最后

此外,tcp_rcv 内部还调用了 tcp_ack 函数,这些函数比较大,其实 tcp_ack 函数内部实现基本上就是 tcp状态转换,对于进一步理解tcp协议转换很有帮助:

tcp_ack 函数:

tcp_ack 函数用于处理本地(本地既可以是服务器端,也可以是客户端,内核栈没有这两者的概念,所有数据传输函数都是通用,只有本地和远端的概念)接收到的ack数据包。使用tcp协议的套接字。在连接建立完成后,此后发送的每个数据包中ack标志位都被设置为1,所以一个ack数据包本身也将包含数据,但数据部分则由专门的函数处理(tcp_data,tcp_urg),tcp_ack 函数将只对ack 标志位及其相关联字段进行处理。

首先既然是一个ack数据包,则表示本地发送的数据包已经成功被远端接收,这是远端发过来的确认包,则可以对重发队列中已得到ack数据包进行释放。tcp协议会将发送的数据包不立即释放(除非认为设置free标志位,发送后立即释放),而是将其缓存在重发队列中,以防止中间丢弃的问题,如果本地在一定时间内没有收到远端关于该数据包的ack数据包,则认为数据包中间丢弃了,则重新发送该数据包,如果收到了ack包,则释放重发队列中对应的数据包,这就是tcp可靠性之一的超时重传策略。

从远端接受的任何数据包(包括ack数据包)都携带有发送端(远端)的信息,如远端的窗口大小,远端的地址(建立连接时将通过这个数据包设置本地套接字的远端地址信息)等,本地将对此窗口进行检查(对面的接收能力如何),从而决定是否将写队列中的相关数据包发送出去,或者将重发队列中部分数据包重新缓存到写队列中。

如果数据包的交换着重于状态的更新,即该数据包不是单纯的数据传输,而是建立连接或者关闭连接的数据包,那么本地套接字则根据它的当前状态进行相应的更新,收到合法(序列号正确)的ack数据包意味着本地套接字可以进入对应的下一个状态

如果数据报非法,当然非法处置。具体实现细节参见下面源码剖析(有部分本人理解晦涩,没有贴出注释,以免误导)。

  1. /* 
  2.  *  This routine deals with incoming acks, but not outgoing ones. 
  3.  */  
  4.  //处理本地接收到的ack数据包  
  5.  /* 
  6.  sk:本地套接字;th:数据包tcp首部;saddr:源端(发送端)地址;len:数据包数据部分长度 
  7.  */  
  8. extern __inline__ int tcp_ack(struct sock *sk, struct tcphdr *th, unsigned long saddr, int len)  
  9. {  
  10.     unsigned long ack;  
  11.     int flag = 0;  
  12.   
  13.     /*  
  14.      * 1 - there was data in packet as well as ack or new data is sent or  
  15.      *     in shutdown state 
  16.      * 2 - data from retransmit queue was acked and removed 
  17.      * 4 - window shrunk or data from retransmit queue was acked and removed 
  18.      */  
  19. //置位,表示本地套接字之前接收到远端发送的一个RST数据包,所以任何从远端接收到的数据包都简单丢弃  
  20.     if(sk->zapped)  
  21.         return(1);  /* Dead, cant ack any more so why bother */  
  22.   
  23.     /* 
  24.      *  Have we discovered a larger window 
  25.      */  
  26.      //这个数据包是远端发过来的,承载了远端的一些信息  
  27.     ack = ntohl(th->ack_seq);//设置为远端期望从本地接收的下一个字节的序列号  
  28.   
  29.     //窗口大小处理,并更新MSS值,数据包本身已经携带了发送端的窗口大小  
  30.     if (ntohs(th->window) > sk->max_window)   
  31.     {  
  32.         sk->max_window = ntohs(th->window);  
  33. #ifdef CONFIG_INET_PCTCP  
  34.         /* Hack because we don't send partial packets to non SWS 
  35.            handling hosts */  
  36.         sk->mss = min(sk->max_window>>1, sk->mtu);  
  37. #else  
  38.         sk->mss = min(sk->max_window, sk->mtu);  
  39. #endif    
  40.     }  
  41.   
  42.     /* 
  43.      *  We have dropped back to keepalive timeouts. Thus we have 
  44.      *  no retransmits pending. 
  45.      */  
  46. //保活定时器用于双方长时间内暂无数据交换时,进行连接保持,以防止一方崩溃后  
  47.      //另一方始终占用资源的情况发生  
  48.     if (sk->retransmits && sk->ip_xmit_timeout == TIME_KEEPOPEN)  
  49.         sk->retransmits = 0;//重发次数清零  
  50.   
  51.     /* 
  52.      *  If the ack is newer than sent or older than previous acks 
  53.      *  then we can probably ignore it. 
  54.      */  
  55.     //下面after和before函数就是一个大、小比较   
  56. //sent_seq表示将要发送的下一个数据包中第一个字节的序列号  
  57. //rcv_ack_seq表示本地当前为止从远端接收到的最后一个ACK数据包所包含的应答序列号  
  58. //ack设置为远端期望从本地接收的下一个字节的序列号  
  59.     if (after(ack, sk->sent_seq) || before(ack, sk->rcv_ack_seq))   
  60.     {//出现序列号不匹配情况,即传输出现错误(tcp可靠的其中之一就是通过序列号匹配)  
  61.         if(sk->debug)  
  62.             printk("Ack ignored %lu %lu ",ack,sk->sent_seq);  
  63.               
  64.         /* 
  65.          *  Keepalive processing. 
  66.          */  
  67.            
  68.         if (after(ack, sk->sent_seq))   
  69.         {  
  70.             return(0);  
  71.         }  
  72.           
  73.         /* 
  74.          *  Restart the keepalive timer. 
  75.          */  
  76.            
  77.         if (sk->keepopen)   
  78.         {  
  79.             if(sk->ip_xmit_timeout==TIME_KEEPOPEN)  
  80.                 reset_xmit_timer(sk, TIME_KEEPOPEN, TCP_TIMEOUT_LEN);  
  81.         }  
  82.         return(1);  
  83.     }  
  84.   
  85.     /* 
  86.      *  If there is data set flag 1 
  87.      */  
  88.     //len=tcp首部+tcp数据负载,如果len!=tcp首部,表示该数据包携带有数据负载  
  89.     if (len != th->doff*4)   
  90.         flag |= 1;  
  91.   
  92.     /* 
  93.      *  See if our window has been shrunk.  
  94.      */  
  95.    //检查窗口大小是否满足  
  96.     if (after(sk->window_seq, ack+ntohs(th->window)))   
  97.     {  
  98.         /* 
  99.          * We may need to move packets from the send queue 
  100.          * to the write queue, if the window has been shrunk on us. 
  101.          * The RFC says you are not allowed to shrink your window 
  102.          * like this, but if the other end does, you must be able 
  103.          * to deal with it. 
  104.          */  
  105.         struct sk_buff *skb;  
  106.         struct sk_buff *skb2;  
  107.         struct sk_buff *wskb = NULL;  
  108.   
  109.     //从重发队列里面获得一个数据包  
  110.         skb2 = sk->send_head;  
  111.         sk->send_head = NULL;  
  112.         sk->send_tail = NULL;  
  113.       
  114.         /* 
  115.          *  This is an artifact of a flawed concept. We want one 
  116.          *  queue and a smarter send routine when we send all. 
  117.          */  
  118.       
  119.         flag |= 4;  /* Window changed */  
  120.     //改变本地套接字窗口大小  
  121.         sk->window_seq = ack + ntohs(th->window);  
  122.         cli();  
  123.   
  124.     //这段代码的功能就是:遍历整个重发队列,检查每个数据包的序列号,如果超过了本地窗口大小  
  125.     //就把该数据包已送到写队列中  
  126.         while (skb2 != NULL)   
  127.         {  
  128.             skb = skb2;  
  129.             skb2 = skb->link3;  
  130.             skb->link3 = NULL;  
  131.             //检查重发队列中的数据包的序列号是否超过了本地窗口大小  
  132.             if (after(skb->h.seq, sk->window_seq))   
  133.             {//如果超过了,则将该数据包从重发队列移除到写队列中  
  134.                 if (sk->packets_out > 0)   
  135.                     sk->packets_out--;  
  136.                 /* We may need to remove this from the dev send list. */  
  137.                 if (skb->next != NULL)   
  138.                 {  
  139.                     skb_unlink(skb);                  
  140.                 }  
  141.                 /* Now add it to the write_queue. */  
  142.                 if (wskb == NULL)  
  143.                     skb_queue_head(&sk->write_queue,skb);//移动到写队列  
  144.                 else  
  145.                     skb_append(wskb,skb);  
  146.                 wskb = skb;  
  147.             }   
  148.             else   
  149.             {  
  150.                 if (sk->send_head == NULL)   
  151.                 {  
  152.                     sk->send_head = skb;  
  153.                     sk->send_tail = skb;  
  154.                 }  
  155.                 else  
  156.                 {  
  157.                     sk->send_tail->link3 = skb;  
  158.                     sk->send_tail = skb;  
  159.                 }  
  160.                 skb->link3 = NULL;  
  161.             }  
  162.         }  
  163.         sti();  
  164.     }  
  165.   
  166.     /* 
  167.      *  Pipe has emptied 
  168.      */  
  169.     //重发队列为空   
  170.     if (sk->send_tail == NULL || sk->send_head == NULL)   
  171.     {  
  172.         sk->send_head = NULL;  
  173.         sk->send_tail = NULL;  
  174.         sk->packets_out= 0;  
  175.     }  
  176.   
  177.     /* 
  178.      *  Update the right hand window edge of the host 
  179.      */  
  180.      //正式更新窗口大小,前面的更新是属于if判断语句内  
  181.     sk->window_seq = ack + ntohs(th->window);  
  182.   
  183.     /* 
  184.      *  We don't want too many packets out there.  
  185.      */  
  186.     //处理拥塞,就是相应增加该窗口大小,直到达到某个最大值   
  187.     if (sk->ip_xmit_timeout == TIME_WRITE &&   
  188.         sk->cong_window < 2048 && after(ack, sk->rcv_ack_seq))   
  189.     {  
  190.         /*  
  191.          * This is Jacobson's slow start and congestion avoidance.  
  192.          * SIGCOMM '88, p. 328.  Because we keep cong_window in integral 
  193.          * mss's, we can't do cwnd += 1 / cwnd.  Instead, maintain a  
  194.          * counter and increment it once every cwnd times.  It's possible 
  195.          * that this should be done only if sk->retransmits == 0.  I'm 
  196.          * interpreting "new data is acked" as including data that has 
  197.          * been retransmitted but is just now being acked. 
  198.          */  
  199.     //设置拥塞窗口大小:本地最大可同时发送但未得到应答的数据包个数  
  200.         if (sk->cong_window < sk->ssthresh)    
  201.             /*  
  202.              *  In "safe" area, increase 
  203.              */  
  204.             sk->cong_window++;  
  205.         else   
  206.         {  
  207.             /* 
  208.              *  In dangerous area, increase slowly.  In theory this is 
  209.              *      sk->cong_window += 1 / sk->cong_window 
  210.              */  
  211.             if (sk->cong_count >= sk->cong_window)   
  212.             {  
  213.                 sk->cong_window++;  
  214.                 sk->cong_count = 0;  
  215.             }  
  216.             else   
  217.                 sk->cong_count++;  
  218.         }  
  219.     }  
  220.   
  221.     /* 
  222.      *  Remember the highest ack received. 
  223.      */  
  224.        
  225.     sk->rcv_ack_seq = ack;//最近一次接收的数据包的应答序列号更新为远端期望接收到的序列号  
  226.   
  227.     /* 
  228.      *  If this ack opens up a zero window, clear backoff.  It was 
  229.      *  being used to time the probes, and is probably far higher than 
  230.      *  it needs to be for normal retransmission. 
  231.      */  
  232.   //检查数据包是否是一个窗口通报数据包  
  233.     if (sk->ip_xmit_timeout == TIME_PROBE0)   
  234.     {  
  235.         sk->retransmits = 0; /* Our probe was answered */  
  236.           
  237.         /* 
  238.          *  Was it a usable window open ? 
  239.          */  
  240.            
  241.         if (skb_peek(&sk->write_queue) != NULL &&   /* should always be non-null */  
  242.             ! before (sk->window_seq, sk->write_queue.next->h.seq))   
  243.         {  
  244.             sk->backoff = 0;  
  245.               
  246.             /* 
  247.              *  Recompute rto from rtt.  this eliminates any backoff. 
  248.              */  
  249.   
  250.             sk->rto = ((sk->rtt >> 2) + sk->mdev) >> 1;  
  251.             if (sk->rto > 120*HZ)  
  252.                 sk->rto = 120*HZ;  
  253.             if (sk->rto < 20) /* Was 1*HZ, then 1 - turns out we must allow about 
  254.                            .2 of a second because of BSD delayed acks - on a 100Mb/sec link 
  255.                            .2 of a second is going to need huge windows (SIGH) */  
  256.             sk->rto = 20;  
  257.         }  
  258.     }  
  259.   
  260.     /*  
  261.      *  See if we can take anything off of the retransmit queue. 
  262.      */  
  263.    //重发队列  
  264.     while(sk->send_head != NULL)   
  265.     {  
  266.         /* Check for a bug. */  
  267.         //重发队列中的数据包是按序列号进行排序的  
  268.         if (sk->send_head->link3 &&  
  269.             after(sk->send_head->h.seq, sk->send_head->link3->h.seq))   
  270.             printk("INET: tcp.c: *** bug send_list out of order. ");  
  271.               
  272.         /* 
  273.          *  If our packet is before the ack sequence we can 
  274.          *  discard it as it's confirmed to have arrived the other end. 
  275.          */  
  276.            
  277.         if (before(sk->send_head->h.seq, ack+1))   
  278.         {  
  279.             struct sk_buff *oskb;     
  280.             if (sk->retransmits)   
  281.             {     
  282.                 /* 
  283.                  *  We were retransmitting.  don't count this in RTT est  
  284.                  */  
  285.                 flag |= 2;  
  286.   
  287.                 /* 
  288.                  * even though we've gotten an ack, we're still 
  289.                  * retransmitting as long as we're sending from 
  290.                  * the retransmit queue.  Keeping retransmits non-zero 
  291.                  * prevents us from getting new data interspersed with 
  292.                  * retransmissions. 
  293.                  */  
  294.   
  295.                 if (sk->send_head->link3) /* Any more queued retransmits? */  
  296.                     sk->retransmits = 1;  
  297.                 else  
  298.                     sk->retransmits = 0;  
  299.             }  
  300.             /* 
  301.              * Note that we only reset backoff and rto in the 
  302.              * rtt recomputation code.  And that doesn't happen 
  303.              * if there were retransmissions in effect.  So the 
  304.              * first new packet after the retransmissions is 
  305.              * sent with the backoff still in effect.  Not until 
  306.              * we get an ack from a non-retransmitted packet do 
  307.              * we reset the backoff and rto.  This allows us to deal 
  308.              * with a situation where the network delay has increased 
  309.              * suddenly.  I.e. Karn's algorithm. (SIGCOMM '87, p5.) 
  310.              */  
  311.   
  312.             /* 
  313.              *  We have one less packet out there.  
  314.              */  
  315.                
  316.             if (sk->packets_out > 0)   
  317.                 sk->packets_out --;  
  318.             /*  
  319.              *  Wake up the process, it can probably write more.  
  320.              */  
  321.             if (!sk->dead)   
  322.                 sk->write_space(sk);  
  323.             oskb = sk->send_head;  
  324.   
  325.             if (!(flag&2))  /* Not retransmitting */  
  326.             {  
  327.                 long m;  
  328.       
  329.                 /* 
  330.                  *  The following amusing code comes from Jacobson's 
  331.                  *  article in SIGCOMM '88.  Note that rtt and mdev 
  332.                  *  are scaled versions of rtt and mean deviation. 
  333.                  *  This is designed to be as fast as possible  
  334.                  *  m stands for "measurement". 
  335.                  */  
  336.       
  337.                 m = jiffies - oskb->when;  /* RTT */  
  338.                 if(m<=0)  
  339.                     m=1;        /* IS THIS RIGHT FOR <0 ??? */  
  340.                 m -= (sk->rtt >> 3);    /* m is now error in rtt est */  
  341.                 sk->rtt += m;           /* rtt = 7/8 rtt + 1/8 new */  
  342.                 if (m < 0)  
  343.                     m = -m;     /* m is now abs(error) */  
  344.                 m -= (sk->mdev >> 2);   /* similar update on mdev */  
  345.                 sk->mdev += m;           /* mdev = 3/4 mdev + 1/4 new */  
  346.       
  347.                 /* 
  348.                  *  Now update timeout.  Note that this removes any backoff. 
  349.                  */  
  350.                
  351.                 sk->rto = ((sk->rtt >> 2) + sk->mdev) >> 1;  
  352.                 if (sk->rto > 120*HZ)  
  353.                     sk->rto = 120*HZ;  
  354.                 if (sk->rto < 20) /* Was 1*HZ - keep .2 as minimum cos of the BSD delayed acks */  
  355.                     sk->rto = 20;  
  356.                 sk->backoff = 0;  
  357.             }  
  358.             flag |= (2|4);  /* 2 is really more like 'don't adjust the rtt  
  359.                                In this case as we just set it up */  
  360.             cli();  
  361.             oskb = sk->send_head;  
  362.             IS_SKB(oskb);  
  363.             sk->send_head = oskb->link3;  
  364.             if (sk->send_head == NULL)   
  365.             {  
  366.                 sk->send_tail = NULL;  
  367.             }  
  368.   
  369.         /* 
  370.          *  We may need to remove this from the dev send list.  
  371.          */  
  372.   
  373.             if (oskb->next)  
  374.                 skb_unlink(oskb);  
  375.             sti();  
  376.             kfree_skb(oskb, FREE_WRITE); /* write. */  
  377.             if (!sk->dead)   
  378.                 sk->write_space(sk);  
  379.         }  
  380.         else  
  381.         {  
  382.             break;  
  383.         }  
  384.     }  
  385.   
  386.     /* 
  387.      * XXX someone ought to look at this too.. at the moment, if skb_peek() 
  388.      * returns non-NULL, we complete ignore the timer stuff in the else 
  389.      * clause.  We ought to organize the code so that else clause can 
  390.      * (should) be executed regardless, possibly moving the PROBE timer 
  391.      * reset over.  The skb_peek() thing should only move stuff to the 
  392.      * write queue, NOT also manage the timer functions. 
  393.      */  
  394.   
  395.     /* 
  396.      * Maybe we can take some stuff off of the write queue, 
  397.      * and put it onto the xmit queue. 
  398.      */  
  399.      //查看待发送队列中是否缓存有数据包  
  400.     if (skb_peek(&sk->write_queue) != NULL)   
  401.     {  
  402.     //检查序列号是否超出了窗口大小,  
  403.         if (after (sk->window_seq+1, sk->write_queue.next->h.seq) &&  
  404.                 (sk->retransmits == 0 ||   
  405.              sk->ip_xmit_timeout != TIME_WRITE ||  
  406.              before(sk->write_queue.next->h.seq, sk->rcv_ack_seq + 1))  
  407.             && sk->packets_out < sk->cong_window)   
  408.         {  
  409.             /* 
  410.              *  Add more data to the send queue. 
  411.              */  
  412.             flag |= 1;  
  413.             tcp_write_xmit(sk);  
  414.         }  
  415.         else if (before(sk->window_seq, sk->write_queue.next->h.seq) &&  
  416.             sk->send_head == NULL &&  
  417.             sk->ack_backlog == 0 &&  
  418.             sk->state != TCP_TIME_WAIT)   
  419.         {  
  420.             /* 
  421.              *  Data to queue but no room. 
  422.              */  
  423.                 reset_xmit_timer(sk, TIME_PROBE0, sk->rto);  
  424.         }         
  425.     }  
  426.     else  
  427.     {  
  428.         /* 
  429.          * from TIME_WAIT we stay in TIME_WAIT as long as we rx packets 
  430.          * from TCP_CLOSE we don't do anything 
  431.          * 
  432.          * from anything else, if there is write data (or fin) pending, 
  433.          * we use a TIME_WRITE timeout, else if keepalive we reset to 
  434.          * a KEEPALIVE timeout, else we delete the timer. 
  435.          * 
  436.          * We do not set flag for nominal write data, otherwise we may 
  437.          * force a state where we start to write itsy bitsy tidbits 
  438.          * of data. 
  439.          */  
  440.      //不同状态处理  
  441.         switch(sk->state) {  
  442.         case TCP_TIME_WAIT:  
  443.             /* 
  444.              * keep us in TIME_WAIT until we stop getting packets, 
  445.              * reset the timeout. 
  446.              */  
  447.              //重置2MSL定时器  
  448.             reset_msl_timer(sk, TIME_CLOSE, TCP_TIMEWAIT_LEN);  
  449.             break;  
  450.         case TCP_CLOSE:  
  451.             /* 
  452.              * don't touch the timer. 
  453.              */  
  454.             break;  
  455.         default:  
  456.             /* 
  457.              *  Must check send_head, write_queue, and ack_backlog 
  458.              *  to determine which timeout to use. 
  459.              */  
  460.             if (sk->send_head || skb_peek(&sk->write_queue) != NULL || sk->ack_backlog) {  
  461.                 reset_xmit_timer(sk, TIME_WRITE, sk->rto);  
  462.             } else if (sk->keepopen) {  
  463.                 reset_xmit_timer(sk, TIME_KEEPOPEN, TCP_TIMEOUT_LEN);  
  464.             } else {  
  465.                 del_timer(&sk->retransmit_timer);  
  466.                 sk->ip_xmit_timeout = 0;  
  467.             }  
  468.             break;  
  469.         }  
  470.     }  
  471.   
  472.     /* 
  473.      *  We have nothing queued but space to send. Send any partial 
  474.      *  packets immediately (end of Nagle rule application). 
  475.      */  
  476.        
  477.     if (sk->packets_out == 0 && sk->partial != NULL &&  
  478.         skb_peek(&sk->write_queue) == NULL && sk->send_head == NULL)   
  479.     {  
  480.         flag |= 1;  
  481.         tcp_send_partial(sk);  
  482.     }  
  483.   
  484.   
  485.     //下面状态更新,请参考TCP状态转换图理解  
  486.     /* 
  487.      * In the LAST_ACK case, the other end FIN'd us.  We then FIN'd them, and 
  488.      * we are now waiting for an acknowledge to our FIN.  The other end is 
  489.      * already in TIME_WAIT. 
  490.      * 
  491.      * Move to TCP_CLOSE on success. 
  492.      */  
  493.  //远端已经完成关闭操作。进入该状态,表明该套接字为服务器端,且服务器端已经发送FIN数据包,  
  494.  //双方连接的完全关闭只需等待本地(服务器端)接收一个ACK数据包,如果接收到合法的ack包,将进入CLOSE状态,连接完全关闭  
  495.     if (sk->state == TCP_LAST_ACK)   
  496.     {  
  497.         if (!sk->dead)  
  498.             sk->state_change(sk);  
  499.         if(sk->debug)  
  500.             printk("rcv_ack_seq: %lX==%lX, acked_seq: %lX==%lX ",  
  501.                 sk->rcv_ack_seq,sk->write_seq,sk->acked_seq,sk->fin_seq);  
  502.         //检查序列号  
  503.         //rcv_ack_seq前面已被更新为ack(远端期望接收到的数据包第一个字节的序列号)  
  504.         //write_seq表示本地写入的最后一个字节的序列号,二者相等,合法  
  505.         if (sk->rcv_ack_seq == sk->write_seq /*&& sk->acked_seq == sk->fin_seq*/)   
  506.         {  
  507.             flag |= 1;  
  508.             tcp_set_state(sk,TCP_CLOSE);//设置为close状态  
  509.             sk->shutdown = SHUTDOWN_MASK;//本地关闭,至此连接实现完全关闭  
  510.         }  
  511.     }  
  512.   
  513.     /* 
  514.      *  Incoming ACK to a FIN we sent in the case of our initiating the close. 
  515.      * 
  516.      *  Move to FIN_WAIT2 to await a FIN from the other end. Set 
  517.      *  SEND_SHUTDOWN but not RCV_SHUTDOWN as data can still be coming in. 
  518.      */  
  519.      //第一次挥手  
  520.  //本地属于首先关闭的一方,并且已经发送了FIN数据包,正在等待ACK数据包,从而进入TCP_FIN_WAIT2状态  
  521.     if (sk->state == TCP_FIN_WAIT1)   
  522.     {  
  523.   
  524.         if (!sk->dead)   
  525.             sk->state_change(sk);  
  526.         //检查序列号,可靠性  
  527.         if (sk->rcv_ack_seq == sk->write_seq)   
  528.         {  
  529.             flag |= 1;  
  530.             sk->shutdown |= SEND_SHUTDOWN;//本地关闭,处于半关闭状态  
  531.             tcp_set_state(sk, TCP_FIN_WAIT2);//状态转换  
  532.             //进入上述状态后,仍可进行数据包接收(半关闭),但不能再发送数据包  
  533.             //发送FIN表示关闭了发送通道,但其接收通道需要远端进行关闭  
  534.         }  
  535.     }  
  536.   
  537.     /* 
  538.      *  Incoming ACK to a FIN we sent in the case of a simultaneous close. 
  539.      * 
  540.      *  Move to TIME_WAIT 
  541.      */  
  542.  //表示双方同时关闭,即两端同时发起关闭请求  
  543.     if (sk->state == TCP_CLOSING)   
  544.     {  
  545.   
  546.         if (!sk->dead)   
  547.             sk->state_change(sk);  
  548.         if (sk->rcv_ack_seq == sk->write_seq)   
  549.         {  
  550.             flag |= 1;  
  551.             tcp_time_wait(sk);//设置本地套接字进入TIME_WAIT状态,并设置定时器  
  552.         }  
  553.     }  
  554.       
  555.     /* 
  556.      *  Final ack of a three way shake  
  557.      */  
  558.     //三次握手过程  
  559.     //处于SYN_RECV状态表示处于被动打开的一方接收到了远端发送的SYN数据包,  
  560.     //且发送了对应的ACK数据包,现在等待远端回复一个ACK包,即宣告连接建立的完成  
  561.     if(sk->state==TCP_SYN_RECV)  
  562.     {  
  563.     //这里没有检查序列号,因为连接建立之前没有其余数据包到达,  
  564.     //且前面已经判断了这是个有效序列号的应答,所以这里直接处理  
  565.         tcp_set_state(sk, TCP_ESTABLISHED);  
  566.         tcp_options(sk,th);//tcp选项处理,获取MSS值  
  567.         sk->dummy_th.dest=th->source;//建立连接,自然得更新本地套接字的远端地址信息  
  568.         sk->copied_seq = sk->acked_seq;//上层有待读取的数据的序列号,等于通知上层有可用连接  
  569.         if(!sk->dead)  
  570.             sk->state_change(sk);  
  571.         if(sk->max_window==0)  
  572.         {  
  573.             sk->max_window=32;   /* Sanity check */  
  574.             sk->mss=min(sk->max_window,sk->mtu);  
  575.         }  
  576.     }  
  577.       
  578.     /* 
  579.      * I make no guarantees about the first clause in the following 
  580.      * test, i.e. "(!flag) || (flag&4)".  I'm not entirely sure under 
  581.      * what conditions "!flag" would be true.  However I think the rest 
  582.      * of the conditions would prevent that from causing any 
  583.      * unnecessary retransmission.  
  584.      *   Clearly if the first packet has expired it should be  
  585.      * retransmitted.  The other alternative, "flag&2 && retransmits", is 
  586.      * harder to explain:  You have to look carefully at how and when the 
  587.      * timer is set and with what timeout.  The most recent transmission always 
  588.      * sets the timer.  So in general if the most recent thing has timed 
  589.      * out, everything before it has as well.  So we want to go ahead and 
  590.      * retransmit some more.  If we didn't explicitly test for this 
  591.      * condition with "flag&2 && retransmits", chances are "when + rto < jiffies" 
  592.      * would not be true.  If you look at the pattern of timing, you can 
  593.      * show that rto is increased fast enough that the next packet would 
  594.      * almost never be retransmitted immediately.  Then you'd end up 
  595.      * waiting for a timeout to send each packet on the retransmission 
  596.      * queue.  With my implementation of the Karn sampling algorithm, 
  597.      * the timeout would double each time.  The net result is that it would 
  598.      * take a hideous amount of time to recover from a single dropped packet. 
  599.      * It's possible that there should also be a test for TIME_WRITE, but 
  600.      * I think as long as "send_head != NULL" and "retransmit" is on, we've 
  601.      * got to be in real retransmission mode. 
  602.      *   Note that tcp_do_retransmit is called with all==1.  Setting cong_window 
  603.      * back to 1 at the timeout will cause us to send 1, then 2, etc. packets. 
  604.      * As long as no further losses occur, this seems reasonable. 
  605.      */  
  606.     //超时重发  
  607.     if (((!flag) || (flag&4)) && sk->send_head != NULL &&  
  608.            (((flag&2) && sk->retransmits) ||  
  609.            (sk->send_head->when + sk->rto < jiffies)))   
  610.     {  
  611.         if(sk->send_head->when + sk->rto < jiffies)  
  612.             tcp_retransmit(sk,0);     
  613.         else  
  614.         {  
  615.             tcp_do_retransmit(sk, 1);  
  616.             reset_xmit_timer(sk, TIME_WRITE, sk->rto);  
  617.         }  
  618.     }  
  619.   
  620.     return(1);  
  621. }  

为什么有专门的接收到ack数据包处理,而没有专门的接收到syn数据包处理呢?这是因为在数据传输阶段,tcp为确保数据的可靠性传输,通信双方再接收到对方的数据包后,还需要回送一个确认应答数据包,表示已经接收到对端的数据包,对端可以释放重发队列中的数据包了,如果对端一端固定时间后没有收到这边回送的确认数据包,那么远端将开始数据超时重传操作,重发数据包。

数据超时重传和数据确认应答以及对每个传输的字节分配序列号是TCP协议提供可靠性数据传输的核心本质。



原文地址:https://www.cnblogs.com/ztguang/p/12645487.html