当前位置:   article > 正文

linux内核协议栈 UDP之数据报接收过程_udp4_lib_lookup

udp4_lib_lookup

UDP报文接收概述

UDP数据报的接收要分两部分来看:

  1. 网络层接收完数据包后递交给UDP后,UDP的处理过程。该过程UDP需要做的工作就是接收数据包并对其进行校验,校验成功后将其放入接收队列 sk_receive_queue 中等待用户空间程序来读取。
  2. 用户空间程序调用read()等系统调用读取已经放入接收队列 sk_receive_queue 中的数据。

linux内核协议栈 UDP之数据报接收过程

 

从IP层接收数据包 udp_rcv()

该函数是在AF_INET协议族初始化时,由UDP注册给网络层的回调函数,当网络层代码处理完一个输入数据包后,如果该数据包是发往本机的,并且其上层协议就是UDP,那么会调用该回调函数。

  1. int udp_rcv(struct sk_buff *skb)
  2. {
  3. return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
  4. }
  5. @skb: 输入数据包
  6. @udptable:已绑定端口的UDP传输控制块,将从该哈希表查找给skb属于哪个套接字
  7. @proto:L4协议号,到这里可能是IPPROTO_UDP或者IPPROTO_UDPLITE
  8. int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
  9. int proto)
  10. {
  11. struct sock *sk;
  12. struct udphdr *uh;
  13. unsigned short ulen;
  14. struct rtable *rt = skb_rtable(skb);
  15. __be32 saddr, daddr;
  16. struct net *net = dev_net(skb->dev);
  17. /*
  18. * Validate the packet.
  19. */
  20. //调整SKB内部数据布局,使得线性地址空间中至少包含UDP首部
  21. if (!pskb_may_pull(skb, sizeof(struct udphdr)))
  22. goto drop; /* No space for header. */
  23. uh = udp_hdr(skb);
  24. ulen = ntohs(uh->len);
  25. //skb中的数据长度不能小于UDP首部指示的数据包长度,即数据包是完整的
  26. if (ulen > skb->len)
  27. goto short_packet;
  28. if (proto == IPPROTO_UDP) {
  29. //1. UDP数据包长度必须大于首部长度
  30. //2. pskb_trim_rcum()会去掉可能的填充(UDP数据包过小,IP可能会填充),然后重新计算校验和
  31. if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
  32. goto short_packet;
  33. uh = udp_hdr(skb);
  34. }
  35. //计算校验和
  36. if (udp4_csum_init(skb, uh, proto))
  37. goto csum_error;
  38. //获取数据包中的源IP和目的IP地址
  39. saddr = ip_hdr(skb)->saddr;
  40. daddr = ip_hdr(skb)->daddr;
  41. //对于多播或者广播报文的处理
  42. if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
  43. return __udp4_lib_mcast_deliver(net, skb, uh, saddr, daddr, udptable);
  44. //根据报文的源端口号和目的端口号查询udptable,寻找应该接收该数据包的传输控制块
  45. sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
  46. //找到了处理该数据包的传输控制块,调用udp_queue_rcv_skb()接收数据包
  47. if (sk != NULL) {
  48. int ret = udp_queue_rcv_skb(sk, skb);
  49. sock_put(sk);
  50. /* a return value > 0 means to resubmit the input, but
  51. * it wants the return to be -protocol, or 0
  52. */
  53. if (ret > 0)
  54. return -ret;
  55. return 0;
  56. }
  57. //到这里,说明没有传输控制块接收该数据包,做些统计然后丢弃该数据包
  58. //IPSec相关
  59. if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
  60. goto drop;
  61. nf_reset(skb);
  62. /* No socket. Drop packet silently, if checksum is wrong */
  63. if (udp_lib_checksum_complete(skb))
  64. goto csum_error;
  65. //累计输入数据包错误统计值,并且回复端口不可达ICMP报文
  66. UDP_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
  67. icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
  68. /*
  69. * Hmm. We got an UDP packet to a port to which we
  70. * don't wanna listen. Ignore it.
  71. */
  72. kfree_skb(skb);
  73. return 0;
  74. short_packet:
  75. LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
  76. proto == IPPROTO_UDPLITE ? "-Lite" : "",
  77. &saddr,
  78. ntohs(uh->source),
  79. ulen,
  80. skb->len,
  81. &daddr,
  82. ntohs(uh->dest));
  83. goto drop;
  84. csum_error:
  85. /*
  86. * RFC1122: OK. Discards the bad packet silently (as far as
  87. * the network is concerned, anyway) as per 4.1.3.4 (MUST).
  88. */
  89. LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
  90. proto == IPPROTO_UDPLITE ? "-Lite" : "",
  91. &saddr,
  92. ntohs(uh->source),
  93. &daddr,
  94. ntohs(uh->dest),
  95. ulen);
  96. drop:
  97. UDP_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
  98. kfree_skb(skb);
  99. return 0;
  100. }

疑惑:为何校验和的计算和验证要分udp4_csum_init()和udp_lib_checksum_complete()两步完成???

 查找数据包所属套接字 __udp4_lib_lookup_skb()

如上,非常关键的一步就是根据数据包中目的地址信息寻找应该由谁来处理该数据包。

  1. static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
  2. __be16 sport, __be16 dport,
  3. struct udp_table *udptable)
  4. {
  5. struct sock *sk;
  6. const struct iphdr *iph = ip_hdr(skb);
  7. //在网络层可能已经为该数据包查询过传输控制块了,这时会将查询结果记录到skb->sk中
  8. if (unlikely(sk = skb_steal_sock(skb)))
  9. return sk;
  10. else
  11. //之前没有查询过,继续查询
  12. return __udp4_lib_lookup(dev_net(skb_dst(skb)->dev), iph->saddr, sport,
  13. iph->daddr, dport, inet_iif(skb),
  14. udptable);
  15. }
  16. @dif: 该数据包的输入网络设备接口
  17. static struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
  18. __be16 sport, __be32 daddr, __be16 dport,
  19. int dif, struct udp_table *udptable)
  20. {
  21. struct sock *sk, *result;
  22. struct hlist_nulls_node *node;
  23. //目的端口号为哈希表的key
  24. unsigned short hnum = ntohs(dport);
  25. unsigned int hash = udp_hashfn(net, hnum);
  26. struct udp_hslot *hslot = &udptable->hash[hash];
  27. int score, badness;
  28. rcu_read_lock();
  29. begin:
  30. //遍历冲突链,寻找一个分值最高的保存到result中
  31. result = NULL;
  32. badness = -1;
  33. sk_nulls_for_each_rcu(sk, node, &hslot->head) {
  34. score = compute_score(sk, net, saddr, hnum, sport,
  35. daddr, dport, dif);
  36. if (score > badness) {
  37. result = sk;
  38. badness = score;
  39. }
  40. }
  41. /*
  42. * if the nulls value we got at the end of this lookup is
  43. * not the expected one, we must restart lookup.
  44. * We probably met an item that was moved to another chain.
  45. */
  46. if (get_nulls_value(node) != hash)
  47. goto begin;
  48. if (result) {
  49. if (unlikely(!atomic_inc_not_zero(&result->sk_refcnt)))
  50. result = NULL;
  51. else if (unlikely(compute_score(result, net, saddr, hnum, sport,
  52. daddr, dport, dif) < badness)) {
  53. sock_put(result);
  54. goto begin;
  55. }
  56. }
  57. rcu_read_unlock();
  58. return result;
  59. }

疑惑:查个表为什么这么复杂,这个分值什么鬼???

 数据包进入队列 udp_queue_rcv_skb()

找到数据包目的端口对应的传输控制块后,会调用该函数接收该数据包。

  1. /* returns:
  2. * -1: error
  3. * 0: success
  4. * >0: "udp encap" protocol resubmission
  5. *
  6. * Note that in the success and error cases, the skb is assumed to
  7. * have either been requeued or freed.
  8. */
  9. int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  10. {
  11. struct udp_sock *up = udp_sk(sk);
  12. int rc;
  13. int is_udplite = IS_UDPLITE(sk);
  14. //IPSec相关
  15. if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
  16. goto drop;
  17. nf_reset(skb);
  18. //IPSeck相关处理
  19. if (up->encap_type) {
  20. /*
  21. * This is an encapsulation socket so pass the skb to
  22. * the socket's udp_encap_rcv() hook. Otherwise, just
  23. * fall through and pass this up the UDP socket.
  24. * up->encap_rcv() returns the following value:
  25. * =0 if skb was successfully passed to the encap
  26. * handler or was discarded by it.
  27. * >0 if skb should be passed on to UDP.
  28. * <0 if skb should be resubmitted as proto -N
  29. */
  30. /* if we're overly short, let UDP handle it */
  31. if (skb->len > sizeof(struct udphdr) &&
  32. up->encap_rcv != NULL) {
  33. int ret;
  34. ret = (*up->encap_rcv)(sk, skb);
  35. if (ret <= 0) {
  36. UDP_INC_STATS_BH(sock_net(sk),
  37. UDP_MIB_INDATAGRAMS,
  38. is_udplite);
  39. return -ret;
  40. }
  41. }
  42. /* FALLTHROUGH -- it's a UDP Packet */
  43. }
  44. //UDPlite相关处理
  45. if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) {
  46. /*
  47. * MIB statistics other than incrementing the error count are
  48. * disabled for the following two types of errors: these depend
  49. * on the application settings, not on the functioning of the
  50. * protocol stack as such.
  51. *
  52. * RFC 3828 here recommends (sec 3.3): "There should also be a
  53. * way ... to ... at least let the receiving application block
  54. * delivery of packets with coverage values less than a value
  55. * provided by the application."
  56. */
  57. if (up->pcrlen == 0) { /* full coverage was set */
  58. LIMIT_NETDEBUG(KERN_WARNING "UDPLITE: partial coverage "
  59. "%d while full coverage %d requested\n",
  60. UDP_SKB_CB(skb)->cscov, skb->len);
  61. goto drop;
  62. }
  63. /* The next case involves violating the min. coverage requested
  64. * by the receiver. This is subtle: if receiver wants x and x is
  65. * greater than the buffersize/MTU then receiver will complain
  66. * that it wants x while sender emits packets of smaller size y.
  67. * Therefore the above ...()->partial_cov statement is essential.
  68. */
  69. if (UDP_SKB_CB(skb)->cscov < up->pcrlen) {
  70. LIMIT_NETDEBUG(KERN_WARNING
  71. "UDPLITE: coverage %d too small, need min %d\n",
  72. UDP_SKB_CB(skb)->cscov, up->pcrlen);
  73. goto drop;
  74. }
  75. }
  76. //如果设置了套接口过滤器时,那么需要提前进行校验和的处理,保证传给过滤器的数据包一定是校验通过的
  77. if (sk->sk_filter) {
  78. if (udp_lib_checksum_complete(skb))
  79. goto drop;
  80. }
  81. rc = 0;
  82. //锁定socket
  83. bh_lock_sock(sk);
  84. //如果当前没有用户空间程序正在从接收队列接收数据,那么直接将SKB放入到接收队列中即可
  85. if (!sock_owned_by_user(sk))
  86. rc = __udp_queue_rcv_skb(sk, skb);
  87. else
  88. //如果接收队列已经被锁定,那么暂时将数据放入到后备队列中,后备队列中的数据在
  89. //release_sock()中被转移到接收队列中
  90. sk_add_backlog(sk, skb);
  91. bh_unlock_sock(sk);
  92. return rc;
  93. drop:
  94. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  95. kfree_skb(skb);
  96. return -1;
  97. }

 数据包进接收队列 sk_receive_queue

  1. static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  2. {
  3. int is_udplite = IS_UDPLITE(sk);
  4. int rc;
  5. //调用sock_queue_rcv_skb()接收
  6. if ((rc = sock_queue_rcv_skb(sk, skb)) < 0) {
  7. /* Note that an ENOMEM error is charged twice */
  8. if (rc == -ENOMEM) {
  9. //如果由于内存问题导致数据包接收失败,进行统计
  10. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS,
  11. is_udplite);
  12. atomic_inc(&sk->sk_drops);
  13. }
  14. goto drop;
  15. }
  16. return 0;
  17. drop:
  18. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  19. kfree_skb(skb);
  20. return -1;
  21. }
  22. int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  23. {
  24. int err = 0;
  25. int skb_len;
  26. //如果接收该数据包后,占用内存过大,则接收失败
  27. if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
  28. (unsigned)sk->sk_rcvbuf) {
  29. err = -ENOMEM;
  30. goto out;
  31. }
  32. //对于设置了套接字过滤器的调用其过滤器回调,过滤失败直接返回失败
  33. err = sk_filter(sk, skb);
  34. if (err)
  35. goto out;
  36. //进行内存相关的统计,如果内存不足或者超过了接收缓存上限,则接收失败
  37. if (!sk_rmem_schedule(sk, skb->truesize)) {
  38. err = -ENOBUFS;
  39. goto out;
  40. }
  41. skb->dev = NULL;
  42. //输入数据包由该套接字认领
  43. skb_set_owner_r(skb, sk);
  44. /* Cache the SKB length before we tack it onto the receive
  45. * queue. Once it is added it no longer belongs to us and
  46. * may be freed by other threads of control pulling packets
  47. * from the queue.
  48. */
  49. skb_len = skb->len;
  50. //将该SKB加入到接收队列中
  51. skb_queue_tail(&sk->sk_receive_queue, skb);
  52. //调用回调通知可能由于数据不足而block的进程
  53. if (!sock_flag(sk, SOCK_DEAD))
  54. sk->sk_data_ready(sk, skb_len);
  55. out:
  56. return err;
  57. }

 唤醒阻塞进程 sock_def_readable(进接收队列唤醒)

将数据放入接收队列后,需要唤醒那些因为数据不足而阻塞的进程,这是通过上面的sk->sk_data_ready()回调实现的,对于UDP,该函数就是 sock_def_readable。

  1. static void sock_def_readable(struct sock *sk, int len)
  2. {
  3. //先获取读锁
  4. read_lock(&sk->sk_callback_lock);
  5. //如果有正在阻塞的进程,唤醒它们
  6. if (sk_has_sleeper(sk))
  7. wake_up_interruptible_sync_poll(sk->sk_sleep, POLLIN |
  8. POLLRDNORM | POLLRDBAND);
  9. sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
  10. read_unlock(&sk->sk_callback_lock);
  11. }
  12. static inline int sk_has_sleeper(struct sock *sk)
  13. {
  14. /*
  15. * We need to be sure we are in sync with the
  16. * add_wait_queue modifications to the wait queue.
  17. *
  18. * This memory barrier is paired in the sock_poll_wait.
  19. */
  20. smp_mb__after_lock();
  21. //block的进程都阻塞在了sk->sk_sleep等待队列上
  22. return sk->sk_sleep && waitqueue_active(sk->sk_sleep);
  23. }

数据包进后备队列 sk_backlog

在下半部接收时,如果传输控制块已经被进程锁定,那么会先将数据放入到后备队列中,等进程释放传输控制块时再进行处理,这种设计可以使得软中断能够尽快的结束。

  1. /* The per-socket spinlock must be held here. */
  2. //调用该函数时,要确保已经使用自旋锁sk_lock.slock
  3. static inline void sk_add_backlog(struct sock *sk, struct sk_buff *skb)
  4. {
  5. //将skb放入后备队列的末尾
  6. if (!sk->sk_backlog.tail) {
  7. sk->sk_backlog.head = sk->sk_backlog.tail = skb;
  8. } else {
  9. sk->sk_backlog.tail->next = skb;
  10. sk->sk_backlog.tail = skb;
  11. }
  12. skb->next = NULL;
  13. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/252973
推荐阅读
相关标签
  

闽ICP备14008679号